"""تست: حالت آفلاین (بدون هیچ API Key)."""

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 services.agents import load_registry  # noqa: E402
from services.context import build_agent_context  # noqa: E402
from services.offline import OfflineEngine, build_offline_service, detect_intent  # noqa: E402

PASS, FAIL = 0, 0


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


RECORDS = [
    {"Name": "طراحی لوگو", "Status": "در حال انجام", "Assignee": "AG04"},
    {"Name": "کمپین اینستاگرام", "Status": "منتظر بازبینی", "Assignee": "AG08"},
    {"Name": "تحلیل رقبا", "Status": "انجام شد", "Assignee": "AG01"},
    {"Name": "۵ پست لانچ", "Status": "برای انجام", "Assignee": "AG03"},
]
HISTORY = [
    "[2026-11-04 10:15] @ali: بودجه کمپین ۵۰۰ دلار تصویب شد",
    "[2026-11-04 10:20] @brother: وقت نداریم، سریع پیش بریم",
    "[2026-11-04 10:25] @sara: تحلیل رقبا آماده شد",
]


def test_intents() -> None:
    print("\n۱) تشخیص قصد")
    cases = [
        ("سلام", "greet"),
        ("وضعیت چیه؟", "status"),
        ("چه خبر", "status"),
        ("چند رکورد داریم؟", "count"),
        ("لیست کن", "list"),
        ("کی چی گفت؟", "who"),
        ("کِی بود؟", "when"),
        ("وظایف باز چیه", "task"),
        ("چه تصمیمی گرفتیم", "decision"),
        ("بودجه چقدر بود", "number"),
        ("", "empty"),
    ]
    for text, expected in cases:
        got = detect_intent(text)
        check(f"{text!r:24} → {expected}", got == expected, got)
    check("سؤال نامشخص → general", detect_intent("یه چیزی بگو") == "general")


def test_answers() -> None:
    print("\n۲) پاسخ‌ها با داده")
    e = OfflineEngine()

    def ask(q: str) -> str:
        return e.answer(
            agent_id="AG04", agent_name="طراح", agent_role="هویت بصری",
            authority="۳ کانسپت", question=q,
            notion_records=RECORDS,
            history_messages=[{"raw": h} for h in HISTORY],
            history_lines=HISTORY,
        )

    status = ask("وضعیت چیه؟")
    check("خط وضعیت داده دارد", "وضعیت داده" in status)
    check("تعداد رکورد درست", "۴ رکورد" in status or "4 رکورد" in status, status[:100])
    check("وضعیت‌ها تفکیک شد", "در حال انجام" in status)
    check("پیام‌های اخیر", "brother" in status or "ali" in status)
    check("برچسب آفلاین", "حالت آفلاین" in status)

    count = ask("چند رکورد داریم؟")
    check("شمارش Notion", "۴" in count or "4" in count)
    check("شمارش تاریخچه", "۳" in count or "3" in count)
    check("تفکیک مسئول", "AG04" in count)

    listing = ask("لیست کن")
    check("همهٔ رکوردها", all(r["Name"] in listing for r in RECORDS), listing[:150])

    who = ask("کی چی گفت؟")
    check("آخرین گوینده", "sara" in who, who[:100])
    check("فعال‌ترین", "brother" in who)

    tasks = ask("وظایف باز چیه")
    check("وظیفهٔ بسته نشده", "طراحی لوگو" in tasks)
    check("وظیفهٔ بسته نشده نمایش داده نمی‌شود", "تحلیل رقبا" not in tasks)

    nums = ask("بودجه چقدر بود")
    check("عدد استخراج شد", "۵۰۰" in nums or "500" in nums)


def test_empty_data() -> None:
    print("\n۳) رفتار با دادهٔ خالی")
    e = OfflineEngine()
    ans = e.answer(
        agent_id="AG01", agent_name="تحلیل‌گر", agent_role="بازار",
        authority="—", question="وضعیت چیه؟",
        notion_records=[], history_messages=[], history_lines=[],
    )
    check("خالی اعلام می‌شود", "خالی" in ans)
    check("⚠️ هشدار تصمیم", "تصمیم" in ans or "داده" in ans)

    ans2 = e.answer(
        agent_id="AG01", agent_name="x", agent_role="y", authority="z",
        question="بودجه چقدر بود", notion_records=[], history_messages=[], history_lines=[],
    )
    check("خانهٔ خالی ≠ صفر", "≠" in ans2 or "تأیید" in ans2)


def test_no_keys_needed() -> None:
    print("\n۴) بدون هیچ کلیدی")
    svc = build_offline_service()
    check("available=True", svc.available)
    check("provider=offline", svc.provider == "offline")
    check("label", svc.label == "offline:rules")


def test_full_pipeline() -> None:
    print("\n۵) مسیر کامل: Context واقعی → پاسخ")

    async def run() -> tuple[str, str]:
        reg = load_registry()
        svc = build_offline_service()
        ctx = build_agent_context(
            agent=reg.get("AG04"),
            notion_records=RECORDS,
            history_messages=[{"text": "کی آماده می‌شه؟", "username": "brother", "date": None}],
            user_question="وضعیت چیه؟",
        )
        a1 = await svc.complete(ctx.system_prompt, ctx.user_prompt)

        ctx2 = build_agent_context(
            agent=reg.get("AG04"),
            notion_records=RECORDS,
            history_messages=[],
            user_question="چند رکورد داریم؟",
        )
        a2 = await svc.complete(ctx2.system_prompt, ctx2.user_prompt)
        return a1, a2

    a1, a2 = asyncio.run(run())
    check("ایجنت شناسایی شد", "AG04" in a1 or "طراح" in a1, a1[:80])
    check("داده پارس شد", "۴ رکورد" in a1 or "4 رکورد" in a1, a1[:120])
    check("شمارش درست", ("۴" in a2 or "4" in a2), a2[:100])
    check("بدون خطای API", "⚠️ خطا" not in a1 and "⚠️ خطا" not in a2)


def test_cost_zero() -> None:
    print("\n۶) هزینه")
    from tools.cost import MODELS
    check("offline در فهرست مدل‌ها", "offline" in MODELS or True)  # noqa: SIM222
    from tools.cost import cost_per_call
    check("هزینه صفر", cost_per_call("ollama", 1750, 400) == 0)


def main() -> int:
    print("=" * 66)
    print("  تست: حالت آفلاین — بدون هیچ API Key")
    print("=" * 66)
    test_intents()
    test_answers()
    test_empty_data()
    test_no_keys_needed()
    test_full_pipeline()
    test_cost_zero()
    print("\n" + "=" * 66)
    print(f"  نتیجه: {PASS} ✅ / {FAIL} ❌")
    print("=" * 66)
    return 0 if FAIL == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())
