"""موتور اتوماسیون زنجیره‌ای (Orchestrator Engine).

چرخهٔ کار:
    ┌──────────────┐   AG09 پاسخ می‌دهد + بلوک JSON زیرکارها
    │  وظیفهٔ والد │──────────────┐
    └──────────────┘              ▼
                         ┌──────────────────┐
                         │ ساخت زیرکارها   │  (Notion + ایندکس)
                         └──────────────────┘
                                  ▼
            ┌─────────────────────────────────────┐
            │ برای هر زیرکار به‌ترتیب:            │
            │   ایجنت مسئول → LLM → پاسخ          │
            │   → ذخیره در Result + تلگرام        │
            └─────────────────────────────────────┘
                                  ▼
                    همه بسته شد؟ → زنجیره DONE (اتوماسیون خاموش)

اصول:
  • ترتیب اجرا = ترتیب آرایهٔ subtasks (وابستگی خطی).
  • هر زیرکار پس از پاسخ به «منتظر بازبینی» می‌رود (نه مستقیم «انجام شد»)،
    چون قاعدهٔ پروژه: تصمیم نهایی با مدیر است.
  • اگر MANAGER_AUTO_CLOSE=true باشد، «منتظر بازبینی» خودکار «انجام شد» می‌شود
    تا زنجیره بدون دخالت انسان پیش برود.
  • هر وظیفه فقط یک بار اجرا می‌شود (status از «برای انجام» به «در حال انجام»).
"""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable, Optional

from services.tasks import (
    Task,
    chain_is_complete,
    parse_subtasks,
    status_for,
    summarize_chain,
)

logger = logging.getLogger(__name__)

#: فرستندهٔ پیام: async def (chat_id: int, text: str, reply_to: int | None) -> None
NotifyFn = Callable[[int, str, Optional[int]], Awaitable[None]]

#: اجراکنندهٔ ایجنت: async def (agent_id: str, prompt: str, extra_context: str) -> str
AgentRunnerFn = Callable[[str, str, str], Awaitable[str]]


@dataclass
class ChainResult:
    trace_id: str
    parent_task: Task
    subtasks: list[Task] = field(default_factory=list)
    completed: bool = False
    failed: list[str] = field(default_factory=list)

    @property
    def summary(self) -> str:
        lines = [f"🧩 زنجیرهٔ {self.parent_task.assignee} — {self.parent_task.title}"]
        lines.append(summarize_chain([self.parent_task, *self.subtasks]))
        if self.failed:
            lines.append("⚠️ ناموفق: " + ", ".join(self.failed))
        return "\n".join(lines)


class OrchestratorEngine:
    """اجرای زنجیرهٔ وظایف بین ایجنت‌ها."""

    def __init__(
        self,
        task_store: Any = None,
        run_agent: Optional[AgentRunnerFn] = None,
        notify: Optional[NotifyFn] = None,
        auto_close: bool = False,
        max_depth: int = 3,
        max_subtasks: int = 8,
    ) -> None:
        self.task_store = task_store
        self.run_agent = run_agent
        self.notify = notify
        self.auto_close = auto_close
        self.max_depth = max_depth
        self.max_subtasks = max_subtasks

    # ------------------------------------------------------------------ #
    async def _say(
        self,
        chat_id: Optional[int],
        text: str,
        reply_to: Optional[int] = None,
        thread_id: Optional[int] = None,
    ) -> None:
        if not chat_id or not self.notify:
            return
        try:
            try:
                await self.notify(chat_id, text, reply_to, thread_id)
            except TypeError:
                await self.notify(chat_id, text, reply_to)
        except Exception:  # noqa: BLE001 — اعلان نباید زنجیره را بشکند
            logger.exception("ارسال اعلان تلگرام ناموفق بود")

    async def _set_status(self, task: Task, status: str) -> None:
        task.status = status
        if self.task_store is None:
            return
        try:
            # وظیفهٔ ساخته‌شده از Notion قبلاً صفحه دارد → update؛ وگرنه set_status
            if getattr(task, "notion_page_id", None):
                await self.task_store.update(task, {"status": status})
            else:
                await self.task_store.set_status(task, status)
        except Exception:  # noqa: BLE001
            logger.exception("به‌روزرسانی وضعیت وظیفه ناموفق: %s", task.trace_id)

    # ------------------------------------------------------------------ #
    async def handle_parent_response(self, parent: Task, response_text: str) -> ChainResult:
        """پاسخ ایجنت والد (معمولاً AG09) را می‌گیرد و زیرکارها را می‌سازد."""
        result = ChainResult(trace_id=parent.trace_id, parent_task=parent)

        subtasks_spec = parse_subtasks(response_text)[: self.max_subtasks]
        if not subtasks_spec:
            # وظیفه‌ای برای تقسیم نبود → خودِ پاسخ، نتیجهٔ نهایی است
            await self._set_status(parent, status_for("done") if self.auto_close else status_for("review"))
            result.completed = True
            logger.info("زنجیره بدون زیرکار بسته شد: %s", parent.trace_id)
            return result

        await self._say(
            parent.chat_id,
            f"🧩 {parent.assignee} زنجیره را برنامه‌ریزی کرد — {len(subtasks_spec)} وظیفه:",
        )

        for spec in subtasks_spec:
            child = Task(
                title=spec["title"],
                assignee=spec["assignee"],
                description=spec["description"],
                status=status_for("todo"),
                priority=spec.get("priority", "متوسط"),
                parent_task_id=parent.trace_id,
                source="orchestrator",
                chat_id=parent.chat_id,
                message_id=parent.message_id,
                requester=parent.requester,
            )
            if self.task_store is not None:
                try:
                    await self.task_store.create(child)
                except Exception:  # noqa: BLE001
                    logger.exception("ساخت زیرکار ناموفق: %s", child.title)
            result.subtasks.append(child)

        await self._say(parent.chat_id, summarize_chain(result.subtasks), thread_id=getattr(parent, 'thread_id', None))
        return result

    # ------------------------------------------------------------------ #
    async def run_task(self, task: Task, extra_context: str = "") -> bool:
        """یک وظیفه را با ایجنت مسئولش اجرا می‌کند. True = موفق."""
        if not self.run_agent:
            logger.warning("run_agent تنظیم نشده است")
            return False

        await self._set_status(task, status_for("doing"))
        prompt = task.description or task.title
        try:
            answer = await self.run_agent(task.assignee, prompt, extra_context)
        except Exception as exc:  # noqa: BLE001
            logger.exception("اجرای وظیفه ناموفق: %s", task.trace_id)
            await self._set_status(task, status_for("blocked"))
            task.evidence = f"خطا: {exc}"
            await self._say(task.chat_id, f"⛔ {task.assignee} — {task.title}\nخطا در اجرا.", thread_id=getattr(task, 'thread_id', None))
            return False

        task.result = answer
        next_status = status_for("done") if self.auto_close else status_for("review")
        task.status = next_status

        if self.task_store is not None:
            try:
                await self.task_store.update(
                    task, {"result": answer, "status": next_status, "evidence": task.evidence}
                )
            except Exception:  # noqa: BLE001
                logger.exception("ذخیرهٔ نتیجهٔ وظیفه ناموفق: %s", task.trace_id)

        icon = "✅" if self.auto_close else "👀"
        await self._say(
            task.chat_id,
            f"{icon} {task.assignee} — {task.title}\n\n{answer[:3500]}",
            task.message_id,
        )
        return True

    # ------------------------------------------------------------------ #
    async def run_chain(self, parent: Task, children: list[Task], extra_context: str = "") -> ChainResult:
        """زیرکارهای یک زنجیره را به‌ترتیب اجرا می‌کند."""
        result = ChainResult(trace_id=parent.trace_id, parent_task=parent, subtasks=list(children))

        for idx, child in enumerate(children, start=1):
            if child.status != status_for("todo"):
                continue
            progress = f"🔄 ({idx}/{len(children)}) {child.assignee} — {child.title}"
            await self._say(child.chat_id, progress, thread_id=getattr(child, 'thread_id', None))
            ok = await self.run_task(child, extra_context)
            if not ok:
                result.failed.append(f"{child.assignee}: {child.title}")
                # وابستگی خطی: اگر یکی شکست خورد، بقیه مسدود می‌شوند
                for rest in children[idx:]:
                    if rest.status == status_for("todo"):
                        await self._set_status(rest, status_for("blocked"))
                break

        done = all(c.status in {status_for("done"), status_for("review")} for c in children)
        if done:
            await self._set_status(parent, status_for("done") if self.auto_close else status_for("review"))
            result.completed = True
            await self._say(
                parent.chat_id,
                f"🎉 زنجیره بسته شد — {parent.assignee} / {parent.title}\n" + summarize_chain(children),
            )
        return result

    # ------------------------------------------------------------------ #
    async def handle_orchestrator_task(
        self, parent: Task, response_text: str, extra_context: str = ""
    ) -> ChainResult:
        """مسیر کامل: پاسخ AG09 → ساخت زیرکارها → اجرای زنجیره."""
        chain = await self.handle_parent_response(parent, response_text)
        if not chain.subtasks:
            return chain
        return await self.run_chain(parent, chain.subtasks, extra_context)


# --------------------------------------------------------------------------- #
#  ساخت Context برای هر ایجنت درون زنجیره
# --------------------------------------------------------------------------- #
def build_task_context(
    agent_id: str,
    task: Task,
    siblings: Optional[list[Task]] = None,
    parent: Optional[Task] = None,
) -> str:
    """متنی که قبل از پرامپت اصلی به LLM داده می‌شود."""
    lines = [
        f"## وظیفهٔ محول‌شده به تو ({agent_id})",
        f"- عنوان: {task.title}",
        f"- توضیح: {task.description or '(بدون توضیح)'}",
        f"- اولویت: {task.priority}",
        f"- شناسهٔ وظیفه: {task.trace_id}",
    ]
    if parent:
        lines.append(f"- وظیفهٔ والد: {parent.title} (توسط {parent.assignee})")
    if siblings:
        lines.append("\n## سایر وظایف این زنجیره (به‌ترتیب اجرا)")
        for i, s in enumerate(siblings, 1):
            mark = "→" if s.trace_id == task.trace_id else " "
            lines.append(f"{mark} {i}. {s.assignee}: {s.title} [{s.status}]")
            if s.result and s.assignee != agent_id:
                lines.append(f"     نتیجهٔ قبلی: {s.result[:600]}")
    lines.append(
        "\n## الزامات خروجی\n"
        "- پاسخ نهایی و قابل استفاده بده (نه توضیح دربارهٔ اینکه چه کاری می‌کنی).\n"
        "- هر ادعا با `[شاهد: ...]` یا `⚠️ نیازمند تأیید`.\n"
        "- حداقل یک «✅ اقدام بعدی» با حداکثر ۳ مورد.\n"
    )
    return "\n".join(lines)
