# =============================================================
# telegram_bot/handlers.py — MIM / Miks AI Asistents
# =============================================================

import logging
import requests
import json
import os
from collections import defaultdict
from django.conf import settings
from .gemini_client import ask_gemini

logger = logging.getLogger(__name__)

# Sarunu vēsture LLM vajadzībām
_conversation_history: dict = defaultdict(list)
MAX_HISTORY = 10

def _add_to_history(chat_id: int, role: str, text: str) -> None:
    history = _conversation_history[chat_id]
    history.append({"role": role, "text": text})
    if len(history) > MAX_HISTORY:
        _conversation_history[chat_id] = history[-MAX_HISTORY:]

def _get_history(chat_id: int) -> list:
    return list(_conversation_history.get(chat_id, []))

def _clear_history(chat_id: int) -> None:
    _conversation_history.pop(chat_id, None)

# ── TELEGRAM API BĀZE ─────────────────────────────────────────
def _token() -> str:
    return settings.TELEGRAM_BOT_TOKEN

def send_message(chat_id: int, text: str, reply_markup: dict = None) -> bool:
    url = f"https://api.telegram.org/bot{_token()}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "Markdown",
        "disable_web_page_preview": True,
    }
    if reply_markup:
        payload["reply_markup"] = reply_markup
    try:
        resp = requests.post(url, json=payload, timeout=10)
        resp.raise_for_status()
        return True
    except Exception as e:
        logger.error(f"send_message kļūda: {e}")
        return False

def send_telegram_document(chat_id: int, file_path: str) -> bool:
    url = f"https://api.telegram.org/bot{_token()}/sendDocument"
    try:
        with open(file_path, 'rb') as f:
            resp = requests.post(url, data={"chat_id": chat_id}, files={"document": f}, timeout=15)
            resp.raise_for_status()
            return True
    except Exception as e:
        logger.error(f"send_telegram_document kļūda: {e}")
        return False

def send_typing_action(chat_id: int) -> None:
    try:
        requests.post(
            f"https://api.telegram.org/bot{_token()}/sendChatAction",
            json={"chat_id": chat_id, "action": "typing"},
            timeout=5,
        )
    except Exception:
        pass

def answer_callback(callback_query_id: str) -> None:
    try:
        requests.post(
            f"https://api.telegram.org/bot{_token()}/answerCallbackQuery",
            json={"callback_query_id": callback_query_id},
            timeout=5,
        )
    except Exception:
        pass

def _edit_message(chat_id: int, message_id: int, text: str, reply_markup: dict = None) -> None:
    payload = {
        "chat_id": chat_id,
        "message_id": message_id,
        "text": text,
        "parse_mode": "Markdown",
        "disable_web_page_preview": True,
    }
    if reply_markup is not None:
        payload["reply_markup"] = reply_markup
    try:
        requests.post(
            f"https://api.telegram.org/bot{_token()}/editMessageText",
            json=payload,
            timeout=10,
        )
    except Exception as e:
        logger.error(f"editMessageText kļūda: {e}")

# ── SATURS UN TEKSTI ──────────────────────────────────────────
CONTENT = {
    "welcome": (
        "⟁ *Tavs Mākslīgā Intelekta Menedžeris*\n"
        "─────────────────────────\n\n"
        "Sveicināti! Es esmu *Miks* — MIM aģentūras AI asistents.\n\n"
        "🚀 Mēs palīdzam uzņēmumiem un privātpersonām integrēt MI tehnoloģijas darbā un ikdienā.\n\n"
        "💡 _Izvēlies sadaļu vai vienkārši uzdod man jautājumu!_"
    ),
    "about": (
        "🚀 *M I M  —  AI Aģentūra*\n"
        "─────────────────────────\n\n"
        "Latvijas IT uzņēmums, kas specializējas *mākslīgā intelekta* risinājumu un *web platformu* izstrādē.\n\n"
        "📋 *Pakalpojumi un orientējošās cenas:*\n\n"
        "🤖 *AI Čatboti un Asistenti*\n"
        "└ No €90 · Gatavs 1-2 nedēļās\n\n"
        "💻 *Web / Aplikāciju Izstrāde*\n"
        "└ No €100 · Gatavs 2-6 nedēļās\n\n"
        "⚡ *Procesu Automatizācija*\n"
        "└ No €120 · Gatavs 1-3 nedēļās\n\n"
        "💡 *AI Konsultācija (1-pret-1)*\n"
        "└ No €20 · Gatavs 1 nedēļā\n\n"
        "🧠 *Personīgais AI Asistents*\n"
        "└ No €59 · Gatavs 2-3 nedēļās\n\n"
        "─────────────────────────\n"
        "💎 *Kāpēc MIM?*\n"
        "⚡ Ātrums · 🇱🇻 Vietējais tirgus · 🔒 ES AI Akts\n\n"
        "🌐 [mim.lv](https://mim.lv) · 📧 info@mim.lv"
    ),
    "modules": (
        "⬢ *MI Izziņas Moduļi*\n"
        "─────────────────────────\n\n"
        "Praktiski moduļi cilvēkiem, kas vēlas *saprast un izmantot* MI ikdienā.\n"
        "Nav ilgu kursu — tikai *praktiski rīki* un rezultāts.\n\n"
        "⎋ _Izvēlies moduli detalizētai info:_"
    ),
    "web": (
        "⌘ *Premium Web Izstrāde*\n"
        "─────────────────────────\n\n"
        "Zibensātras mājaslapas *bez sākotnējās izstrādes maksas*.\n"
        "Tu maksā tikai fiksētu ikmēneša uzturēšanas maksu.\n\n"
        "⟡ *Bāzes Plāns* — 49€/mēn\n"
        "└ React.js, SSL, mobilais, SEO, dizains\n\n"
        "◈ *Premium Plāns* — 79€/mēn\n"
        "└ Viss iepriekšējais + AI čatbots, animācijas, analītika\n\n"
        "_Izstrāde ir BEZMAKSAS — tu sāc maksāt tikai, kad lapa ir gatava!_"
    ),
    "agents": (
        "⚡︎ *AI Aģenti — Autonoma Automatizācija*\n"
        "─────────────────────────\n\n"
        "◬ *OpenClaw Aģents*\n"
        "└ Autonoms robots (cron jobs). Apstrādā e-pastus, YouTube, dokumentus.\n\n"
        "⍟ *Antigravity Aģents*\n"
        "└ Koda redaktors ar iebūvētu AI — raksta, testē un deploijē kodu.\n\n"
        "_Abi aģenti darbojas lokāli tavā infrastruktūrā — pilna datu kontrole._"
    )
}

MODULE_DETAILS = {
    "mod_1": "▤ *Modulis 1: Teksta un Satura Ģenerēšana*\nApgūsti ChatGPT/Gemini, lai ātri radītu tekstus ikdienas vajadzībām.",
    "mod_2": "⌕ *Modulis 2: SEO un Satura Optimizācija*\nIzmanto MI, lai uzlabotu lapas redzamību Google meklētājā.",
    "mod_3": "◧ *Modulis 3: Vizuālā Satura Radīšana*\nSaproti attēlu ģenerēšanu (DALL-E, Midjourney, Canva).",
    "mod_4": "⎍ *Modulis 4: MI Sociālajiem Tīkliem un Reklāmām*\nAutomatizē savu klātbūtni sociālajos tīklos un uzlabo konversijas.",
    "mod_5": "⚙ *Modulis 5: Procesu Automatizācija un Dati*\nAtbrīvojies no rutīnas darbiem, izmantojot viedus skriptus.",
    "mod_6": "💻 *Modulis 6: IT un Programmēšanas Pamati*\nIegūsti fundamentālas zināšanas veiksmīgai karjerai tehnoloģiju nozarē.",
    "mod_7": "◬ *Modulis 7: OpenClaw Aģenta Izbūve*\nApgūsti autonoma AI robota izveidi (e-pasti, YouTube, dokumenti).",
    "mod_8": "⍟ *Modulis 8: Antigravity Vides Uzstādīšana*\nSaproti, kā integrēt AI tieši savā koda redaktorā un terminālī."
}

# ── ZINĀŠANU BĀZES FAILU KARTĒJUMS ────────────────────────────
TOPIC_FILES = {
    "topic_ai": "ai_tehnologijas.md",
    "topic_aiakts": "es_ai_akts.md",
    "topic_drosha": "ai_drosha_un_etika.md",
    "topic_bizness": "ai_biznesam.md",
    "topic_parmums": "par_mums.md"
}

# ── TASTATŪRAS UN IZVĒLNES ────────────────────────────────────
def _main_menu_keyboard() -> dict:
    portal = getattr(settings, "PORTAL_URL", "https://mim.lv/portals")
    return {
        "inline_keyboard": [
            [
                {"text": "🚀 Par MIM (Cenas & Info)", "callback_data": "menu_about"}
            ],
            [
                {"text": "⬢ MI Izziņas Moduļi", "callback_data": "menu_modules"},
                {"text": "⌘ Web Izstrāde", "callback_data": "menu_web"}
            ],
            [
                {"text": "⚡︎ AI Aģenti (Lokāli)", "callback_data": "menu_agents"},
                {"text": "◷ Uzzināt jaunumus", "callback_data": "news_latest"}
            ],
            [
                {"text": "✍️ Jautāt AI Miksam", "callback_data": "prompt_ask"},
                {"text": "✆ Pieteikties (Portālā)", "url": "https://mim.lv/portals"}
            ],
            [
                {"text": "⎋ Atvērt Klientu Portālu", "url": portal}
            ]
        ]
    }

def get_modules_menu() -> dict:
    keyboard = []
    for i in range(1, 9, 2):
        keyboard.append([
            {"text": f"Modulis {i}", "callback_data": f"mod_{i}"},
            {"text": f"Modulis {i+1}", "callback_data": f"mod_{i+1}"}
        ])
    keyboard.append([{"text": "✆ Sastādīt programmu", "url": "https://mim.lv/kontakti"}])
    keyboard.append([{"text": "↶ Galvenā izvēlne", "callback_data": "main_menu"}])
    return {"inline_keyboard": keyboard}

def get_web_dev_menu() -> dict:
    return {
        "inline_keyboard": [
            [{"text": "⟡ Pasūtīt Bāzes Plānu", "url": "https://mim.lv/kontakti"}],
            [{"text": "◈ Pasūtīt Premium Plānu", "url": "https://mim.lv/kontakti"}],
            [{"text": "↶ Galvenā izvēlne", "callback_data": "main_menu"}]
        ]
    }

def get_agents_menu() -> dict:
    return {
        "inline_keyboard": [
            [{"text": "✆ Pieteikties aģenta integrācijai", "url": "https://mim.lv/portals"}],
            [{"text": "↶ Galvenā izvēlne", "callback_data": "main_menu"}]
        ]
    }

def _after_answer_keyboard() -> dict:
    return {
        "inline_keyboard": [
            [
                {"text": "❓ Vēl jautājums",  "callback_data": "prompt_ask"},
                {"text": "↶ Galvenā izvēlne", "callback_data": "main_menu"}
            ]
        ]
    }

def _back_keyboard() -> dict:
    return {"inline_keyboard": [[{"text": "↶ Galvenā izvēlne", "callback_data": "main_menu"}]]}

# ── KOMANDU UN IZVĒLNES APSTRĀDE ──────────────────────────────
def link_account(chat_id: int, code: str):
    from django.contrib.auth import get_user_model
    User = get_user_model()
    try:
        user = User.objects.get(telegram_link_code=code)
        user.telegram_id = chat_id
        user.save()
        send_message(chat_id, f"✅ Tavs konts veiksmīgi saistīts ar portālu: {user.email}")
    except User.DoesNotExist:
        send_message(chat_id, "❌ Kļūme: Nederīgs pieslēgšanās kods.")
    except Exception as e:
        logger.error(f"Kļūda link_account: {e}")

def handle_start(chat_id: int, first_name: str, payload: str = None) -> None:
    _clear_history(chat_id)
    if payload:
        link_account(chat_id, payload)
        
    text = f"Sveiks, *{first_name}*! 👋\n\n" + CONTENT["welcome"]
    send_message(chat_id, text, reply_markup=_main_menu_keyboard())

def handle_jauns(chat_id: int) -> None:
    _clear_history(chat_id)
    send_message(
        chat_id,
        "🔄 *Saruna notīrīta!*\n\n_Sākam no nulles. Ko vēlies uzzināt vai redzēt?_",
        reply_markup=_main_menu_keyboard(),
    )

def handle_main_menu(chat_id: int, message_id: int) -> None:
    _edit_message(
        chat_id, message_id,
        CONTENT["welcome"],
        _main_menu_keyboard(),
    )

def handle_news(chat_id: int, message_id: int) -> None:
    news_content = (
        "◷ *Jaunākās Ziņas no MIM*\n\n"
        "Mēs esam veiksmīgi integrējuši *Gemini AI* modeli mūsu platformā, "
        "kā arī izveidojuši interaktīvu Telegram aģentu arhitektūru.\n\n"
        "_Drīzumā šeit parādīsies automātiski atjauninājumi no mūsu ziņu datubāzes!_"
    )
    _edit_message(chat_id, message_id, news_content, reply_markup=_back_keyboard())
    
def send_long_message(chat_id: int, text: str, reply_markup: dict = None) -> None:
    """Droši nosūta garu tekstu, sadalot to gabalos (Telegram limits ir 4096 simboli)."""
    MAX_LEN = 4000
    
    if len(text) <= MAX_LEN:
        send_message(chat_id, text, reply_markup=reply_markup)
        return
        
    # Sadalām tekstu pa daļām
    chunks = [text[i:i+MAX_LEN] for i in range(0, len(text), MAX_LEN)]
    
    for i, chunk in enumerate(chunks):
        # Pievienojam pogas tikai pēdējai ziņas daļai
        markup = reply_markup if i == len(chunks) - 1 else None
        send_message(chat_id, chunk, reply_markup=markup)

def _read_knowledge_file(filename: str) -> str:
    """Droši nolasa Markdown failu no knowledge_base mapes."""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(base_dir, "knowledge_base", filename)
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        logger.error(f"Zināšanu fails nav atrasts: {file_path}")
        return "⚠️ Piedošanu, šī informācija šobrīd tiek atjaunota (fails nav atrasts)."
    except Exception as e:
        logger.error(f"Kļūda lasot failu {filename}: {e}")
        return "⚠️ Radās kļūda, ielādējot informāciju."

def handle_topic_command(chat_id: int, topic_key: str) -> None:
    filename = TOPIC_FILES.get(topic_key)
    
    if not filename:
        send_message(chat_id, "⚠️ Tēma netika atrasta.", reply_markup=_back_keyboard())
        return
        
    # Ielasa faila saturu
    text = _read_knowledge_file(filename)
    
    # Nosūta, izmantojot viedo sadalītāju
    send_long_message(chat_id, text, reply_markup=_back_keyboard())

def handle_komandas(chat_id: int) -> None:
    text = (
        "🛠 *Pieejamās komandas:*\n"
        "─────────────────────────\n\n"
        "🏠 /start — Galvenā izvēlne\n"
        "🔄 /jauns — Notīrīt sarunu vēsturi\n"
        "📊 /status — Tavs portāla statuss\n\n"
        "🤖 /ai — Par Mākslīgo Intelektu\n"
        "📜 /aiakts — ES AI Akts un drošība\n"
        "💼 /bizness — Risinājumi biznesam\n"
        "ℹ️ /parmums — Par MIM un pakalpojumiem\n"
        "🧠 /modeli — Izmantotie AI modeļi\n\n"
        "🌐 /portals — Klientu portāla saite\n"
        "✉️ /kontakts — Sazināties ar mums"
    )
    send_message(chat_id, text, reply_markup=_back_keyboard())

def handle_modeli(chat_id: int) -> None:
    text = "🧠 *Mūsu izmantotie modeļi:*\n\nMēs integrējam GPT-4, Google Gemini un atvērtā koda lokālos modeļus (piem., Llama 3), lai nodrošinātu augstāko drošību un ātrumu."
    send_message(chat_id, text, reply_markup=_back_keyboard())

def handle_riki(chat_id: int) -> None:
    text = "⚙️ *AI Rīki:*\n\nIzpēti mūsu rīku klāstu platformā [mim.lv/portals](https://mim.lv/portals)."
    send_message(chat_id, text, reply_markup=_back_keyboard())

def handle_standarti(chat_id: int) -> None:
    text = "🛡 *Koda un Izstrādes Standarti:*\n\nMēs rakstām tīru kodu, izmantojam React.js, Django un ievērojam labāko nozares praksi drošībai un mērogojamībai."
    send_message(chat_id, text, reply_markup=_back_keyboard())

def handle_portals(chat_id: int) -> None:
    portal_url = getattr(settings, "PORTAL_URL", "https://mim.lv/portals")
    text = f"🌐 *Klientu portāls:*\n\nPieslēdzies šeit, lai pārvaldītu savus projektus un rēķinus: {portal_url}"
    send_message(chat_id, text, reply_markup=_back_keyboard())


# ── /STATUS — Klienta portāla statuss Telegram ────────────────
def handle_status(chat_id: int) -> None:
    """Parāda klienta projektu, uzdevumu un rēķinu kopsavilkumu."""
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    try:
        user = User.objects.filter(telegram_id=chat_id).first()
        if not user:
            send_message(
                chat_id,
                "⚠️ Tavs Telegram konts vēl nav piesaistīts MIM portālam.\n\n"
                "🔗 Piesaisti to portālā: _Iestatījumi → Telegram saistīšana_",
                reply_markup=_back_keyboard()
            )
            return
        
        from projects.models import Projekts, Uzdevums
        from invoices.models import Rekkins
        from pieteikumi.models import Message
        
        projects = Projekts.objects.filter(klients=user)
        tasks = Uzdevums.objects.filter(klients=user)
        invoices = Rekkins.objects.filter(klients=user)
        messages = Message.objects.filter(client=user)
        
        active_projects = projects.filter(statuss__in=['AKTĪVS', 'PROCESĀ']).count()
        active_tasks = tasks.exclude(statuss='PABEIGTS').count()
        done_tasks = tasks.filter(statuss='PABEIGTS').count()
        unpaid = invoices.filter(statuss='NEAPMAKSĀTS')
        unpaid_count = unpaid.count()
        unpaid_total = sum(float(i.summa or 0) for i in unpaid)
        unread_msgs = messages.order_by('-created_at')[:3]
        
        text = (
            f"📊 *Tavs MIM Portāla Statuss*\n"
            f"─────────────────────────\n\n"
            f"👤 *{user.full_name or user.email}*\n\n"
            f"📁 *Projekti:* {projects.count()} (aktīvie: {active_projects})\n"
            f"📋 *Uzdevumi:* {active_tasks} aktīvi, {done_tasks} pabeigti\n"
        )
        
        if unpaid_count > 0:
            text += f"💰 *Neapmaksāti rēķini:* {unpaid_count} (€{unpaid_total:.2f})\n"
        else:
            text += f"✅ *Rēķini:* Viss apmaksāts!\n"
        
        text += f"📨 *Ziņas:* {messages.count()} kopā\n"
        
        if unread_msgs.exists():
            text += f"\n─────────────────────────\n📌 *Pēdējās ziņas:*\n"
            for m in unread_msgs:
                sender = "🔹 Tu" if m.sender == user else "🔸 MIM"
                text += f"{sender}: _{m.content[:50]}_\n"
        
        portal_url = getattr(settings, "PORTAL_URL", "https://mim.lv/portals")
        keyboard = {
            "inline_keyboard": [
                [{"text": "⎋ Atvērt Portālu", "url": portal_url}],
                [{"text": "↶ Galvenā izvēlne", "callback_data": "main_menu"}]
            ]
        }
        send_message(chat_id, text, reply_markup=keyboard)
        
    except Exception as e:
        logger.error(f"handle_status kļūda: {e}")
        send_message(chat_id, "⚠️ Nevarēju ielādēt statusu. Mēģini vēlreiz.", reply_markup=_back_keyboard())

# ── UZDEVUMU APSTIPRINĀŠANA (INTERACTIVE) ─────────────────────
def handle_task_approval(chat_id: int, message_id: int, task_id: int) -> None:
    from django.contrib.auth import get_user_model
    from projects.models import Uzdevums
    User = get_user_model()
    try:
        user = User.objects.get(telegram_id=chat_id)
        task = Uzdevums.objects.get(id=task_id, klients=user)
        if task.statuss != 'PABEIGTS':
            task.statuss = 'PABEIGTS'
            task.save()
            _edit_message(
                chat_id, message_id,
                f"✅ **Paldies par apstiprinājumu!**\nUzdevums *{task.tituls}* ir veiksmīgi noslēgts un portālā pārcelts uz 'Pabeigts' sadaļu!",
                reply_markup=None
            )
        else:
            _edit_message(
                chat_id, message_id,
                f"ℹ️ Uzdevums *{task.tituls}* jau bija atzīmēts kā pabeigts.",
                reply_markup=None
            )
    except Exception as e:
        logger.error(f"Kļūda handle_task_approval: {e}")
        send_message(chat_id, "⚠️ Kļūda no portāla: nevarēju apstiprināt uzdevumu.")

# ── NPS / ATSAUKSMES (INTERACTIVE) ────────────────────────────
def handle_nps_rating(chat_id: int, message_id: int, stars: int, task_id: int) -> None:
    if stars == 5:
        txt = "🌟 *Liels Paldies par uzticību!*\nMēs esam bezgala priecīgi par augsto vērtējumu.\nBūtu ideāli, ja varētu ielikt 5 zvaigznes arī mūsu sabiedriskajam profilam: [Google Atsauksmes](#)"
    elif stars == 4:
        txt = "👍 *Paldies par 4 Zvaigznēm!*\nMēs priecājamies, ka esi apmierināts, taču vienmēr mēģināsim noķert to pašu labāko un izcilāko līmeni nākotnē!"
    else:
        txt = f"⚠️ *Paldies par atgriezisko saiti ({stars}/5)*\nMēs ļoti atvainojamies, ka nespējām attaisnot augstākās cerības šeit. Aģentūras vadītājs ir saņēmis Tavu vērtējumu un rīt personīgi ar Tevi sazināsies."
        admin_id = getattr(settings, "TELEGRAM_ADMIN_CHAT_ID", None)
        if admin_id:
            send_message(int(admin_id), f"🚨 *Kritika!* Klients (Chat {chat_id}) novērtēja uzdevumu ID {task_id} tikai ar *{stars}/5 Zvaigznēm*!")
            
    _edit_message(chat_id, message_id, txt, reply_markup=None)

# ── GALVENĀ FUNKCIJA — GEMINI AI ──────────────────────────────
def handle_free_text(chat_id: int, user_text: str) -> None:
    send_typing_action(chat_id)
    _add_to_history(chat_id, "user", user_text)

    # Saglabā tekstam uz backend ja piesaistīts un sagatavo kontekstu
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    user_context_str = ""
    try:
        user = User.objects.filter(telegram_id=chat_id).first()
        if user:
            from projects.models import AgentaZina, Projekts, Uzdevums
            from invoices.models import Rekkins
            
            # Saglabā jauno klienta ziņu modelī
            AgentaZina.objects.create(klients=user, tips='text', saturs=user_text)
            
            # Veido LLM kontekstu no datubāzes
            ctx = [f"Klienta vārds: {user.full_name or user.email}\n"]
            
            # Projekti
            projekti = Projekts.objects.filter(klients=user)
            if projekti.exists():
                ctx.append("Aktīvie Projekti:")
                for p in projekti:
                    ctx.append(f"- {p.nosaukums} (Statuss: {p.get_statuss_display()})")
            
            # Uzdevumi
            uzdevumi = Uzdevums.objects.filter(klients=user)
            if uzdevumi.exists():
                ctx.append("\nUzdevumi un progresija:")
                for u in uzdevumi:
                    ctx.append(f"- {u.tituls} (Stadija: {u.get_statuss_display()})")
                    
            # Rēķini
            rekkini = Rekkins.objects.filter(klients=user, statuss='GAIDA')
            if rekkini.exists():
                ctx.append("\nNeapmaksātie Rēķini:")
                for r in rekkini:
                    ctx.append(f"- Nr. {r.numurs} | Summa: {r.summa} EUR | Apmaksāt līdz: {r.termins}")
                    
            # Faili / Mēdiji (Pēdējie sniegtie dati)
            zinas = AgentaZina.objects.filter(klients=user).exclude(tips='text').order_by('-izveidots')[:5]
            if zinas.exists():
                ctx.append("\nAugšupielādētie fails / dati portalā:")
                for z in zinas:
                    ctx.append(f"- Tips: {z.get_tips_display()} | Faila nosaukums vai raksturojums: {z.saturs}")
            
            user_context_str = "\n".join(ctx)

    except Exception as e:
        logger.error(f"Kļūda sagatavojot AI kontekstu no DB: {e}")

    history = _get_history(chat_id)[:-1]
    
    try:
        response = ask_gemini(user_text, conversation_history=history, user_context=user_context_str, portal_user=user)
    except Exception as e:
        logger.error(f"Gemini API kļūda: {e}")
        response = "⎋ Piedošanu, manas AI smadzenes šobrīd veic atjauninājumus. Mēģini vēlāk!"

    _add_to_history(chat_id, "model", response)
    send_message(chat_id, response, reply_markup=_after_answer_keyboard())

def handle_prompt_ask(chat_id: int, message_id: int) -> None:
    _edit_message(
        chat_id, message_id,
        "✍️ *Uzdod jautājumu Mikusam*\n\n"
        "Esmu pieslēgts Gemini sistēmai. Vari man jautāt jebko par tehnoloģijām, "
        "AI Aktu, vai to, kā MIM var palīdzēt tavam biznesam!\n\n"
        "_Vienkārši ieraksti savu jautājumu šajā čatā. ↧_",
        {"inline_keyboard": [[{"text": "↶ Atcelt", "callback_data": "main_menu"}]]},
    )

# ── KONTAKTA VEIDLAPA ─────────────────────────────────────────
_contact_state: dict = {}
STEP_NAME    = "name"
STEP_DESC    = "desc"
STEP_CONTACT = "contact"
STEP_CONFIRM = "confirm"

def _contact_cancel_keyboard() -> dict:
    return {"inline_keyboard": [[{"text": "❌ Atcelt", "callback_data": "contact_cancel"}]]}

def _contact_confirm_keyboard() -> dict:
    return {
        "inline_keyboard": [[
            {"text": "✅ Nosūtīt!",        "callback_data": "contact_confirm"},
            {"text": "✏️ Sākt no jauna",   "callback_data": "contact_cancel"},
        ]]
    }

def handle_contact_start(chat_id: int, message_id: int = None) -> None:
    _contact_state[chat_id] = {"step": STEP_NAME}
    text = (
        "📬 *Sazināties ar MIM*\n\n"
        "Mēs specializējamies:\n"
        "🌐 *Web Izstrādē un WebApos*\n"
        "🤖 *AI Čatbotu un Aģentu Integrācijās*\n\n"
        "Kādā vārdā ar Tevi sazināties?\n"
        "_(Norādi vārdu vai uzņēmuma nosaukumu)_"
    )
    if message_id:
        _edit_message(chat_id, message_id, text, _contact_cancel_keyboard())
    else:
        send_message(chat_id, text, reply_markup=_contact_cancel_keyboard())

def handle_contact_text(chat_id: int, user_text: str) -> None:
    state = _contact_state.get(chat_id)
    if not state:
        return
    step = state.get("step")

    if step == STEP_NAME:
        state["name"] = user_text.strip()
        state["step"] = STEP_DESC
        send_message(
            chat_id,
            f"✅ *{state['name']}*, lieliski!\n\n"
            "💬 Pastāsti īsi — *kāda ir Tava pamata vajadzība?*\n"
            "_(Piemēram: nepieciešama Telegram čatbota izveide manam biznesam, vai jaunas mājaslapas/portāla izstrāde)_",
            reply_markup=_contact_cancel_keyboard(),
        )
    elif step == STEP_DESC:
        state["desc"] = user_text.strip()
        state["step"] = STEP_CONTACT
        send_message(
            chat_id,
            "📞 *Kā ar Tevi sazināties?*\n\nNorādi e-pastu vai tālruni.",
            reply_markup=_contact_cancel_keyboard(),
        )
    elif step == STEP_CONTACT:
        state["contact"] = user_text.strip()
        state["step"]    = STEP_CONFIRM
        summary = (
            "📋 *Pārbaudi datus:*\n\n"
            f"👤 *Vārds:* {state.get('name','—')}\n"
            f"💬 *Apraksts:* {state.get('desc','—')}\n"
            f"📞 *Kontakts:* {state.get('contact','—')}\n\n"
            "Vai nosūtām pieteikumu?"
        )
        send_message(chat_id, summary, reply_markup=_contact_confirm_keyboard())

def handle_contact_confirm(chat_id: int, message_id: int, username: str) -> None:
    state   = _contact_state.pop(chat_id, {})
    name    = state.get("name", "—")
    desc    = state.get("desc", "—")
    contact = state.get("contact", "—")

    admin_id = getattr(settings, "TELEGRAM_ADMIN_CHAT_ID", None)
    if admin_id:
        send_message(
            int(admin_id),
            f"🔔 *JAUNS PIETEIKUMS — Telegram (MIM)*\n\n"
            f"👤 *Vārds:* {name}\n"
            f"💬 *Apraksts:* {desc}\n"
            f"📞 *Kontakts:* {contact}\n"
            f"📱 *Telegram:* @{username or 'nav'}\n"
            f"🆔 *Chat ID:* `{chat_id}`",
        )

    _edit_message(
        chat_id, message_id,
        "🎉 *Paldies! Pieteikums saņemts!*\n\n"
        "Mūsu komanda ar Tevi sazināsies pavisam drīz.",
        reply_markup=_back_keyboard(),
    )

def handle_contact_cancel(chat_id: int, message_id: int) -> None:
    _contact_state.pop(chat_id, None)
    handle_main_menu(chat_id, message_id)

def is_in_contact_flow(chat_id: int) -> bool:
    state = _contact_state.get(chat_id)
    return bool(state and state.get("step") in [STEP_NAME, STEP_DESC, STEP_CONTACT])

# ── MĒDIJI UN FAILU SAŅEMŠANA ─────────────────────────────────
def handle_media(message: dict, chat_id: int) -> None:
    from django.contrib.auth import get_user_model
    from django.core.files.base import ContentFile
    User = get_user_model()

    user = User.objects.filter(telegram_id=chat_id).first()
    if not user:
        send_message(chat_id, "⚠️ Tu neesi savienojis savu kontu ar portālu. Lūdzu atver portālu un sadaļā sazināties noklikšķini uz AI Aģents.")
        return

    file_id = None
    media_type = 'document'
    if 'photo' in message:
        file_id = message['photo'][-1]['file_id']
        media_type = 'photo'
    elif 'voice' in message:
        file_id = message['voice']['file_id']
        media_type = 'audio'
    elif 'audio' in message:
        file_id = message['audio']['file_id']
        media_type = 'audio'
    elif 'document' in message:
        file_id = message['document']['file_id']
        media_type = 'document'
        
    caption = message.get("caption", "")

    if file_id:
        try:
            file_url_resp = requests.get(f"https://api.telegram.org/bot{_token()}/getFile?file_id={file_id}")
            file_path = file_url_resp.json()['result']['file_path']
            download_url = f"https://api.telegram.org/file/bot{_token()}/{file_path}"
            
            file_content = requests.get(download_url).content
            
            # --- AUDIO TRANSKRIPCIJAS INJEKCIJA ---
            if media_type == 'audio':
                send_message(chat_id, "🎧 *AI klausās audio...* Tūlīt sapratīšu un saglabāšu portalā!")
                try:
                    from .gemini_client import transcribe_audio
                    transcription = transcribe_audio(file_content)
                    if transcription:
                        caption = f"🎙️ [TRANSKRIPCIJA]:\n{transcription}\n\n{caption}".strip()
                except Exception as ex:
                    logger.error(f"Transkripcijas procesa kļūda: {ex}")
            # --------------------------------------
            
            from projects.models import AgentaZina
            zona = AgentaZina(klients=user, tips=media_type, saturs=caption)
            filename = file_path.split('/')[-1]
            zona.fails.save(filename, ContentFile(file_content), save=False)
            zona.save()
            
            send_message(chat_id, f"✅ Saglabāts projektā kā '{media_type}'!")
        except Exception as e:
            logger.error(f"Kļūda mediju saglabāšanā: {e}")
            send_message(chat_id, "❌ Sistēmas kļūda faila saņemšanā.")


# =============================================================
# TIEŠAIS RŪTERIS: Admin atbild klientam no Telegram
# =============================================================
def handle_mailbox_reply(chat_id: int, text: str) -> None:
    """
    Apstrādā admina atbildi no Telegram uz klienta Dashboard ziņu.
    Formāts: /reply_123 Tavs atbildes teksts
    vai:     /reply 123 Tavs atbildes teksts
    """
    try:
        from django.contrib.auth import get_user_model
        from pieteikumi.models import Message
        User = get_user_model()
        
        # Pārbaudām, vai tiešām ir admin
        admin_chat_id = getattr(settings, 'TELEGRAM_ADMIN_CHAT_ID', None)
        if str(chat_id) != str(admin_chat_id):
            send_message(chat_id, "❌ Šī komanda ir pieejama tikai adminiem.")
            return
        
        # Parsējam komandu
        parts = text.split(maxsplit=1)
        cmd_part = parts[0]  # /reply_123 vai /reply
        
        # Izvelkam client_id un reply_text
        if '_' in cmd_part:
            # Formāts: /reply_123 teksts
            client_id_str = cmd_part.split('_', 1)[1]
            reply_text = parts[1] if len(parts) > 1 else ""
        else:
            # Formāts: /reply 123 teksts
            remaining = parts[1] if len(parts) > 1 else ""
            sub_parts = remaining.split(maxsplit=1)
            client_id_str = sub_parts[0] if sub_parts else ""
            reply_text = sub_parts[1] if len(sub_parts) > 1 else ""
        
        if not client_id_str or not reply_text.strip():
            send_message(chat_id, 
                "⚠️ *Lietošana:*\n`/reply_[KLIENTA_ID] Tavs atbildes teksts`\n\n"
                "Piemēram: `/reply_5 Sveiki, jūsu jautājums ir saņemts!`"
            )
            return
        
        client_id = int(client_id_str)
        
        # Atrodam klientu
        try:
            client = User.objects.get(id=client_id)
        except User.DoesNotExist:
            send_message(chat_id, f"❌ Klients ar ID {client_id} nav atrasts.")
            return
        
        # DROŠĪBA (HIGH-03): Atrodam admin pēc telegram_id, ne pirmo is_staff
        try:
            admin_user = User.objects.get(telegram_id=chat_id)
        except User.DoesNotExist:
            # Fallback: ja admin nav saistīts ar Telegram, lietojam pirmo staff
            admin_user = User.objects.filter(is_staff=True).first()
        
        if not admin_user:
            send_message(chat_id, "❌ Sistēmā nav atrasts admin lietotājs.")
            return
        
        # DROŠĪBA: Ierobežojam ziņas garumu
        safe_text = reply_text.strip()[:5000]
        
        # Saglabājam ziņu datubāzē
        message = Message.objects.create(
            client=client,
            sender=admin_user,
            content=safe_text
        )
        
        client_name = getattr(client, 'full_name', '') or client.email
        send_message(
            chat_id,
            f"✅ *Ziņa nosūtīta!*\n\n"
            f"👤 Klients: {client_name}\n"
            f"💬 _{safe_text[:100]}_\n\n"
            f"_Klients ieraudzīs ziņu savā Dashboard automatiskajā atjauninājumā._"
        )
        
        logger.info(f"Mailbox reply: admin -> client {client_id} ({client_name})")
        
    except ValueError:
        send_message(chat_id, "❌ Nederīgs klienta ID. Lietojiet skaitli.")
    except Exception as e:
        logger.error(f"handle_mailbox_reply kļūda: {e}", exc_info=True)
        # DROŠĪBA (MED-03): Neatklāt kļūdas detaļas
        send_message(chat_id, "❌ Sistēmas kļūda. Mēģiniet vēlreiz.")