from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

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")


@csrf_exempt
@api_view(["POST"])
def tanya_ai(request):
    ai_engine = SemanticSearchAI()
    kbli_detector = KBLIDetector()

    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

    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)
