"""پولر Notion — اتوماسیون «هر وقت در Notion ایجنتی را منشن کردیم».

چرا polling و نه webhook؟
  Notion فقط برای **یک** integration می‌تواند webhook بفرستد و آن هم نیاز به
  تأیید و endpoint عمومی HTTPS دارد. برای اجرا روی هاست/سرور بدون دامنه،
  polling ساده‌تر، مطمئن‌تر و بدون کانفیگ اضافه است.

چرخهٔ هر ۳۰ ثانیه:
  ۱) دیتابیس Tasks را می‌خواند: رکوردهایی که Status ∈ {بک‌لاگ, برای انجام}
  ۲) هر رکورد را به یک Task تبدیل می‌کند
  ۳) ایجنت مسئول پاسخ می‌دهد → نتیجه در Notion نوشته می‌شود
  ۴) اگر ایجنت AG09 باشد → زیرکارها ساخته و زنجیره اجرا می‌شود
  ۵) زنجیره که کامل شد، همه «انجام شد» و اتوماسیون خاموش می‌شود
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any, Optional

from services.assignees import agent_id as agent_from_code
from services.assignees import is_human, normalize_code
from services.tasks import (
    Task,
    normalize_agent_id,
    runnable_statuses,
    status_for,
)

logger = logging.getLogger(__name__)


class NotionTaskPoller:
    def __init__(
        self,
        task_store: Any,
        engine: Any,
        agent_ids: Optional[list[str]] = None,
        interval: int = 30,
        auto_close: bool = False,
        history_provider: Optional[Any] = None,
    ) -> None:
        self.task_store = task_store
        self.engine = engine
        # AG09 آخر صدا زده می‌شود تا هماهنگ‌کننده بعد از ایجنت‌های تخصصی اجرا شود
        self.agent_ids = agent_ids or [
            f"AG{i:02d}" for i in range(1, 9)
        ] + ["AG09"]
        self.interval = max(10, interval)
        self.auto_close = auto_close
        self.history_provider = history_provider
        self._task: Optional[asyncio.Task] = None
        self._stop = asyncio.Event()
        self._seen: set[str] = set()
        self.stats = {"scanned": 0, "executed": 0, "errors": 0, "chains": 0}

    # ------------------------------------------------------------------ #
    @property
    def running(self) -> bool:
        return self._task is not None and not self._task.done()

    def start(self) -> None:
        if self.running:
            return
        self._stop.clear()
        self._task = asyncio.create_task(self._loop(), name="notion-task-poller")
        logger.info("Notion task poller شروع شد (هر %s ثانیه)", self.interval)

    async def stop(self) -> None:
        self._stop.set()
        if self._task:
            try:
                await asyncio.wait_for(self._task, timeout=10)
            except (asyncio.TimeoutError, asyncio.CancelledError):
                self._task.cancel()
        self._task = None
        logger.info("Notion task poller متوقف شد")

    # ------------------------------------------------------------------ #
    async def _loop(self) -> None:
        while not self._stop.is_set():
            try:
                await self.tick()
            except Exception:  # noqa: BLE001 — پولر هرگز نباید بمیرد
                self.stats["errors"] += 1
                logger.exception("خطا در چرخهٔ Notion poller")
            try:
                await asyncio.wait_for(self._stop.wait(), timeout=self.interval)
            except asyncio.TimeoutError:
                pass

    # ------------------------------------------------------------------ #
    def _row_to_task(self, row: dict[str, Any], hydrate: bool = False) -> Optional[Task]:
        """تبدیل رکورد Notion (خروجی flatten_page) به Task.

        نسخهٔ ۱.۰.۲: ستون Assignee می‌تواند ایجنت (A01..A09/AG01..AG09)
        یا انسان (H01..H03) باشد.
        """
        props = self.task_store.props
        raw_assignee = str(row.get(props.get("assignee", "Assignee"), "") or "")

        if not raw_assignee.strip():
            return None

        assignee_code = normalize_code(raw_assignee)
        if assignee_code is None:
            # اگر کد نبود ولی نام ایجنت بود، تلاش قدیمی
            if normalize_agent_id(raw_assignee):
                assignee_code = normalize_code(normalize_agent_id(raw_assignee))
            else:
                logger.info("گیرندهٔ ناشناخته در رکورد %s: %r — رد شد",
                            row.get("_page_id"), raw_assignee)
                return None

        # وظیفهٔ انسانی در صف اجرا نیست
        if is_human(assignee_code):
            logger.debug("وظیفهٔ انسانی %s در صف اجرا نیست", assignee_code)
            return None

        assignee = assignee_code
        agent_id = agent_from_code(assignee_code) or assignee_code
        trace = str(row.get(props.get("trace", "TraceID"), "") or "") or (row.get("_page_id") or "")
        task = Task(
            title=str(row.get(props.get("title", "Name"), "") or "بدون عنوان"),
            assignee=agent_id,
            assignee_code=assignee_code,
            description=str(row.get(props.get("description", "Description"), "") or ""),
            status=str(row.get(props.get("status", "Status"), "") or status_for("todo")),
            priority=str(row.get(props.get("priority", "Priority"), "") or "متوسط"),
            parent_task_id=str(row.get(props.get("parent", "ParentTask"), "") or "") or None,
            source=str(row.get(props.get("source", "Source"), "") or "notion"),
            chat_id=row.get(props.get("chat_id", "ChatID")) or None,
            requester=str(row.get(props.get("requester", "Requester"), "") or ""),
            notion_page_id=row.get("_page_id"),
            notion_url=row.get("_url"),
            result=str(row.get(props.get("result", "Result"), "") or ""),
            evidence=str(row.get(props.get("evidence", "Evidence"), "") or ""),
            trace_id=trace,
        )
        if hydrate:
            # وصل کردن صفحهٔ واقعی Notion به شیء Task تا update/set_status کار کند
            task.notion_page_id = row.get("_page_id")
            task.notion_url = row.get("_url")
        return task

    # ------------------------------------------------------------------ #
    async def tick(self) -> int:
        """یک چرخهٔ کامل. تعداد وظایف اجراشده را برمی‌گرداند."""
        if not getattr(self.task_store, "available", False):
            return 0

        executed = 0
        for agent_id in self.agent_ids:
            rows = await self.task_store.query(
                assignee=agent_id, statuses=runnable_statuses(), limit=5
            )
            for row in rows:
                self.stats["scanned"] += 1
                task = self._row_to_task(row, hydrate=True)
                if task is None:
                    continue
                # جلوگیری از اجرای دوباره با کلید پایدار (page_id + status)
                key = f"{task.notion_page_id}:{agent_id}:{task.trace_id}"
                if key in self._seen:
                    continue
                self._seen.add(key)

                logger.info("اجرای وظیفهٔ Notion: %s → %s", task.title, agent_id)
                ok = await self._execute(task)
                if ok:
                    executed += 1
                    self.stats["executed"] += 1
        self._trim_seen()
        return executed

    def _trim_seen(self, limit: int = 2000) -> None:
        if len(self._seen) > limit:
            self._seen = set(list(self._seen)[-limit // 2 :])

    # ------------------------------------------------------------------ #
    async def _execute(self, task: Task) -> bool:
        await self._set_status(task, status_for("doing"))
        extra = ""
        if task.parent_task_id:
            extra = f"- این وظیفه زیرمجموعهٔ زنجیرهٔ {task.parent_task_id} است.\n"

        try:
            answer = await self.engine.run_agent(task.assignee, task.description or task.title, extra)
        except Exception as exc:  # noqa: BLE001
            logger.exception("اجرای ایجنت %s شکست خورد", task.assignee)
            await self._set_status(task, status_for("blocked"))
            task.evidence = f"خطا: {exc}"
            await self.task_store.update(task, {"evidence": task.evidence})
            return False

        # AG09 = مشاور/هماهنگ‌کننده → زنجیره بساز
        if task.assignee == "AG09":
            self.stats["chains"] += 1
            chain = await self.engine.handle_orchestrator_task(task, answer, extra)
            return chain.completed or bool(chain.subtasks)

        next_status = status_for("done") if self.auto_close else status_for("review")
        task.result = answer
        task.status = next_status
        await self.task_store.update(
            task, {"result": answer, "status": next_status, "evidence": task.evidence}
        )
        await self.engine._say(   # noqa: SLF001 — ارسال گزارش به تلگرام
            task.chat_id,
            f"{'✅' if self.auto_close else '👀'} {task.assignee} — {task.title}\n\n{answer[:3500]}",
            None,
        )
        return True

    async def _set_status(self, task: Task, status: str) -> None:
        task.status = status
        try:
            await self.task_store.set_status(task, status)
        except Exception:  # noqa: BLE001
            logger.exception("تغییر وضعیت وظیفه ناموفق: %s", task.trace_id)
