# =============================================================
# ai_chat/views.py — Polling Arhitektūra
# =============================================================
# POST /api/ai/chat/         → Saglabā task, sāk Gemini fonā
#                              Atbild UZREIZ ar task_id
# GET  /api/ai/status/<id>/  → Pārbauda vai Gemini jau atbildēja
# =============================================================

import logging
import threading
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status

from .models import AIChatTask

logger = logging.getLogger(__name__)

try:
    from telegram_bot.gemini_client import ask_gemini
    GEMINI_OK = True
except ImportError:
    GEMINI_OK = False
    logger.error("gemini_client nav pieejams!")


def _run_gemini(task_id: str, message: str, history: list):
    """
    Izpildās atsevišķā thread — tāpat kā Telegram webhook!
    Django atbild uzreiz, Gemini strādā fonā.
    """
    try:
        task = AIChatTask.objects.get(id=task_id)
        reply = ask_gemini(message, conversation_history=history)
        task.reply  = reply or "Hmm, saņēmu tukšu atbildi. Mēģini vēlreiz!"
        task.status = AIChatTask.STATUS_DONE
        task.save(update_fields=["reply", "status", "updated_at"])
        logger.info(f"Task {task_id} — pabeigts ({len(reply)} rakstzīmes)")

    except Exception as e:
        logger.error(f"Task {task_id} — Gemini kļūda: {e}")
        try:
            task = AIChatTask.objects.get(id=task_id)
            task.reply  = "⚠️ Kaut kas nogāja greizi. Mēģini vēlreiz!"
            task.status = AIChatTask.STATUS_ERROR
            task.save(update_fields=["reply", "status", "updated_at"])
        except Exception:
            pass


class AIChatView(APIView):
    """
    POST /api/ai/chat/
    Body:     { "message": "...", "history": [...] }
    Atbilde:  { "ok": true, "task_id": "uuid..." }
    — Atbild UZREIZ, Gemini strādā fonā —
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        message = request.data.get("message", "").strip()
        history = request.data.get("history", [])

        if not message:
            return Response(
                {"ok": False, "error": "Ziņa nevar būt tukša."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        if len(message) > 2000:
            return Response(
                {"ok": False, "error": "Ziņa pārāk gara (max 2000)."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        if not GEMINI_OK:
            return Response(
                {"ok": False, "error": "AI_UNAVAILABLE"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE,
            )

        # Validē vēsturi
        clean_history = []
        if isinstance(history, list):
            for item in history[-8:]:
                if isinstance(item, dict) and item.get("role") in ("user", "model"):
                    clean_history.append({
                        "role": item["role"],
                        "text": str(item.get("text", ""))[:500],
                    })

        # Izveido task DB
        task = AIChatTask.objects.create(
            user=request.user,
            message=message,
            status=AIChatTask.STATUS_PENDING,
        )

        # Sāk Gemini atsevišķā thread — NEATBLOĶĒ worker!
        t = threading.Thread(
            target=_run_gemini,
            args=(str(task.id), message, clean_history),
            daemon=True,
        )
        t.start()

        # Atbild UZREIZ — kā Telegram webhook!
        return Response({"ok": True, "task_id": str(task.id)})


class AIChatStatusView(APIView):
    """
    GET /api/ai/status/<task_id>/
    Atbilde:
      { "status": "pending" }          — vēl domā
      { "status": "done", "reply": "..."} — gatavs!
      { "status": "error", "reply": "..."} — kļūda
    """
    permission_classes = [IsAuthenticated]

    def get(self, request, task_id):
        try:
            task = AIChatTask.objects.get(id=task_id, user=request.user)
        except AIChatTask.DoesNotExist:
            return Response(
                {"error": "Task nav atrasts."},
                status=status.HTTP_404_NOT_FOUND,
            )

        return Response({
            "status": task.status,
            "reply":  task.reply if task.status != AIChatTask.STATUS_PENDING else "",
        })