# =============================================================
# telegram_bot/views.py — Webhook (pilnīgi atjaunots)
# =============================================================

import json
import logging

from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from . import handlers

logger = logging.getLogger(__name__)


@csrf_exempt
@require_POST
def telegram_webhook(request, secret_token: str):
    # Drošības pārbaude
    expected = getattr(settings, "TELEGRAM_WEBHOOK_SECRET", None)
    if not expected or secret_token != expected:
        logger.warning("Webhook: nepareizs secret_token!")
        return HttpResponseForbidden("Forbidden")

    try:
        update = json.loads(request.body.decode("utf-8"))
    except json.JSONDecodeError:
        return HttpResponse("Bad Request", status=400)

    try:
        _process_update(update)
    except Exception as e:
        logger.error(f"Webhook kļūda: {e}", exc_info=True)

    return HttpResponse("OK", status=200)


def _process_update(update: dict) -> None:
    if "callback_query" in update:
        _handle_callback(update["callback_query"])
    elif "message" in update:
        _handle_message(update["message"])


def _handle_message(message: dict) -> None:
    chat_id    = message.get("chat", {}).get("id")
    text       = message.get("text", "").strip()
    first_name = message.get("from", {}).get("first_name", "Lietotāj")

    if not chat_id:
        return

    # JA NAV TEKSTA (ir foto, audio vai dokuments), apstrādājam to
    if not text and any(k in message for k in ("photo", "voice", "audio", "document")):
        handlers.handle_media(message, chat_id)
        return

    if not text:
        return

    cmd = text.split()[0].lower() if text.startswith("/") else None

    # ── Komandas ─────────────────────────────────────────────
    if cmd in ("/start",):
        parts = text.split(maxsplit=1)
        payload = parts[1] if len(parts) > 1 else None
        handlers.handle_start(chat_id, first_name, payload)

    elif cmd in ("/komandas", "/help"):
        handlers.handle_komandas(chat_id)

    elif cmd == "/jauns":
        handlers.handle_jauns(chat_id)

    elif cmd == "/ai":
        handlers.handle_topic_command(chat_id, "topic_ai")

    elif cmd in ("/aiakts", "/ai_akts"):
        handlers.handle_topic_command(chat_id, "topic_aiakts")

    elif cmd in ("/drosha", "/drošība", "/security"):
        handlers.handle_topic_command(chat_id, "topic_drosha")

    elif cmd in ("/bizness", "/biznesam"):
        handlers.handle_topic_command(chat_id, "topic_bizness")

    elif cmd in ("/parmums", "/pakalpojumi"):
        handlers.handle_topic_command(chat_id, "topic_parmums")

    elif cmd == "/modeli":
        handlers.handle_modeli(chat_id)

    elif cmd == "/riki":
        handlers.handle_riki(chat_id)

    elif cmd == "/standarti":
        handlers.handle_standarti(chat_id)

    elif cmd == "/portals":
        handlers.handle_portals(chat_id)

    elif cmd == "/status":
        handlers.handle_status(chat_id)

    elif cmd == "/kontakts":
        handlers.handle_contact_start(chat_id)

    # ── Kontakta veidlapa (aktīvs stāvoklis) ─────────────────
    elif handlers.is_in_contact_flow(chat_id):
        handlers.handle_contact_text(chat_id, text)

    # ── /reply komanda — Tiešais Rūteris (Admin atbild klientam) ──
    elif cmd and cmd.startswith("/reply"):
        # Formāts: /reply_123 Teksts vai /reply 123 Teksts
        handlers.handle_mailbox_reply(chat_id, text)

    # ── Gemini — brīvā teksta jautājums ──────────────────────
    else:
        handlers.handle_free_text(chat_id, text)


def _handle_callback(callback_query: dict) -> None:
    callback_id = callback_query.get("id")
    data        = callback_query.get("data", "")
    chat_id     = callback_query.get("message", {}).get("chat", {}).get("id")
    message_id  = callback_query.get("message", {}).get("message_id")
    username    = callback_query.get("from", {}).get("username", "")

    if not chat_id:
        return

    handlers.answer_callback(callback_id)

    # ── Navigācija & Jaunumi ──────────────────────────────────
    if data == "main_menu":
        handlers.handle_main_menu(chat_id, message_id)
    elif data == "prompt_ask":
        handlers.handle_prompt_ask(chat_id, message_id)
    elif data == "news_latest":
        handlers.handle_news(chat_id, message_id)
    elif data == "menu_about":
        handlers._edit_message(chat_id, message_id, handlers.CONTENT["about"], handlers._back_keyboard())
    elif data == "menu_modules":
        handlers._edit_message(chat_id, message_id, handlers.CONTENT["modules"], handlers.get_modules_menu())
    elif data == "menu_web":
        handlers._edit_message(chat_id, message_id, handlers.CONTENT["web"], handlers.get_web_dev_menu())
    elif data == "menu_agents":
        handlers._edit_message(chat_id, message_id, handlers.CONTENT["agents"], handlers.get_agents_menu())

    # ── Dinamiskie Moduļi ─────────────────────────────────────
    elif data.startswith("mod_"):
        mod_text = handlers.MODULE_DETAILS.get(data, "Informācija nav atrasta.")
        markup = {
            "inline_keyboard": [
                [{"text": "✆ Pieteikties šim modulim", "url": "https://mim.lv/kontakti"}],
                [{"text": "↶ Atpakaļ uz moduļiem", "callback_data": "menu_modules"}]
            ]
        }
        handlers._edit_message(chat_id, message_id, mod_text, markup)

    # ── Tēmas (Atpakaļsaderība) ───────────────────────────────
    elif data in ("topic_ai", "topic_aiakts", "topic_drosha", "topic_bizness", "topic_parmums"):
        text = handlers.TOPIC_TEXTS.get(data, "")
        if text:
            handlers._edit_message(chat_id, message_id, text, handlers._back_keyboard())

    # ── Kontakts ──────────────────────────────────────────────
    elif data == "contact_start":
        handlers.handle_contact_start(chat_id, message_id=message_id)
    elif data == "contact_confirm":
        handlers.handle_contact_confirm(chat_id, message_id, username)
    elif data == "contact_cancel":
        handlers.handle_contact_cancel(chat_id, message_id)

    # ── Uzdevumu Apstiprinājums ───────────────────────────────
    elif data.startswith("task_approve_"):
        try:
            task_id = int(data.split("_")[-1])
            handlers.handle_task_approval(chat_id, message_id, task_id)
        except Exception as e:
            logger.error(f"Task approval fails: {e}")

    # ── NPS / Atsauksmju Vērtējumi ────────────────────────────
    elif data.startswith("stars_"):
        try:
            parts = data.split("_")
            zvaigznes = int(parts[1])
            task_id = int(parts[2])
            handlers.handle_nps_rating(chat_id, message_id, zvaigznes, task_id)
        except Exception as e:
            logger.error(f"NPS error: {e}")

    else:
        logger.warning(f"Nezināms callback_data: '{data}'")