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


def extract_kbli_from_text(text):
    """
    Ambil KBLI 5 digit dari teks.
    Contoh: 'kbli 55120' -> '55120'
    """
    if not text:
        return None
    match = re.search(r"\b\d{5}\b", text)
    return match.group(0) if match else None


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

        # 🔒 PRIORITAS 1: KBLI eksplisit dari teks user
        kbli_from_text = extract_kbli_from_text(pertanyaan)
        if kbli_from_text:
            kbli = kbli_from_text
            auto_detect = False
        else:
            # 🔍 PRIORITAS 2: detector (jika user tidak menyebut KBLI)
            if not kbli:
                kbli = kbli_detector.detect(pertanyaan)
                auto_detect = True

        if not kbli:
            return Response(
                {
                    "error": "KBLI tidak dapat ditentukan",
                    "saran": "Sertakan KBLI (5 digit) atau jelaskan jenis usahanya"
                },
                status=400
            )

        # 🧠 Ambil BAHAN regulasi
        results = ai_engine.search(
            query=pertanyaan,
            kbli=kbli,
            top_n=5
        )

        if not results:
            return Response(
                {
                    "jawaban": (
                        f"Tidak ditemukan ketentuan Permenpar No. 6 Tahun 2025 "
                        f"yang relevan untuk KBLI {kbli}."
                    ),
                    "kbli": kbli,
                    "auto_detect": auto_detect,
                    "referensi": []
                }
            )

        # ✨ FORMAT JAWABAN (KEMENTERIAN)
        output = format_jawaban(
            bahan_regulasi=results,
            pertanyaan=pertanyaan,
            kbli=kbli
        )

        output["kbli"] = kbli
        output["auto_detect"] = auto_detect
        output["jumlah_pasal"] = len(results)

        return Response(output)

    except Exception as e:
        return Response(
            {
                "error": "Terjadi kesalahan di backend",
                "detail": str(e)
            },
            status=500
        )
