from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.shortcuts import render
from django.http import JsonResponse
import traceback

from qa.ai.semantic import SemanticSearchAI
from qa.ai.detect_kbli import KBLIDetector
from qa.ai.formatter import format_jawaban


# =========================
# UI CHAT
# =========================
def chat_ui(request):
    return render(request, "chat.html")


# =========================
# INISIALISASI GLOBAL (PENTING)
# =========================
ai_engine = SemanticSearchAI()
kbli_detector = KBLIDetector()


# =========================
# API TANYA AI
# =========================
@api_view(["POST"])
def tanya_ai(request):
    try:
        pertanyaan = request.data.get("pertanyaan")
        kbli = request.data.get("kbli")

        if not pertanyaan:
            return Response(
                {"error": "Pertanyaan tidak boleh kosong"},
                status=400
            )

        auto_detect = False

        # Auto-detect KBLI
        if not kbli:
            kbli = kbli_detector.detect(pertanyaan)
            auto_detect = True

        if not kbli:
            return Response(
                {
                    "error": "KBLI tidak dapat dideteksi",
                    "saran": "Mohon sertakan KBLI atau jelaskan jenis usahanya"
                },
                status=400
            )

        # Jalankan semantic search
        results = ai_engine.search(
            query=pertanyaan,
            kbli=kbli
        )

        output = format_jawaban(results, pertanyaan)
        output["kbli"] = kbli
        output["auto_detect"] = auto_detect

        return Response(output)

    except Exception as e:
        # 🔥 WAJIB: supaya JS tidak cuma dapat "gagal"
        traceback.print_exc()
        return JsonResponse(
            {
                "error": "Terjadi kesalahan di server",
                "detail": str(e)
            },
            status=500
        )
