from flask import Flask, request, jsonify, render_template_string, session, redirect, url_for
import json
import os
from functools import wraps
from src.data_ingestion import ingest_data
from src.question_generation import QuestionGenerator
from src.grading import Grader

# ==================== CONFIGURAÇÃO ====================
CONFIG_FILE = os.path.join(os.path.dirname(__file__), "config.json")

def load_config():
    try:
        with open(CONFIG_FILE, "r") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return {}

config = load_config()
APP_PASSWORD = config.get("app_password")
SECRET_KEY = config.get("secret_key") or os.urandom(32)

# Inicializar app Flask
app = Flask(__name__)
app.secret_key = SECRET_KEY

# ==================== AUTENTICAÇÃO ====================
def login_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not session.get("authenticated"):
            return redirect(url_for("login", next=request.path))
        return f(*args, **kwargs)
    return wrapper

@app.route("/login", methods=["GET", "POST"])
def login():
    global APP_PASSWORD
    # Sempre recarrega o config.json, para suportar troca de senha sem reiniciar o app
    config = load_config()
    APP_PASSWORD = config.get("app_password")
    error = None

    if request.method == "POST":
        senha_digitada = request.form.get("password", "")
        if APP_PASSWORD and senha_digitada == APP_PASSWORD:
            session["authenticated"] = True
            return redirect(request.args.get("next") or url_for("index"))
        error = "Senha incorreta. Tente novamente."

    return render_template_string("""
    <!doctype html><html lang="pt"><head><meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Entrar</title>
    <style>
      body{font-family:Arial,sans-serif;background:#f5f5f5;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
      .card{background:#fff;padding:24px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,.1);width:100%;max-width:360px}
      h1{font-size:20px;margin:0 0 12px;text-align:center}.err{color:#b00020;margin:8px 0}
      input[type=password]{width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;margin:8px 0 12px}
      button{width:100%;padding:10px;border:0;border-radius:6px;background:#007bff;color:#fff;cursor:pointer}
      button:hover{background:#0056b3}
    </style></head><body><div class="card">
      <h1>Acesso restrito</h1>
      {% if error %}<div class="err">{{error}}</div>{% endif %}
      <form method="POST">
        <input type="password" name="password" placeholder="Digite a senha" autofocus required>
        <button type="submit">Entrar</button>
      </form>
    </div></body></html>
    """, error=error)

@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))

# ==================== INICIALIZAR COMPONENTES ====================
try:
    question_generator = QuestionGenerator()
except ValueError as e:
    print(f"Warning: {e}")
    question_generator = None

grader = Grader()

# ==================== PÁGINA INICIAL PROTEGIDA ====================
@app.route('/')
@login_required
def index():
    return render_template_string("""
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Auto-Avaliação</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .section h2 {
            color: #555;
            margin-top: 0;
        }
        textarea, input[type="text"], select {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        .question-display {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .feedback {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Sistema de Auto-Avaliação</h1>
        
        <div class="section">
            <h2>1. Gerar Perguntas</h2>
            <textarea id="textContent" placeholder="Inserir o conteúdo do texto para gerar perguntas..." rows="6"></textarea>
            <select id="questionType">
                <option value="multiple_choice">Opção Múltiple</option>
                <option value="true_false">Verdadeiro/Falso</option>
            </select>
            <select id="difficulty">
                <option value="easy">Fácil</option>
                <option value="medium">Medio</option>
                <option value="hard">Difícil</option>
            </select>
            <button onclick="generateQuestion()">Gerar Pergunta</button>
            <div id="questionResult" class="result" style="display:none;"></div>
        </div>

        <div class="section">
            <h2>2. Responder Pergunta</h2>
            <div id="questionDisplay" class="question-display" style="display:none;"></div>
            <input type="text" id="studentAnswer" placeholder="Tu respuesta..." style="display:none;">
            <button id="submitAnswer" onclick="submitAnswer()" style="display:none;">Enviar Resposta</button>
            <div id="gradingResult" class="result" style="display:none;"></div>
        </div>
    </div>

    <script>
        let currentQuestion = null;

        async function generateQuestion() {
            const textContent = document.getElementById('textContent').value;
            const questionType = document.getElementById('questionType').value;
            const difficulty = document.getElementById('difficulty').value;

            if (!textContent.trim()) {
                alert('Faz favor, insertar conteúdo do texto.');
                return;
            }

            try {
                const response = await fetch('/generate_question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text_content: textContent,
                        question_type: questionType,
                        difficulty: difficulty
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    currentQuestion = result.question;
                    displayQuestion(result.question);
                    document.getElementById('questionResult').style.display = 'block';
                    document.getElementById('questionResult').innerHTML = '<strong>¡Pergunta gerada com Sucesso!</strong>';
                } else {
                    document.getElementById('questionResult').style.display = 'block';
                    document.getElementById('questionResult').innerHTML = '<strong>Error:</strong> ' + result.error;
                }
            } catch (error) {
                document.getElementById('questionResult').style.display = 'block';
                document.getElementById('questionResult').innerHTML = '<strong>Error:</strong> ' + error.message;
            }
        }

        function displayQuestion(question) {
            const questionDisplay = document.getElementById('questionDisplay');
            const studentAnswer = document.getElementById('studentAnswer');
            const submitButton = document.getElementById('submitAnswer');

            let html = '<h3>' + question.question + '</h3>';
            
            if (question.type === 'multiple_choice' && question.options) {
                html += '<div>';
                question.options.forEach((option, index) => {
                    const letter = String.fromCharCode(65 + index);
                    html += '<div><strong>' + letter + ')</strong> ' + option + '</div>';
                });
                html += '</div>';
                studentAnswer.placeholder = 'Inserir conteúdo de: A, B, C o D';
            } else if (question.type === 'true_false') {
                studentAnswer.placeholder = 'Ingresa Verdadero o Falso';
            }

            questionDisplay.innerHTML = html;
            questionDisplay.style.display = 'block';
            studentAnswer.style.display = 'block';
            submitButton.style.display = 'block';
            
            studentAnswer.value = '';
            document.getElementById('gradingResult').style.display = 'none';
        }

        async function submitAnswer() {
            const studentAnswer = document.getElementById('studentAnswer').value;

            if (!studentAnswer.trim()) {
                alert('Faz favor, inserir sua resposta.');
                return;
            }

            if (!currentQuestion) {
                alert('Não há pergunta para avaliar.');
                return;
            }

            try {
                const response = await fetch('/grade_question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        question: currentQuestion,
                        student_answer: studentAnswer
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    const gradingResult = document.getElementById('gradingResult');
                    const feedbackClass = result.grading.is_correct ? 'correct' : 'incorrect';
                    gradingResult.innerHTML = '<div class="feedback ' + feedbackClass + '">' + result.grading.feedback + '</div>';
                    gradingResult.style.display = 'block';
                } else {
                    document.getElementById('gradingResult').innerHTML = '<strong>Error:</strong> ' + result.error;
                    document.getElementById('gradingResult').style.display = 'block';
                }
            } catch (error) {
                document.getElementById('gradingResult').innerHTML = '<strong>Error:</strong> ' + error.message;
                document.getElementById('gradingResult').style.display = 'block';
            }
        }
    </script>
</body>
</html>
    """)

# ==================== ROTAS PARA API ====================
@app.route('/generate_question', methods=['POST'])
def generate_question():
    try:
        data = request.json
        text_content = data.get('text_content')
        question_type = data.get('question_type', 'multiple_choice')
        difficulty = data.get('difficulty', 'medium')

        if not text_content:
            return jsonify({'success': False, 'error': 'Text content is required'})

        if question_generator is None:
            return jsonify({'success': False, 'error': 'Question generator not available. Please set OPENAI_API_KEY environment variable.'})

        question_json = question_generator.generate_question(text_content, question_type, difficulty)
        
        if question_json:
            question_data = json.loads(question_json)
            return jsonify({'success': True, 'question': question_data})
        else:
            return jsonify({'success': False, 'error': 'Failed to generate question'})

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/grade_question', methods=['POST'])
def grade_question():
    try:
        data = request.json
        question = data.get('question')
        student_answer = data.get('student_answer')

        if not question or not student_answer:
            return jsonify({'success': False, 'error': 'Question and student answer are required'})

        grading_result = grader.grade_question(question, student_answer)
        return jsonify({'success': True, 'grading': grading_result})

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

# ==================== EXECUÇÃO ====================
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

