import mysql.connector
from flask import Flask, request, jsonify, render_template, redirect
from flask_cors import CORS
import joblib
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences

app = Flask(__name__)
CORS(app)

# Load model dan tokenizer
model = load_model('model_rnn.h5')  # model Keras
tokenizer = joblib.load('tokenizer.pkl')  # tokenizer hasil joblib dump

# Konstanta padding dan jumlah kata
MAX_SEQUENCE_LENGTH = 50  # Harus sama dengan saat training
sentiment_labels = {
    1: "positif",
    0: "negatif"
}

# Konfigurasi koneksi MySQL
db_config = {
    "host": "localhost",
    "user": "root",
    "password": "",
    "database": "db_tweet"
}

@app.route('/predict', methods=['POST'])
def predict():
    try:
        text = request.form.get('text')
        if not text:
            return jsonify({"error": "No text provided"}), 400

        # Tokenisasi & padding
        seq = tokenizer.texts_to_sequences([text])
        padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)

        # Prediksi
        prediction = model.predict(padded)
        predicted_class = int(np.round(prediction[0][0]))  # misal output sigmoid

        # Ambil label
        sentiment = sentiment_labels.get(predicted_class, "unknown")

        # Simpan ke DB
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor()
        sql = "INSERT INTO `tweet`(`sentimen`, `klasifikasi`) VALUES (%s, %s)"
        cursor.execute(sql, (text, sentiment))
        conn.commit()
        cursor.close()
        conn.close()

        return redirect("/#analisis")

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/', methods=['GET'])
def landing():
    try:
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor(dictionary=True)

        # Ambil data tweet
        cursor.execute("SELECT id, sentimen, klasifikasi FROM tweet ORDER BY id DESC")
        tweets = cursor.fetchall()

        # Ambil data preprocessing
        cursor.execute("""
            SELECT id, clean_text, tokens, normalized_tokens, filtered_tokens, stemmed_tokens 
            FROM preprocessing 
            ORDER BY id DESC
        """)
        preprocessing_data = cursor.fetchall()

        cursor.close()
        conn.close()

        return render_template('index.html', tweets=tweets, preprocessing_data=preprocessing_data)

    except mysql.connector.Error as err:
        print(f"Error: {err}")
        return "Terjadi kesalahan pada database", 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
