from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.shortcuts import render

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


def chat_ui(request):
    return render(request, "chat.html")


# 🔒 Lazy loader (AMAN UNTUK PASSENGER)
_ai_engine = None
_kbli_detector = None


def get_ai_engine():
    global _ai_engine
    if _ai_engine is None:
        _ai_engine = SemanticSearchAI()
    return _ai_engine


def get_kbli_detector():
    global _kbli_detector
    if _kbli_detector is None:
        _kbli_detector = KBLIDetector()
    return _kbli_detector


@api_view(["POST"])
def tanya_ai(request):
    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

    # 🔹 Ambil instance SAAT DIPERLUKAN
    kbli_detector = get_kbli_detector()
    ai_engine = get_ai_engine()

    if not kbli:
        kbli = kbli_detector.detect(pertanyaan)
        auto_detect = True

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

    results = ai_engine.search(
        query=pertanyaan,
        kbli=kbli
    )

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

    return Response(output)
