"""تست یکپارچه: تلگرام → Notion Tasks → زنجیره → پاسخ.

با Notion شبیه‌سازی‌شده (FakeNotionClient) اجرا می‌شود تا کل مسیر بدون
کلید واقعی تست شود.

اجرا:
    .venv/bin/python tests/test_integration_tasks.py
"""

from __future__ import annotations

import asyncio
import sys
from pathlib import Path
from typing import Any

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

from services.notion import NotionService, NotionTaskStore  # noqa: E402
from services.notion_poller import NotionTaskPoller  # noqa: E402
from services.orchestrator import OrchestratorEngine  # noqa: E402
from services.tasks import (
    status_for,  # noqa: E402
    Task,
    TaskIndex,
)

PASS, FAIL = 0, 0


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


# --------------------------------------------------------------------------- #
#  کلاینت Notion تقلبی (فقط متدهایی که استفاده می‌کنیم)
# --------------------------------------------------------------------------- #
class FakePages:
    def __init__(self, db: "FakeDatabases") -> None:
        self.db = db
        self.counter = 0

    async def create(self, parent: dict, properties: dict) -> dict:
        self.counter += 1
        page_id = f"page-{self.counter:03d}"
        self.db.pages[page_id] = {"properties": properties, "parent": parent}
        return {"id": page_id, "url": f"https://notion.so/{page_id}"}

    async def update(self, page_id: str, properties: dict) -> dict:
        self.db.pages.setdefault(page_id, {"properties": {}})
        self.db.pages[page_id]["properties"].update(properties)
        self.db.updates += 1
        return {"id": page_id}


class FakeDatabases:
    def __init__(self) -> None:
        self.pages: dict[str, dict] = {}
        self.updates = 0

    async def query(self, database_id: str, page_size: int = 25, sorts=None,
                    filter=None, **kw) -> dict:
        """فیلتر ساده: Assignee/Status/ParentTask را اعمال می‌کند."""
        rows = []
        for pid, page in self.pages.items():
            props = page["properties"]
            if filter and not self._match(props, filter):
                continue
            rows.append(self._to_row(pid, props))
        return {"results": rows[:page_size]}

    @staticmethod
    def _prop_value(prop: dict) -> Any:
        if not prop:
            return None
        t = prop.get("type") or next(iter(prop.keys()), None)
        if t in {"title", "rich_text"}:
            return "".join(
                x.get("plain_text") or (x.get("text") or {}).get("content", "")
                for x in prop.get(t, [])
            )
        if t in {"select", "status"}:
            v = prop.get(t)
            return v.get("name") if isinstance(v, dict) else None
        if t == "number":
            return prop.get("number")
        if t == "date":
            v = prop.get("date")
            return v.get("start") if isinstance(v, dict) else None
        return None

    def _match(self, props: dict, flt: dict) -> bool:
        if "and" in flt:
            return all(self._match(props, f) for f in flt["and"])
        if "or" in flt:
            return any(self._match(props, f) for f in flt["or"])
        name = flt.get("property")
        prop = props.get(name, {})
        if "select" in flt:
            return self._prop_value(prop) == flt["select"].get("equals")
        if "status" in flt:
            return self._prop_value(prop) == flt["status"].get("equals")
        if "rich_text" in flt:
            return self._prop_value(prop) == flt["rich_text"].get("equals")
        return True

    @staticmethod
    def _with_type(props: dict) -> dict:
        """API واقعی Notion کلید `type` را همیشه برمی‌گرداند؛ اینجا هم اضافه می‌شود."""
        out = {}
        for k, v in props.items():
            if isinstance(v, dict) and "type" not in v:
                for t in ("title", "rich_text", "select", "status", "number", "date",
                          "multi_select", "checkbox", "url"):
                    if t in v:
                        v = {**v, "type": t}
                        break
            out[k] = v
        return out

    @staticmethod
    def _to_row(pid: str, props: dict) -> dict:
        typed = FakeDatabases._with_type(props)
        # خروجی API واقعی Notion: {"id", "properties": {...}}
        page = {"id": pid, "url": f"https://notion.so/{pid}",
                "last_edited_time": "2025-01-01T00:00:00Z", "properties": typed}
        from services.notion import flatten_page
        row = flatten_page(page)
        row["_url"] = f"https://notion.so/{pid}"
        return row


class FakeClient:
    def __init__(self) -> None:
        self.databases = FakeDatabases()
        self.pages = FakePages(self.databases)

    async def aclose(self) -> None:
        return None


def make_store() -> tuple[NotionTaskStore, FakeClient]:
    client = FakeClient()
    svc = NotionService(api_key="dummy")
    svc._client = client          # noqa: SLF001 — تزریق کلاینت تقلبی
    store = NotionTaskStore(notion=svc, database_id="db-tasks", index=TaskIndex())
    return store, client


# --------------------------------------------------------------------------- #
async def test_create_and_query() -> None:
    print("\n۱) ساخت وظیفه در Notion و خواندن با فیلتر")
    store, client = make_store()
    t = Task(title="تحلیل بازار", assignee="AG01", description="رقبا", chat_id=555)
    await store.create(t)

    check("صفحه ساخته شد", t.notion_page_id is not None, t.notion_page_id)
    check("لینک دارد", bool(t.notion_url))

    rows = await store.query(assignee="AG01", statuses=[status_for("todo")])
    check("کوئری با فیلتر ایجنت", len(rows) == 1, rows)
    check("عنوان درست", rows and rows[0]["Name"] == "تحلیل بازار", rows)
    check("Status درست", rows and rows[0]["Status"] == status_for("todo"), rows)

    rows2 = await store.query(assignee="AG05")
    check("فیلتر ایجنت اشتباه", rows2 == [], rows2)


async def test_status_and_result() -> None:
    print("\n۲) تغییر وضعیت و ذخیرهٔ نتیجه")
    store, client = make_store()
    t = Task(title="x", assignee="AG02")
    await store.create(t)

    await store.set_status(t, status_for("doing"))
    check("وضعیت حافظه", t.status == status_for("doing"))
    rows = await store.query(assignee="AG02", statuses=[status_for("doing")])
    check("وضعیت در Notion", len(rows) == 1, rows)

    await store.save_result(t, "نتیجهٔ نهایی", "شاهد: رکورد ۱")
    check("نتیجه ذخیره شد", t.result == "نتیجهٔ نهایی")
    rows = await store.query(assignee="AG02")
    check("نتیجه در Notion", rows[0]["Result"] == "نتیجهٔ نهایی", rows)
    check("وضعیت به بازبینی رفت", rows[0]["Status"] == "منتظر بازبینی", rows)


async def test_children() -> None:
    print("\n۳) زیرکارها با ParentTask")
    store, _ = make_store()
    parent = Task(title="والد", assignee="AG09")
    await store.create(parent)

    for i, ag in enumerate(["AG01", "AG04"], 1):
        child = Task(title=f"زیرکار {i}", assignee=ag, parent_task_id=parent.trace_id)
        await store.create(child)

    kids = await store.children(parent.trace_id)
    check("۲ زیرکار", len(kids) == 2, kids)
    check("والد درست", all(k["ParentTask"] == parent.trace_id for k in kids), kids)


# --------------------------------------------------------------------------- #
async def test_poller_end_to_end() -> None:
    print("\n۴) پولر Notion: وظیفهٔ AG01 → اجرا → نتیجه در Notion")
    store, _ = make_store()
    calls: list[str] = []
    messages: list[str] = []

    async def runner(agent_id: str, prompt: str, ctx: str) -> str:
        calls.append(agent_id)
        return f"[شاهد: پیام ۱۲] پاسخ {agent_id}"

    async def notify(chat_id, text, reply_to):
        messages.append(text)

    engine = OrchestratorEngine(task_store=store, run_agent=runner, notify=notify, auto_close=True)
    poller = NotionTaskPoller(task_store=store, engine=engine, interval=10, auto_close=True)

    # یک وظیفه در Notion «می‌نشیند» (مثل وقتی کاربر در Notion رکورد می‌سازد)
    t = Task(title="بررسی سئو", assignee="AG06", description="لندینگ را چک کن", chat_id=777)
    await store.create(t)

    executed = await poller.tick()
    check("۱ وظیفه اجرا شد", executed == 1, executed)
    check("ایجنت درست صدا زده شد", calls == ["AG06"], calls)

    rows = await store.query(assignee="AG06")
    check("وضعیت نهایی DONE", rows[0]["Status"] == status_for("done"), rows[0]["Status"])
    check("نتیجه در Notion", "پاسخ AG06" in (rows[0]["Result"] or ""), rows)

    # اجرای دوباره نباید تکرار شود
    executed2 = await poller.tick()
    check("بدون اجرای تکراری", executed2 == 0, executed2)


async def test_poller_orchestrator_chain() -> None:
    print("\n۵) پولر Notion: وظیفهٔ AG09 → زنجیرهٔ ۳ ایجنت → بسته شدن")
    store, _ = make_store()
    order: list[str] = []
    messages: list[str] = []

    async def runner(agent_id: str, prompt: str, ctx: str) -> str:
        order.append(agent_id)
        if agent_id == "AG09":
            return (
                "برنامه:\n```json\n"
                '{"subtasks":['
                '{"assignee":"AG01","title":"تحلیل","description":"بازار"},'
                '{"assignee":"AG04","title":"لوگو","description":"۳ کانسپت"},'
                '{"assignee":"AG03","title":"محتوا","description":"۵ پست"}]}'
                "\n```"
            )
        return f"خروجی {agent_id}"

    async def notify(chat_id, text, reply_to):
        messages.append(text)

    engine = OrchestratorEngine(task_store=store, run_agent=runner, notify=notify, auto_close=True)
    poller = NotionTaskPoller(task_store=store, engine=engine, interval=10, auto_close=True)

    parent = Task(title="کمپین لوگو", assignee="AG09", description="لوگو + محتوا", chat_id=42)
    await store.create(parent)

    await poller.tick()
    check("AG09 اجرا شد", "AG09" in order, order)
    check("زیرکارها ساخته شدند", len([t for t in store.index.all() if t.parent_task_id]) == 3,
          len(store.index.all()))
    check("ترتیب اجرا درست", order == ["AG09", "AG01", "AG04", "AG03"], order)
    # والد در Notion باید «انجام شد» شده باشد (شیء پولر نمونهٔ جدا از شیء تست است)
    parent_rows = await store.query(assignee="AG09")
    check("والد بسته شد", parent_rows and parent_rows[0]["Status"] == status_for("done"),
          parent_rows[0]["Status"] if parent_rows else None)
    check("پیام «زنجیره بسته شد»", any("زنجیره بسته شد" in m for m in messages), messages[-3:])

    # زیرکارها در Notion با ParentTask ثبت شده‌اند
    kids = await store.children(parent.trace_id)
    check("زیرکارها در Notion", len(kids) == 3, len(kids))
    check("همه DONE", all(k["Status"] == status_for("done") for k in kids), [k["Status"] for k in kids])


async def test_poller_disabled_without_notion() -> None:
    print("\n۶) رفتار امن بدون Notion")
    from services.notion import NotionTaskStore as Store

    svc = NotionService(api_key="")   # بدون کلید → available=False
    store = Store(notion=svc, database_id="", index=TaskIndex())
    check("store غیرفعال است", not store.available)

    async def runner(a, p, c):
        return "x"

    async def notify(c, t, r):
        return None

    engine = OrchestratorEngine(task_store=store, run_agent=runner, notify=notify, auto_close=True)
    poller = NotionTaskPoller(task_store=store, engine=engine)
    executed = await poller.tick()
    check("پولر بدون Notion کاری نمی‌کند", executed == 0, executed)

    # ولی ساخت وظیفه در حافظه کار می‌کند (fallback)
    t = Task(title="فقط حافظه", assignee="AG01")
    await store.create(t)
    check("fallback حافظه", len(store.index.all()) == 1, len(store.index.all()))


# --------------------------------------------------------------------------- #
async def main() -> int:
    print("=" * 66)
    print("  تست یکپارچه: تلگرام → Notion Tasks → زنجیره → پاسخ")
    print("=" * 66)
    await test_create_and_query()
    await test_status_and_result()
    await test_children()
    await test_poller_end_to_end()
    await test_poller_orchestrator_chain()
    await test_poller_disabled_without_notion()

    print("\n" + "=" * 66)
    print(f"  نتیجه: {PASS} ✅ / {FAIL} ❌")
    print("=" * 66)
    return 0 if FAIL == 0 else 1


if __name__ == "__main__":
    raise SystemExit(asyncio.run(main()))
