"""ساخت Context ترکیبی برای هر ایجنت:
   الف) System Prompt ایجنت (agents.yaml)
   ب)  داده‌های Notion (حداکثر ۱۰ رکورد اخیر، Status=فعال)
   ب-۲) منابع دادهٔ موجود (نسخهٔ ۱.۰.۱): بانک مرکزی وظایف، شناسنامه‌ها،
        خطوط درآمدی و ۶ تب Google Sheets — فقط منابعی که در agents.yaml
        برای همین ایجنت فهرست شده‌اند.
   ج)  تاریخچه چت گروه (آخرین ۳۰ پیام از MongoDB)
"""

from __future__ import annotations

import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Optional
from zoneinfo import ZoneInfo

from services.agents import Agent
from services.notion import format_records_for_prompt

logger = logging.getLogger(__name__)

PERSIAN_MONTHS = [
    "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور",
    "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند",
]


@dataclass
class AgentContext:
    agent: Agent
    system_prompt: str
    user_prompt: str
    notion_records: list[dict[str, Any]]
    history_count: int
    user_question: str
    evidence_hint: str
    sources_block: str = ""
    sources_footer: str = ""


def _to_local(dt: datetime, tz_name: str) -> datetime:
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    try:
        return dt.astimezone(ZoneInfo(tz_name))
    except Exception:  # noqa: BLE001 — tz نامعتبر
        return dt.astimezone(timezone.utc)


def format_message_line(msg: dict[str, Any], tz_name: str = "Asia/Tehran") -> str:
    """`[2025-01-15 14:30] @username: متن پیام`"""
    dt = msg.get("date") or msg.get("saved_at") or datetime.now(timezone.utc)
    if isinstance(dt, str):
        try:
            dt = datetime.fromisoformat(dt)
        except ValueError:
            dt = datetime.now(timezone.utc)
    stamp = _to_local(dt, tz_name).strftime("%Y-%m-%d %H:%M")
    username = msg.get("username") or msg.get("sender_name") or "unknown"
    text = (msg.get("text") or "").replace("\n", " ").strip()
    if not text:
        if msg.get("has_media"):
            text = f"[{msg.get('media_type') or 'media'}]"
        else:
            text = "[پیام بدون متن]"
    if len(text) > 500:
        text = text[:500] + "…"
    reply_to = msg.get("reply_to_message_id")
    reply_note = f" (پاسخ به #{reply_to})" if reply_to else ""
    return f"[{stamp}] @{username}:{reply_note} {text}"


def format_history(messages: list[dict[str, Any]], tz_name: str = "Asia/Tehran") -> str:
    if not messages:
        return "تاریخچه‌ای در دست نیست (هیچ پیامی در دیتابیس نیست)."
    return "\n".join(format_message_line(m, tz_name) for m in messages)


def build_user_prompt(
    agent: Agent,
    notion_block: str,
    history_block: str,
    user_question: str,
    today_str: str,
    notion_is_empty: bool,
    history_is_empty: bool,
    sources_block: str = "",
    sources_footer: str = "",
) -> str:
    if sources_block:
        sources_section = (
            "## بخش ب-۲ — منابع دادهٔ متصل (فقط‌خواندنی)\n"
            f"{sources_footer}\n\n"
            f"{sources_block}\n\n"
            "> یادآوری: این منابع فقط‌خواندنی‌اند. منبع هر جمله را نام ببر. "
            "«خالی» را «صفر» تفسیر نکن و تعارض منابع را اعلام کن.\n"
        )
    else:
        sources_section = (
            "## بخش ب-۲ — منابع دادهٔ متصل\n"
            "هیچ منبع دادهٔ خارجی به این ایجنت متصل نیست؛ فقط تاریخچهٔ چت را داری.\n"
        )
    return f"""# Context عملیاتی — {agent.id} ({agent.name})

## بخش الف — هویت و مرز اختیار
نقش: {agent.role}
مرز اختیار: {agent.authority}

## بخش ب — داده‌های Notion (دیتابیس {agent.notion_db_key or '—'}، حداکثر ۱۰ رکورد اخیر با Status=فعال)
{notion_block}

{sources_section}
## بخش ج — تاریخچه چت گروه (آخرین پیام‌ها، قدیمی → جدید)
{history_block}

---

## درخواست کاربر (در گروه، امروز {today_str})
{user_question or '(بدون متن — فقط منشن)'}

---

## دستور پاسخ
۱. فقط در نقش {agent.id} پاسخ بده و از مرز اختیار خودت بیرون نزن.
۲. اگر داده Notion {"خالی" if notion_is_empty else "موجود"} و تاریخچه {"خالی" if history_is_empty else "موجود"} است،
   این را در ابتدای پاسخ با یک خط وضعیت شفاف اعلام کن.
۳. هر ادعا شاهد داشته باشد: `[شاهد: ...]`. ادعای بدون شاهد → `⚠️ نیازمند تأیید`.
۴. هیچ ردیف/عددی را حدس نزن. خانه خالی ≠ صفر و ≠ تأیید.
۵. فقط ابزار رایگان پیشنهاد بده.
۶. پایان پاسخ: «✅ اقدام بعدی» (حداکثر ۳ مورد) و در صورت لزوم «⚠️ نیازمند تأیید مدیر».
"""


def build_agent_context(
    agent: Agent,
    notion_records: list[dict[str, Any]],
    history_messages: list[dict[str, Any]],
    user_question: str,
    tz_name: str = "Asia/Tehran",
    history_limit: int = 30,
    sources: object | None = None,
) -> AgentContext:
    notion_block = format_records_for_prompt(agent.id, notion_records)
    trimmed = history_messages[-history_limit:]
    history_block = format_history(trimmed, tz_name)
    now_local = _to_local(datetime.now(timezone.utc), tz_name)
    today_str = now_local.strftime("%Y-%m-%d %H:%M")

    user_prompt = build_user_prompt(
        agent=agent,
        notion_block=notion_block,
        history_block=history_block,
        user_question=user_question,
        today_str=today_str,
        notion_is_empty=not notion_records,
        history_is_empty=not trimmed,
        sources_block=getattr(sources, "block", "") or "",
        sources_footer=getattr(sources, "footer_line", lambda: "")() or "",
    )

    evidence_hint = (
        "منقول از چت گروه"
        if trimmed
        else "بدون شاهد مستقیم (تاریخچه خالی بود)"
    )
    if notion_records:
        first_url = notion_records[0].get("_url")
        if first_url:
            evidence_hint = f"منقول از چت گروه + Notion: {first_url}"

    if getattr(sources, "results", None):
        stats = ", ".join(
            f"{r.title}={r.count}" for r in sources.results if getattr(r, "status", "") == "ok"
        )
        if stats:
            evidence_hint = f"{evidence_hint} | منابع: {stats}"

    return AgentContext(
        agent=agent,
        system_prompt=agent.full_system_prompt,
        user_prompt=user_prompt,
        notion_records=notion_records,
        history_count=len(trimmed),
        user_question=user_question,
        evidence_hint=evidence_hint,
        sources_block=getattr(sources, "block", "") or "",
        sources_footer=getattr(sources, "footer_line", lambda: "")() or "",
    )


def split_for_telegram(text: str, limit: int = 3900) -> list[str]:
    """تقسیم پاسخ بلند به چند پیام تلگرام، با حفظ مرز پاراگراف."""
    text = (text or "").strip()
    if not text:
        return []
    if len(text) <= limit:
        return [text]
    chunks: list[str] = []
    remaining = text
    while len(remaining) > limit:
        window = remaining[:limit]
        cut = max(window.rfind("\n\n"), window.rfind("\n"), window.rfind(". "))
        if cut < limit * 0.5:
            cut = limit
        chunks.append(remaining[:cut].strip())
        remaining = remaining[cut:].strip()
    if remaining:
        chunks.append(remaining)
    return chunks


def now_local(tz_name: str = "Asia/Tehran") -> datetime:
    return datetime.now(timezone.utc).astimezone(ZoneInfo(tz_name))


def gregorian_to_jalali(gy: int, gm: int, gd: int) -> tuple[int, int, int]:
    """تبدیل تاریخ میلادی به جلالی (الگوریتم استاندارد، بدون وابستگی خارجی)."""
    g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    gy2 = gy + 1 if gm > 2 else gy
    days = (
        355666
        + 365 * gy
        + (gy2 + 3) // 4
        - (gy2 + 99) // 100
        + (gy2 + 399) // 400
        + gd
        + g_d_m[gm - 1]
    )
    jy = -1595 + 33 * (days // 12053)
    days %= 12053
    jy += 4 * (days // 1461)
    days %= 1461
    if days > 365:
        jy += (days - 1) // 365
        days = (days - 1) % 365
    if days < 186:
        jm = 1 + days // 31
        jd = 1 + days % 31
    else:
        jm = 7 + (days - 186) // 30
        jd = 1 + (days - 186) % 30
    return jy, jm, jd


def human_today(tz_name: str = "Asia/Tehran") -> str:
    d = now_local(tz_name)
    jy, jm, jd = gregorian_to_jalali(d.year, d.month, d.day)
    return f"{d.strftime('%Y-%m-%d')} ({jd} {PERSIAN_MONTHS[jm - 1]} {jy})"
