# =============================================================
# ai_chat/views.py — VIENKĀRŠĀ VERSIJA v2.0
# =============================================================
# IEPRIEKŠĒJĀ PROBLĒMA:
#   threading.Thread + DB polling = nestabils cPanel vidē.
#   Frontend gaidīja task_id, tad polling-oja — lapa uzkarājās.
#
# JAUNAIS RISINĀJUMS:
#   POST /api/ai/chat/ → ask_gemini() sinhroni → atgriež reply
#   Nekāda DB. Nekādi thread. Nekādi polling.
#   ask_gemini() pati ir ātra (~2-5 sek) — vienkārši gaidam.
# =============================================================

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

logger = logging.getLogger(__name__)

# Importējam Gemini klientu no Telegram bota mapes
try:
    from telegram_bot.gemini_client import ask_gemini
    GEMINI_OK = True
except ImportError:
    GEMINI_OK = False
    logger.error("gemini_client nav pieejams! Pārbaudi telegram_bot/gemini_client.py")


class AIChatView(APIView):
    """
    POST /api/ai/chat/
    Body:    { "message": "...", "history": [...] }
    Atbilde: { "reply": "Mikas atbilde..." }

    Sinhroni izsauc ask_gemini() un atgriež atbildi uzreiz.
    Nav DB. Nav threading. Nav polling.
    """
    permission_classes = [IsAuthenticated]

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

        # ── Validācija ───────────────────────────────────────────
        if not message:
            return Response(
                {"error": "Ziņa nevar būt tukša."},
                status=status.HTTP_400_BAD_REQUEST,
            )

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

        if not GEMINI_OK:
            return Response(
                {"error": "AI_UNAVAILABLE: gemini_client nav pieejams."},
                status=status.HTTP_503_SERVICE_UNAVAILABLE,
            )

        # ── Sarunu vēstures attīrīšana ───────────────────────────
        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],
                    })

        # ── Gemini izsaukums (sinhroni) ──────────────────────────
        try:
            reply = ask_gemini(message, conversation_history=clean_history)
            return Response({"reply": reply})

        except Exception as e:
            logger.error(f"AIChatView kļūda: {e}")
            return Response(
                {"error": f"Servera kļūda: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )
