"""تست: منابع دادهٔ متصل (نسخهٔ ۱.۰.۱) — منابع Notion، کش Sheets، دسترسی هر ایجنت."""

from __future__ import annotations

import asyncio
import sys
from pathlib import Path

APP = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(APP))

from config.settings import settings  # noqa: E402
from services.agents import load_registry  # noqa: E402
from services.context import build_agent_context  # noqa: E402
from services.sheets_cache import SheetCache, normalize_name  # noqa: E402
from services.sources import (  # noqa: E402
    SourceResult,
    SourceSpec,
    format_notion_block,
    format_sheets_block,
    gather_sources,
    load_sources_config,
    record_fields,
    record_title,
)

PASS, FAIL = 0, 0


def check(name: str, cond: bool, detail: str = "") -> None:
    global PASS, FAIL
    if cond:
        PASS += 1
        print(f"  ✅ {name}")
    else:
        FAIL += 1
        print(f"  ❌ {name}" + (f" — {detail}" if detail else ""))


# --------------------------------------------------------------------------- #
class FakeNotion:
    """کلاینت ساختگی Notion که رکوردهای آماده برمی‌گرداند."""

    def __init__(self, records_by_db: dict[str, list[dict]] | None = None, fail: bool = False):
        self.records_by_db = records_by_db or {}
        self.fail = fail
        self.available = True
        self.calls: list[str] = []

    async def fetch_active_records(self, database_id: str, limit: int = 10) -> list[dict]:
        self.calls.append(database_id)
        if self.fail:
            raise RuntimeError("Notion 503")
        return self.records_by_db.get(database_id, [])[:limit]


class FakeTab:
    def __init__(self, headers, rows, synced_at="2026-11-05T08:00"):
        self.headers = headers
        self.rows = rows
        self.synced_at = synced_at


def run(coro):
    """اجرای یک کوروتین — با حلقهٔ تازه تا در pytest هم کار کند."""
    return asyncio.run(coro)


# --------------------------------------------------------------------------- #
print("\n=== ۱) پیکربندی منابع از agents.yaml ===")
cfg = load_sources_config(reload=True)
check("۹ منبع تعریف شده", len(cfg.specs) == 9, str(len(cfg.specs)))
check("۳ منبع Notion", sum(1 for s in cfg.specs.values() if s.kind == "notion") == 3)
check("۶ منبع Sheets", sum(1 for s in cfg.specs.values() if s.kind == "sheets") == 6)
check("نگاشت ۹ ایجنت", len(cfg.agent_map) == 9, str(len(cfg.agent_map)))
check("AG09 بیشترین دسترسی (۹ منبع)", len(cfg.for_agent("AG09")) == 9, str(len(cfg.for_agent("AG09"))))
check("AG01 به roles دسترسی ندارد", "roles" not in [s.key for s in cfg.for_agent("AG01")])
check("AG07 به ۵ تب Sheets دسترسی دارد",
      len([s for s in cfg.for_agent("AG07") if s.kind == "sheets"]) == 5,
      str([s.key for s in cfg.for_agent("AG07") if s.kind == "sheets"]))
check("AG09 به همهٔ ۶ تب Sheets دسترسی دارد",
      len([s for s in cfg.for_agent("AG09") if s.kind == "sheets"]) == 6,
      str([s.key for s in cfg.for_agent("AG09") if s.kind == "sheets"]))
check("ایجنت ناشناس → بدون منبع", cfg.for_agent("AG99") == ())
check("عنوان فارسی منبع", cfg.specs["tasks"].title == "بانک مرکزی وظایف", cfg.specs["tasks"].title)
check("قواعد منابع موجود است", "قواعد منابع داده" in cfg.rules)
check("قاعدهٔ تعارض منابع", "تعارض منابع" in cfg.rules)
check("قاعدهٔ «خالی ≠ صفر»", "خالی ≠ صفر" in cfg.rules)

# --------------------------------------------------------------------------- #
print("\n=== ۲) استخراج عنوان و فیلدها ===")
rec = {
    "Name": "تدوین تقویم محتوایی آذر",
    "Assignee": "AG03",
    "Status": "در حال انجام",
    "Due": "2026-12-01",
    "Empty": None,
    "Blank": "",
    "Tags": ["محتوا", "فوری"],
    "_page_id": "abc12345",
    "_url": "https://notion.so/x",
}
check("عنوان از Name", record_title(rec) == "تدوین تقویم محتوایی آذر", record_title(rec))
fields = dict(record_fields(rec))
check("عنوان در فیلدها تکرار نشده", "Name" not in fields)
check("فیلد خالی حذف شد", "Empty" not in fields and "Blank" not in fields)
check("لیست به رشته تبدیل شد", fields.get("Tags") == "محتوا, فوری", str(fields.get("Tags")))
check("فیلد _url در فیلدها نیست", "_url" not in fields)

rec_fa = {"عنوان": "بررسی خط درآمدی B2B", "وضعیت شاهد": "فاقد شاهد"}
check("عنوان فارسی", record_title(rec_fa) == "بررسی خط درآمدی B2B", record_title(rec_fa))
check("بدون عنوان → شناسه", record_title({"_page_id": "deadbeef99"}).startswith("deadbeef"))
check("فیلد بلند بریده می‌شود",
      len(dict(record_fields({"X": "ب" * 500}, skip_title=False))["X"]) == 301)

# --------------------------------------------------------------------------- #
print("\n=== ۳) بلوک پرامپت Notion ===")
ok_result = SourceResult("tasks", "بانک مرکزی وظایف", "notion", status="ok", records=[rec])
block = format_notion_block(ok_result)
check("عنوان منبع در بلوک", "بانک مرکزی وظایف" in block)
check("نوع Notion ذکر شد", "Notion" in block)
check("رکورد شماره‌گذاری شد", "1. تدوین تقویم" in block)
check("لینک رکورد درج شد", "https://notion.so/x" in block)

empty_block = format_notion_block(SourceResult("roles", "شناسنامه‌های شغلی", "notion", status="empty"))
check("منبع خالی → هشدار خالی≠صفر", "خالی ≠ صفر" in empty_block)
check("منبع خالی → صریح اعلام", "هیچ رکوردی برنگرداند" in empty_block)

nc_block = format_notion_block(
    SourceResult("revenue", "خطوط درآمدی", "notion", status="not_configured", error="کلید نیست")
)
check("منبع تنظیم‌نشده → «داده‌ای در دست نیست»", "داده‌ای در دست نیست" in nc_block)
check("منبع تنظیم‌نشده → علت ذکر شد", "کلید نیست" in nc_block)

err_block = format_notion_block(
    SourceResult("tasks", "بانک مرکزی وظایف", "notion", status="error", error="timeout")
)
check("منبع خطادار → برچسب خطا", "خطا در خواندن" in err_block)

# --------------------------------------------------------------------------- #
print("\n=== ۴) بلوک پرامپت Sheets ===")
spec = SourceSpec("daily", "sheets", "ثبت روزانه", "فعالیت انجام‌شده")
tab = FakeTab(["مجری", "تاریخ", "کار"], [["AG03", "۱۴۰۵/۰۸/۱۴", "تقویم محتوایی"]])
sb = format_sheets_block(spec, tab)
check("عنوان تب", "ثبت روزانه" in sb)
check("نوع Sheets", "Google Sheets" in sb)
check("سرستون به کلید تبدیل شد", "مجری=AG03" in sb, sb[:200])
check("زمان همگام‌سازی درج شد", "2026-11-05T08:00" in sb)

sb_empty = format_sheets_block(spec, None)
check("تب همگام‌نشده → صریح", "هنوز همگام نشده" in sb_empty)
check("تب همگام‌نشده → «صفر نکن»", "صفر» نکن" in sb_empty or "صفر نکن" in sb_empty)

# --------------------------------------------------------------------------- #
print("\n=== ۵) کش Sheets ===")
cache = SheetCache()
check("کش اولیه خالی", cache.is_empty)
check("گت روی کش خالی → None", cache.get("ثبت روزانه") is None)

n = cache.update({
    "tabs": [
        {"name": "ثبت روزانه", "headers": ["مجری", "کار"], "rows": [["AG03", "تقویم"], ["", ""]]},
        {"name": "گزارش مدیریتی", "headers": ["هفته", "تعداد"], "rows": [["۴۵", "۱۲"]]},
    ],
    "synced_at": "2026-11-05T09:00",
})
check("۲ تب به‌روز شد", n == 2, str(n))
check("ردیف خالی دور ریخته شد", len(cache.get("ثبت روزانه").rows) == 1)
check("زمان همگام‌سازی ذخیره شد", cache.last_sync == "2026-11-05T09:00", cache.last_sync)
check("شمارندهٔ همگام‌سازی", cache.sync_count == 1)

# قالب دیکشنری
n2 = cache.update({"tabs": {"پیگیری وظایف": {"headers": ["وظیفه", "وضعیت"], "rows": [["A", "باز"]]}}})
check("قالب دیکشنری پذیرفته شد", n2 == 1 and cache.get("پیگیری وظایف") is not None)

# قالب لیست خام
n3 = cache.update({"tabs": {"ثبت تصمیم‌ها": [["تاریخ", "تصمیم"], ["۱۴۰۵/۰۸/۰۱", "لانچ"]]}})
check("قالب ردیف خام پذیرفته شد", n3 == 1)
check("ردیف‌ها ذخیره شدند", len(cache.get("ثبت تصمیم‌ها").rows) == 2)

check("نرمال‌سازی «ي» عربی", normalize_name("ثبت روزانه") == normalize_name("ثبت روزانه"))
check("نرمال‌سازی نیم‌فاصله", normalize_name("ثبت‌روزانه") == normalize_name("ثبت روزانه"))
check("تطبیق جزئی نام تب", cache.get("روزانه") is not None)
check("نام ناموجود → None", cache.get("تب ناموجود") is None)
check("فهرست نام‌ها", set(cache.names()) == {"ثبت روزانه", "گزارش مدیریتی", "پیگیری وظایف", "ثبت تصمیم‌ها"})
check("as_records با کلید ستون", cache.get("ثبت روزانه").as_records()[0]["مجری"] == "AG03")
check("وضعیت کش", cache.status()["tabs"] == 4)

bad = cache.update({"no_tabs": 1})
check("payload بدون tabs → 0", bad == 0)
check("خطا ثبت شد", cache.last_error != "")

cleared = SheetCache()
cleared.update({"tabs": {"x": {"rows": [["a"]]}}})
cleared.clear()
check("پاک‌سازی کش", cleared.is_empty)

# --------------------------------------------------------------------------- #
print("\n=== ۶) جمع‌آوری منابع یک ایجنت ===")
for key, db in {"tasks": "db-tasks", "roles": "db-roles", "revenue": "db-revenue"}.items():
    setattr(settings, {"tasks": "notion_db_tasks", "roles": "notion_db_roles",
                       "revenue": "notion_db_revenue"}[key], db)

fake = FakeNotion({
    "db-tasks": [{"Name": "وظیفه ۱", "Assignee": "AG03", "_page_id": "p1"}],
    "db-roles": [{"Name": "نقش محتوا", "اختیار": "پیشنهاددهنده", "_page_id": "p2"}],
    "db-revenue": [{"Name": "خط B2B", "وضعیت شاهد": "فاقد شاهد", "_page_id": "p3"}],
})

cache2 = SheetCache()
cache2.update({"tabs": [
    {"name": "ثبت روزانه", "headers": ["مجری"], "rows": [["AG03"]]},
    {"name": "راهنما و فهرست‌ها", "headers": ["واژه"], "rows": [["باز"]]},
    {"name": "گزارش مدیریتی", "headers": ["هفته"], "rows": [["۴۵"]]},
]})

bundle = run(gather_sources("AG01", fake, sheets=cache2))
keys = {r.key for r in bundle.results}
check("AG01: tasks+revenue از Notion", "tasks" in keys and "revenue" in keys, str(keys))
check("AG01: به roles دسترسی ندارد", "roles" not in keys)
check("AG01: mgmt_report از Sheets", "mgmt_report" in keys, str(keys))
check("AG01: به daily دسترسی ندارد", "daily" not in keys)
check("بلوک پرامپت ساخته شد", len(bundle.block) > 100)
check("آمار منابع", bundle.stats.get("tasks") == 1, str(bundle.stats))
check("خط فوتر منابع", "بانک مرکزی وظایف: 1" in bundle.footer_line())

bundle9 = run(gather_sources("AG09", fake, sheets=cache2))
check("AG09: دسترسی گسترده (۹ منبع)", len(bundle9.results) == 9, str(len(bundle9.results)))
check("AG09: تب همگام‌نشده → خالی", any(r.status == "empty" for r in bundle9.results))

# منابع تنظیم‌نشده
for f in ("notion_db_tasks", "notion_db_roles", "notion_db_revenue"):
    old = getattr(settings, f)
    setattr(settings, f, "")
bundle_none = run(gather_sources("AG03", fake, sheets=SheetCache()))
check("منابع Notion تنظیم‌نشده → not_configured",
      all(r.status == "not_configured" for r in bundle_none.results if r.kind == "notion"))
check("بلوک با منابع تنظیم‌نشده هم ساخته می‌شود", "دسترسی این منبع" in bundle_none.block)

# Notion خطادار
for key, db in {"tasks": "db-tasks", "roles": "db-roles", "revenue": "db-revenue"}.items():
    setattr(settings, {"tasks": "notion_db_tasks", "roles": "notion_db_roles",
                       "revenue": "notion_db_revenue"}[key], db)
bundle_err = run(gather_sources("AG01", FakeNotion(fail=True), sheets=None))
check("خطای Notion مهار شد (بدون استثنا)",
      all(r.status in {"error", "not_configured", "empty"} for r in bundle_err.results),
      str([(r.key, r.status) for r in bundle_err.results]))
check("خطا در بلوک درج شد", "خطا در خواندن" in bundle_err.block or "دسترسی این منبع" in bundle_err.block)

# ایجنت بدون منبع
check("ایجنت ناشناس → bundle خالی", run(gather_sources("AG99", fake)).empty)

# --------------------------------------------------------------------------- #
print("\n=== ۷) تزریق منابع به Context پرامپت ===")
registry = load_registry()
agent9 = registry.get("AG09")
ctx_with = build_agent_context(agent9, [], [], "امروز چه کارهایی داریم؟", sources=bundle9)
check("بخش ب-۲ در پرامپت", "بخش ب-۲" in ctx_with.user_prompt)
check("منبع در پرامپت درج شد", "بانک مرکزی وظایف" in ctx_with.user_prompt)
check("هشدار فقط‌خواندنی", "فقط‌خواندنی" in ctx_with.user_prompt)
check("یادآوری خالی≠صفر در پرامپت", "صفر» تفسیر نکن" in ctx_with.user_prompt or "صفر تفسیر نکن" in ctx_with.user_prompt)
check("footer در پرامپت", "منابع →" in ctx_with.user_prompt)
check("evidence_hint شامل منابع", "منابع:" in ctx_with.evidence_hint, ctx_with.evidence_hint)

ctx_without = build_agent_context(agent9, [], [], "تست")
check("بدون منبع → اعلام صریح", "هیچ منبع دادهٔ خارجی" in ctx_without.user_prompt)
check("بدون منبع → block خالی", ctx_without.sources_block == "")

# --------------------------------------------------------------------------- #
print("\n=== ۸) قواعد منابع در System Prompt ===")
sp = agent9.full_system_prompt
check("قواعد منابع در System Prompt", "قواعد منابع داده" in sp)
check("قاعدهٔ نام‌بردن منبع", "منبع هر جمله را نام ببر" in sp)
check("قاعدهٔ جدول≠جدول", "جدول ≠ جدول" in sp)
check("قاعدهٔ شناسنامه مصوب نیست", "نیازمند تأیید مدیر پروژه" in sp)
check("قاعدهٔ فقط‌خواندنی", "فقط‌خواندنی" in sp)
check("همهٔ ۹ ایجنت قاعده را دارند",
      all("قواعد منابع داده" in a.full_system_prompt for a in registry.agents.values()))

# --------------------------------------------------------------------------- #
print("\n=== ۹) تنظیمات نسخهٔ ۱.۰.۱ ===")
check("نسخه 1.0.2-beta", settings.app_version == "1.0.2-beta", settings.app_version)
check("منبع حقیقت وظایف پیش‌فرض central", settings.tasks_source == "central")
check("پوش Sheets فقط loopback به‌صورت پیش‌فرض", settings.sheets_push_allow_remote is False)
check("توکن داخلی خالی به‌صورت پیش‌فرض", settings.internal_token == "")
check("source_dbs سه کلید دارد", set(settings.source_dbs) == {"tasks", "roles", "revenue"})
check("URL داخلی Sheets", settings.sheets_internal_url.endswith("/internal/sheets/push"))
check("اولویت notion_db_tasks",
      settings.source_dbs["tasks"] == "db-tasks", settings.source_dbs["tasks"])
settings.notion_tasks_db = "db-old"
settings.notion_db_tasks = ""
check("fallback به notion_tasks_db", settings.source_dbs["tasks"] == "db-old")
settings.notion_db_tasks = "db-tasks"
settings.notion_tasks_db = ""

# --------------------------------------------------------------------------- #
print("\n" + "=" * 60)
print(f"نتیجه: {PASS} ✅ / {FAIL} ❌")
if FAIL:
    raise SystemExit(1)
print("همهٔ تست‌های منابع داده پاس شد.")
