"""sources.py — خواندن یکسان منابع دادهٔ موجود و تبدیل به متن فارسی برای پرامپت.

نسخهٔ ۱.۰.۱ بتا

منابع:
    • Notion (فقط‌خواندنی)  : بانک مرکزی وظایف | شناسنامه‌های شغلی | خطوط درآمدی
    • Google Sheets (کش)   : ۶ تب، از طریق n8n → /internal/sheets/push

اصل طراحی:
    ۱) هر ایجنت فقط منابعی را می‌بیند که در config/agents.yaml → agent_sources
       برایش فهرست شده. دسترسی، تصمیمِ پیکربندی است نه تصمیمِ مدل.
    ۲) هیچ‌جا نوشتن انجام نمی‌شود. تنها متد نوشتنی وجود ندارد — عمداً.
    ۳) خطا هرگز پرامپت را نمی‌شکند: منبع خطادار با برچسب «در دسترس نیست»
       در متن می‌آید تا مدل بداند داده ندارد، نه اینکه داده صفر است.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional

import yaml

from config.settings import settings

logger = logging.getLogger(__name__)

AGENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "agents.yaml"

#: منابعی که از Notion خوانده می‌شوند و کلیدشان در settings.source_dbs هست
NOTION_SOURCE_KEYS = ("tasks", "roles", "revenue")


# --------------------------------------------------------------------------- #
#  پیکربندی منابع (از agents.yaml)
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class SourceSpec:
    key: str
    kind: str        # notion | sheets
    title: str
    hint: str = ""


@dataclass(frozen=True)
class SourcesConfig:
    specs: dict[str, SourceSpec]
    agent_map: dict[str, tuple[str, ...]]
    rules: str

    def for_agent(self, agent_id: str) -> tuple[SourceSpec, ...]:
        keys = self.agent_map.get(agent_id.upper(), ())
        return tuple(self.specs[k] for k in keys if k in self.specs)


_config_cache: Optional[SourcesConfig] = None


def load_sources_config(path: Path | None = None, *, reload: bool = False) -> SourcesConfig:
    """بارگذاری تعریف منابع و نگاشت ایجنت ← منبع از agents.yaml."""
    global _config_cache
    if _config_cache is not None and not reload:
        return _config_cache

    file_path = path or AGENTS_FILE
    try:
        with file_path.open("r", encoding="utf-8") as fh:
            raw = yaml.safe_load(fh) or {}
    except FileNotFoundError:
        logger.warning("agents.yaml پیدا نشد؛ منابع داده غیرفعال می‌شوند.")
        raw = {}

    specs: dict[str, SourceSpec] = {}
    for key, item in (raw.get("sources") or {}).items():
        if not isinstance(item, dict):
            continue
        specs[str(key)] = SourceSpec(
            key=str(key),
            kind=str(item.get("kind") or "notion").lower(),
            title=str(item.get("title") or key),
            hint=str(item.get("hint") or ""),
        )

    agent_map: dict[str, tuple[str, ...]] = {}
    for agent_id, keys in (raw.get("agent_sources") or {}).items():
        if isinstance(keys, str):
            keys = [k.strip() for k in keys.split(",")]
        agent_map[str(agent_id).upper()] = tuple(str(k) for k in (keys or []))

    _config_cache = SourcesConfig(
        specs=specs,
        agent_map=agent_map,
        rules=str(raw.get("source_rules") or "").strip(),
    )
    logger.info(
        "منابع داده بارگذاری شد: %d منبع | نگاشت برای %d ایجنت",
        len(specs),
        len(agent_map),
    )
    return _config_cache


def source_rules() -> str:
    return load_sources_config().rules


# --------------------------------------------------------------------------- #
#  استخراج فیلدهای خوانا از یک رکورد Notion
# --------------------------------------------------------------------------- #
_TITLE_HINTS = ("name", "نام", "title", "عنوان", "task", "وظیفه", "خط درآمدی", "نقش")
_SKIP_PROP_TYPES = {
    "formula", "rollup", "created_time", "last_edited_time",
    "created_by", "last_edited_by", "unique_id",
}


def record_title(rec: dict[str, Any]) -> str:
    """بهترین عنوان قابل‌نمایش برای یک رکورد."""
    for hint in _TITLE_HINTS:
        for key, value in rec.items():
            if key.startswith("_"):
                continue
            if key.lower() == hint and isinstance(value, (str, int, float)):
                text = str(value).strip()
                if text:
                    return text
    # اولین فیلد متنی غیرخالی
    for key, value in rec.items():
        if key.startswith("_"):
            continue
        if isinstance(value, str) and value.strip():
            return value.strip()
    return str(rec.get("_page_id", ""))[:8] or "(بدون عنوان)"


def record_fields(rec: dict[str, Any], *, skip_title: bool = True) -> list[tuple[str, str]]:
    """جفت‌های (نام ستون، مقدار) برای نمایش در پرامپت."""
    title = record_title(rec) if skip_title else None
    out: list[tuple[str, str]] = []
    for key, value in rec.items():
        if key.startswith("_"):
            continue
        if value is None or value == "" or value == []:
            continue
        if isinstance(value, list):
            value = ", ".join(str(v) for v in value)
        text = str(value).strip()
        if not text:
            continue
        if skip_title and text == title:
            continue
        if len(text) > 300:
            text = text[:300] + "…"
        out.append((key, text))
    return out


# --------------------------------------------------------------------------- #
#  خواندن از Notion
# --------------------------------------------------------------------------- #
@dataclass
class SourceResult:
    """نتیجهٔ خواندن یک منبع."""

    key: str
    title: str
    kind: str
    hint: str = ""
    status: str = "ok"          # ok | not_configured | error | empty
    records: list[dict[str, Any]] = field(default_factory=list)
    error: str = ""

    @property
    def count(self) -> int:
        return len(self.records)


async def read_notion_source(
    notion: Any,
    key: str,
    spec: SourceSpec,
    db_id: str,
    limit: int = 25,
) -> SourceResult:
    """خواندن یک دیتابیس Notion. هرگز استثنا پرتاب نمی‌کند."""
    if not db_id:
        return SourceResult(key, spec.title, "notion", spec.hint,
                            status="not_configured", error="شناسهٔ دیتابیس تنظیم نشده")
    if notion is None or not getattr(notion, "available", False):
        return SourceResult(key, spec.title, "notion", spec.hint,
                            status="not_configured", error="NOTION_API_KEY تنظیم نشده")

    try:
        # fetch_active_records فیلتر Status=فعال می‌زند؛ برای منابع عمومی
        # بهتر است بدون فیلتر بخوانیم، ولی برای سازگاری همین مسیر را داریم
        # و در صورت خالی بودن، بدون فیلتر تلاش می‌کنیم.
        records = await notion.fetch_active_records(db_id, limit=limit)
        if not records:
            records = await _fetch_unfiltered(notion, db_id, limit)
        if not records:
            return SourceResult(key, spec.title, "notion", spec.hint, status="empty")
        return SourceResult(key, spec.title, "notion", spec.hint,
                            status="ok", records=records[:limit])
    except Exception as exc:  # noqa: BLE001 — منبع خطادار نباید پرامپت را بشکند
        logger.warning("خواندن منبع Notion «%s» ناموفق: %s", spec.title, exc)
        return SourceResult(key, spec.title, "notion", spec.hint,
                            status="error", error=str(exc)[:200])


async def _fetch_unfiltered(notion: Any, db_id: str, limit: int) -> list[dict[str, Any]]:
    """تلاش دوم: خواندن بدون فیلتر وضعیت (وقتی ستون Status وجود ندارد)."""
    client = getattr(notion, "_client", None) or getattr(notion, "client", None)
    if client is None:
        return []
    from services.notion import flatten_page  # وارد کردن موضعی برای جلوگیری از چرخه

    resp = await client.databases.query(
        database_id=db_id,
        page_size=max(1, min(limit, 100)),
        sorts=[{"timestamp": "last_edited_time", "direction": "descending"}],
    )
    return [flatten_page(p) for p in resp.get("results", [])][:limit]


# --------------------------------------------------------------------------- #
#  فرمت‌بندی بلوک پرامپت
# --------------------------------------------------------------------------- #
def format_notion_block(result: SourceResult, *, max_records: int = 25) -> str:
    head = f'### منبع: {result.title}  (نوع: Notion)'
    if result.hint:
        head += f"  — {result.hint}"

    if result.status == "not_configured":
        return (
            f"{head}\n"
            f"⚠️ دسترسی این منبع هنوز برقرار نشده ({result.error}).\n"
            "→ یعنی «داده‌ای در دست نیست»؛ این را به‌عنوان «صفر» تفسیر نکن."
        )
    if result.status == "error":
        return f"{head}\n⚠️ خطا در خواندن منبع: {result.error}\n→ داده‌ای برای استناد نداری."
    if result.status == "empty":
        return (
            f"{head}\n"
            "این منبع خوانده شد ولی هیچ رکوردی برنگرداند.\n"
            "→ «خالی ≠ صفر»: ممکن است فیلتر وضعیت یا مجوز باشد؛ صریح اعلام کن."
        )

    lines = [head, f"تعداد رکورد خوانده‌شده: {min(len(result.records), max_records)}"]
    for idx, rec in enumerate(result.records[:max_records], start=1):
        title = record_title(rec)
        parts = [f"{idx}. {title}"]
        for key, value in record_fields(rec):
            parts.append(f"   - {key}: {value}")
        url = rec.get("_url")
        if url:
            parts.append(f"   - لینک: {url}")
        lines.append("\n".join(parts))
    return "\n".join(lines)


def format_sheets_block(spec: SourceSpec, tab: Optional["SheetTabLike"]) -> str:
    head = f'### منبع: {spec.title}  (نوع: Google Sheets)'
    if spec.hint:
        head += f"  — {spec.hint}"

    if tab is None or not tab.rows:
        return (
            f"{head}\n"
            "⚠️ این تب هنوز همگام نشده است (کش خالی).\n"
            "→ «داده ثبت نشده» را جایگزین «صفر» نکن."
        )

    lines = [head, f"تعداد ردیف: {len(tab.rows)}  |  آخرین همگام‌سازی: {tab.synced_at or 'نامشخص'}"]
    headers = tab.headers or []
    for idx, row in enumerate(tab.rows[:50], start=1):
        if headers and isinstance(row, list):
            pairs = [
                f"{headers[i]}={v}"
                for i, v in enumerate(row)
                if i < len(headers) and str(v).strip()
            ]
            lines.append(f"{idx}. " + " | ".join(pairs))
        else:
            lines.append(f"{idx}. {row}")
    return "\n".join(lines)


class SheetTabLike:
    """پروتکل ساختاری برای تب شیت (جلوگیری از import چرخه‌ای)."""

    headers: list[str]
    rows: list[Any]
    synced_at: str


# --------------------------------------------------------------------------- #
#  نقطهٔ ورود اصلی
# --------------------------------------------------------------------------- #
@dataclass
class SourcesBundle:
    """همهٔ منابع یک ایجنت، آمادهٔ درج در پرامپت."""

    agent_id: str
    block: str
    results: list[SourceResult]
    stats: dict[str, int]
    empty: bool

    def footer_line(self) -> str:
        if self.empty:
            return "منابع: هیچ منبعی متصل نیست"
        parts = [
            f"{r.title}: {r.count}" if r.status == "ok" else f"{r.title}: —"
            for r in self.results
        ]
        return "منابع → " + " | ".join(parts)


async def gather_sources(
    agent_id: str,
    notion: Any = None,
    *,
    sheets: Any = None,
    max_records: int | None = None,
    config: SourcesConfig | None = None,
) -> SourcesBundle:
    """خواندن همهٔ منابع مجاز یک ایجنت و ساخت متن پرامپت.

    `sheets` می‌تواند یک SheetCache باشد (services.sheets_cache) یا None.
    """
    cfg = config or load_sources_config()
    specs = cfg.for_agent(agent_id)
    limit = max_records or settings.sources_max_records

    if not specs:
        return SourcesBundle(agent_id, "", [], {}, empty=True)

    results: list[SourceResult] = []
    blocks: list[str] = []

    for spec in specs:
        if spec.kind == "notion":
            db_id = settings.source_dbs.get(spec.key, "")
            result = await read_notion_source(notion, spec.key, spec, db_id, limit)
            results.append(result)
            blocks.append(format_notion_block(result, max_records=limit))
        else:  # sheets
            tab = None
            if sheets is not None:
                try:
                    tab = sheets.get(spec.title)
                except Exception:  # noqa: BLE001
                    tab = None
            results.append(
                SourceResult(
                    spec.key, spec.title, "sheets", spec.hint,
                    status="ok" if tab and getattr(tab, "rows", None) else "empty",
                    records=list(getattr(tab, "rows", []) or []),
                )
            )
            blocks.append(format_sheets_block(spec, tab))

    stats = {r.key: r.count for r in results if r.status == "ok"}
    return SourcesBundle(
        agent_id=agent_id,
        block="\n\n".join(blocks),
        results=results,
        stats=stats,
        empty=False,
    )
