from flask import Blueprint, request, jsonify
from modules.rest.security import rest_auth_required
from modules.chat.service import answer_question  # reutiliza lógica

rest_bp = Blueprint("rest", __name__, url_prefix="/rest")


import json

@rest_bp.route("/chat", methods=["POST"])
@rest_auth_required
def rest_chat():
    data = request.get_json(force=True) or {}

    question = (data.get("question") or "").strip()
    if not question:
        return jsonify({"error": "question required"}), 400

    raw_result = answer_question(question)

    try:
        parsed = json.loads(raw_result)
    except Exception:
        return jsonify({
            "error": "invalid LLM response",
            "raw": raw_result
        }), 500

    return json.dumps(parsed)