"""اتصال موتور اتوماسیون به ربات تلگرام.

این ماژول مسئول سه چیز است:
  ۱) ساخت Context واقعی برای هر ایجنت (System Prompt + Notion + تاریخچه گروه)
  ۲) اجرای «وظیفه» از تلگرام: /task @ag03 ... → ثبت در Notion
  ۳) راه‌اندازی پولر Notion برای اتوماسیون از داخل Notion

نکته: تمام وابستگی‌ها به‌صورت تزریق‌شده (dependency injection) گرفته می‌شوند تا
حلقهٔ import بین bot.py و services ایجاد نشود.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any, Awaitable, Callable, Optional

from config.settings import settings
from services.context import build_agent_context, split_for_telegram
from services.notion import NotionTaskStore
from services.notion_poller import NotionTaskPoller
from services.orchestrator import OrchestratorEngine, build_task_context
from services.tasks import (
    STATUS_REVIEW,
    status_for,
    Task,
    TaskIndex,
    normalize_agent_id,
    parse_task_message,
)

logger = logging.getLogger(__name__)

#: نوع فرستندهٔ تلگرام: async def (chat_id, text, reply_to) -> None
SendFn = Callable[[int, str, Optional[int]], Awaitable[None]]


class AutomationService:
    """نگه‌دارندهٔ موتورها و اتصال آن‌ها به ربات."""

    def __init__(
        self,
        registry: Any,
        notion_service: Any,
        llm_service: Any,
        mongo_module: Any,
        get_send_fn: Callable[[], Optional[SendFn]],
    ) -> None:
        self.registry = registry
        from services.mention_tasks import MentionTaskGate

        self.mention_gate = MentionTaskGate()
        self.notion = notion_service
        self.llm = llm_service
        self.mongo = mongo_module
        self._get_send = get_send_fn

        self.index = TaskIndex()
        self.task_store: Optional[NotionTaskStore] = None
        self.engine: Optional[OrchestratorEngine] = None
        self.poller: Optional[NotionTaskPoller] = None

        self.rebuild()

    # ------------------------------------------------------------------ #
    def rebuild(self) -> None:
        """پس از تغییر کلیدها/دیتابیس‌ها از ویزارد، همه را از نو می‌سازد."""
        self.task_store = NotionTaskStore(
            notion=self.notion,
            database_id=getattr(settings, "notion_tasks_db", "") or "",
            props=settings.notion_task_props,   # نام پراپرتی‌های واقعی شما
            index=self.index,
        )
        self.engine = OrchestratorEngine(
            task_store=self.task_store,
            run_agent=self.run_agent,
            notify=self._notify,
            auto_close=bool(getattr(settings, "tasks_auto_close", False)),
            max_subtasks=int(getattr(settings, "tasks_max_subtasks", 8)),
        )
        was_running = self.poller is not None and self.poller.running
        self.poller = NotionTaskPoller(
            task_store=self.task_store,
            engine=self.engine,
            interval=int(getattr(settings, "notion_poll_seconds", 30)),
            auto_close=bool(getattr(settings, "tasks_auto_close", False)),
        )
        if was_running:
            self.poller.start()
        logger.info(
            "اتوماسیون نوسازی شد | Notion Tasks: %s | auto_close=%s",
            "فعال" if self.task_store.available else "غیرفعال",
            getattr(settings, "tasks_auto_close", False),
        )

    # ------------------------------------------------------------------ #
    #  ۱) اجرای ایجنت با Context واقعی (برای موتور زنجیره)
    # ------------------------------------------------------------------ #
    async def run_agent(self, agent_id: str, prompt: str, extra_context: str = "") -> str:
        agent = self.registry.get(agent_id)
        if agent is None:
            raise ValueError(f"ایجنت {agent_id} در agents.yaml تعریف نشده است")

        records = await self._fetch_notion_records(agent)
        history = await self._fetch_history(agent_id)

        ctx = build_agent_context(
            agent=agent,
            notion_records=records,
            history_messages=history,
            user_question=prompt,
            tz_name=settings.display_timezone,
            history_limit=settings.history_limit,
        )
        user_prompt = ctx.user_prompt if not extra_context else f"{extra_context}\n\n{ctx.user_prompt}"

        answer = await self.llm.complete(agent.full_system_prompt, user_prompt)

        # ثبت روزانه
        if getattr(settings, "notion_daily_log_db", ""):
            try:
                await self.notion.create_daily_log(
                    agent_id=agent.id,
                    mission_summary=prompt[:300],
                    evidence=ctx.evidence_hint,
                )
            except Exception:  # noqa: BLE001
                logger.exception("ثبت daily_log ناموفق بود")
        return answer

    async def _fetch_notion_records(self, agent: Any) -> list[dict[str, Any]]:
        db_id = settings.notion_db_id(agent.id)
        if not db_id or not self.notion.available:
            return []
        try:
            return await self.notion.fetch_active_records(db_id, limit=10)
        except Exception:  # noqa: BLE001
            logger.exception("خواندن Notion برای %s ناموفق", agent.id)
            return []

    async def _fetch_history(self, agent_id: str, limit: int = 30) -> list[dict[str, Any]]:
        """۳۰ پیام آخر گروه (همه چت‌های ذخیره‌شده)."""
        try:
            return await self.mongo.recent_messages(limit=limit)
        except Exception:  # noqa: BLE001 — امضای متفاوت یا خطای دیتابیس
            logger.debug("خواندن تاریخچه برای %s ناموفق بود", agent_id, exc_info=True)
            return []

    # ------------------------------------------------------------------ #
    #  ۲) ارسال پیام به تلگرام
    # ------------------------------------------------------------------ #
    async def _notify(
        self,
        chat_id: int,
        text: str,
        reply_to: Optional[int] = None,
        thread_id: Optional[int] = None,
    ) -> None:
        """ارسال پیام — اگر تاپیک داشته باشیم، داخل همان تاپیک."""
        send = self._get_send()
        if not send or not chat_id:
            return
        chunks = split_for_telegram(text, limit=settings.max_reply_chars) or [text]
        for chunk in chunks:
            if thread_id:
                # امضای send ممکن است thread_id را بپذیرد یا نه
                try:
                    await send(chat_id, chunk, reply_to, thread_id)
                    continue
                except TypeError:
                    pass
            await send(chat_id, chunk, reply_to)

    # ------------------------------------------------------------------ #
    #  ۳) وظیفه از تلگرام
    # ------------------------------------------------------------------ #
    async def handle_task_message(self, message: Any) -> bool:
        """اگر پیام دستور /task بود، وظیفه بساز. True = رسیدگی شد.

        نسخهٔ ۱.۰.۲ — گیرنده می‌تواند ایجنت یا انسان باشد و می‌تواند چند تا باشد:
            /task @A03 عنوان
            /task @H02 عنوان
            /task @A01-A09 عنوان         → ۹ وظیفه
            /task @H01-H03 عنوان         → ۳ وظیفه
            /task @A03,@H02 عنوان        → ۲ وظیفه
        """
        text = message.text or message.caption or ""
        parsed = parse_task_message(text)
        if parsed is None:
            return False

        from services.assignees import get_registry, split_runnable
        from services.threads import extract_thread, format_source_block, thread_link

        user = message.from_user
        requester = (user.username or user.full_name) if user else "unknown"

        # کنترل دسترسی: فقط مالک/ادمین‌ها (یا سازندگان تعیین‌شده) وظیفه می‌سازند
        from services.access import can_create_tasks

        in_group = getattr(getattr(message, "chat", None), "type", "") != "private"
        if not can_create_tasks(
            user.id if user else None,
            user.username if user else None,
            in_group=in_group,
        ):
            await message.reply_text(
                "⛔ ساخت وظیفه برای شما مجاز نیست.\n"
                "<i>فقط مالک ایجنت‌ها می‌تواند وظیفه تعریف کند. "
                "برای پاسخ گرفتن از ایجنت، با @ag0X منشن کنید.</i>",
                parse_mode="HTML",
            )
            return True

        registry = get_registry()

        # ---------- گیرنده مشخص نشده → راهنما ----------
        if not parsed.targets:
            await message.reply_text(self._task_help(registry), parse_mode="HTML",
                                     disable_web_page_preview=True)
            return True

        # ---------- اعتبارسنجی گیرنده‌ها ----------
        known: list[str] = []
        unknown: list[str] = []
        for raw in parsed.targets:
            if registry.get(raw) is not None:
                if raw not in known:
                    known.append(raw)
            else:
                unknown.append(raw)

        if not known:
            await message.reply_text(
                "🧩 <b>گیرنده شناخته نشد</b>\n\n"
                f"کدهای واردشده: <code>{', '.join(unknown)}</code>\n\n"
                + "\n".join(registry.directory_lines()),
                parse_mode="HTML",
            )
            return True

        # ---------- تاپیک گروه ----------
        thread = extract_thread(message)
        chat_title = getattr(getattr(message, "chat", None), "title", "") or ""

        # ---------- حالت ریپلای ----------
        replied = getattr(message, "reply_to_message", None)
        replied = replied if replied is not None else getattr(message, "external_reply", None)
        reply_text = ""
        reply_author = ""
        reply_msg_id = None
        reply_from_employer = ""
        if replied is not None:
            reply_text = (getattr(replied, "text", None) or getattr(replied, "caption", None) or "").strip()
            ruser = getattr(replied, "from_user", None)
            reply_author = ((ruser.username or ruser.full_name) if ruser else "") or ""
            reply_msg_id = getattr(replied, "message_id", None)
            reply_from_employer = getattr(ruser, "full_name", "") or ""

            inner = getattr(replied, "reply_to_message", None)
            if inner is not None:
                inner_text = (getattr(inner, "text", None) or getattr(inner, "caption", None) or "").strip()
                inner_user = getattr(inner, "from_user", None)
                inner_author = (inner_user.username or inner_user.full_name) if inner_user else ""
                if inner_text:
                    reply_text = f"[{inner_author or '?'}]: {inner_text}\n\n{reply_text}"

        link = thread_link(
            message.chat_id,
            thread.thread_id,
            reply_msg_id or message.message_id,
        )

        title = parsed.title.strip()
        description = parsed.description.strip()

        if parsed.bare and not reply_text:
            await message.reply_text(
                "🧩 <b>روی یک پیام ریپلای کنید</b>\n\n"
                f"<code>/task {known[0].lower()}</code> را <b>ریپلای</b> روی پیام مورد نظر بفرستید،\n"
                "یا عنوان را همان‌جا بنویسید:\n"
                f"<code>/task {known[0].lower()} عنوان وظیفه</code>",
                parse_mode="HTML",
            )
            return True

        if not title:
            if reply_text:
                title = reply_text.splitlines()[0][:300]
            else:
                title = "بدون عنوان"

        source_block = format_source_block(
            chat_title=chat_title,
            topic=thread.label,
            author=requester,
            permalink=link,
            thread_id=thread.thread_id,
        )
        if "─── منبع ───" not in description:
            description = (description or title) + "\n\n" + source_block

        created: list[Task] = []
        from services.assignees import storage_code

        for code in known:
            assignee = registry.get(code)
            is_human = assignee is not None and assignee.is_human
            task = Task(
                title=title[:300],
                assignee=storage_code(code),   # AG03 برای ایجنت، H02 برای انسان
                assignee_code=code,
                description=description or title,
                status=status_for("todo") if not is_human
                else status_for(getattr(__import__("config.settings", fromlist=["settings"]).settings,
                                       "human_task_status", "todo")),
                source="telegram",
                chat_id=message.chat_id,
                message_id=message.message_id,
                requester=requester,
                thread_id=thread.thread_id,
                topic=thread.label,
                chat_title=chat_title,
                permalink=link,
            )
            if self.task_store is not None:
                try:
                    await self.task_store.create(task)
                except Exception:  # noqa: BLE001 — یک گیرندهٔ خراب بقیه را نداشته باشد
                    logger.exception("ثبت وظیفه برای %s ناموفق بود", code)
            created.append(task)

        # ---------- پاسخ تأیید ----------
        await message.reply_text(
            self._task_receipt(created, registry, thread, link, reply_from_employer or reply_author),
            parse_mode="HTML",
            disable_web_page_preview=True,
            **({"message_thread_id": thread.thread_id} if thread.thread_id else {}),
        )

        # ---------- اجرا: فقط ایجنت‌ها ----------
        agent_codes, human_codes = split_runnable(known)
        for task in created:
            if task.is_human:
                continue
            asyncio_task = asyncio.create_task(self._run_now(task))
            _background_tasks.add(asyncio_task)
            asyncio_task.add_done_callback(_background_tasks.discard)

        # ---------- اعلان به انسان‌ها ----------
        for task in created:
            if task.is_human:
                asyncio_task = asyncio.create_task(self._notify_human(task))
                _background_tasks.add(asyncio_task)
                asyncio_task.add_done_callback(_background_tasks.discard)

        return True

    # ------------------------------------------------------------------ #
    #  متن‌های کمکی
    # ------------------------------------------------------------------ #
    @staticmethod
    def _task_help(registry: Any) -> str:
        lines = [
            "🧩 <b>ساخت وظیفه</b>",
            "",
            "<b>فرم‌های پذیرفته‌شده:</b>",
            "<code>/task @A03 عنوان وظیفه</code>",
            "<code>/task @H02 متن را بازنویسی کن</code>",
            "<code>/task @A01-A09 عنوان</code>  → ۹ وظیفه",
            "<code>/task @H01-H03 عنوان</code>  → ۳ وظیفه",
            "<code>/task @A03,@H02 عنوان</code> → ۲ وظیفه",
            "<code>/task @agents عنوان</code>    → همهٔ ایجنت‌ها",
            "<code>/task @humans عنوان</code>    → هر سه انسان",
            "",
            "سپس در خط بعد توضیح کامل را بنویس، یا روی پیام کارفرما <b>ریپلای</b> کن.",
            "",
        ]
        lines.extend(registry.directory_lines())
        lines.append("")
        lines.append("<i>A0X = ایجنت (پاسخ خودکار) · H0X = انسان (منتظر اقدام)</i>")
        return "\n".join(lines)

    @staticmethod
    def _task_receipt(
        created: list[Task],
        registry: Any,
        thread: Any,
        link: str,
        requester_name: str,
    ) -> str:
        """رسید تأیید — تک‌گیرنده و چندگیرنده فرق دارند."""
        if len(created) == 1:
            task = created[0]
            code = task.assignee_code or task.assignee
            assignee = registry.get(code)
            label = assignee.label() if assignee else task.assignee
            # نمایش هم کد کوتاه و هم شناسهٔ ذخیره‌شده، تا با هر عادتی بخواند
            alias = "" if str(code) == str(task.assignee) else f" (<code>{task.assignee}</code>)"
            head = f"🧩 <b>وظیفه ثبت شد</b> → {label}{alias}"
            if task.is_human:
                head += "\n<i>گیرنده انسان است — اجرای خودکار ندارد؛ منتظر اقدام می‌ماند.</i>"
            lines = [head, f"<b>عنوان:</b> {task.title}"]
        else:
            humans = sum(1 for t in created if t.is_human)
            agents = len(created) - humans
            lines = [
                f"🧩 <b>{len(created)} وظیفه ثبت شد</b> "
                f"({agents} ایجنت، {humans} انسان)",
                f"<b>عنوان:</b> {created[0].title}",
                "",
            ]
            for t in created:
                code = t.assignee_code or t.assignee
                assignee = registry.get(code)
                name = assignee.name if assignee else "?"
                icon = "👤" if t.is_human else "🤖"
                lines.append(f"  {icon} <code>{code}</code> {name} — <code>{t.trace_id}</code>")

        if thread.label:
            lines.append(f"<b>تاپیک:</b> {thread.label}")
        if requester_name:
            lines.append(f"<b>درخواست از:</b> {requester_name}")
        if link:
            lines.append(f'<b>منبع:</b> <a href="{link}">پیام اصلی</a>')

        notion_urls = [t.notion_url for t in created if t.notion_url]
        if notion_urls:
            lines.append(f'<a href="{notion_urls[0]}">مشاهده در Notion</a>')
        elif len(created) == 1 and (created[0].notion_url is None):
            lines.append("<i>Notion Tasks تنظیم نشده — وظیفه فقط در حافظه ثبت شد.</i>")

        if any((t.assignee_code or "") == "A09" for t in created):
            lines.append("\n🔄 A09 در حال برنامه‌ریزی زنجیره است…")

        return "\n".join(lines)

    async def _notify_human(self, task: Task) -> None:
        """اعلان وظیفهٔ انسانی در همان تاپیک + تلاش برای منشن واقعی."""
        from services.assignees import get_registry

        registry = get_registry()
        assignee = registry.get(task.assignee_code or task.assignee)
        human = assignee.human if assignee and assignee.human else None

        mention = ""
        if human is not None:
            ids = set()
            try:
                from config.settings import settings

                ids = settings.human_ids(human.id)
            except Exception:  # noqa: BLE001
                ids = set()
            if ids:
                mention = " ".join(f'<a href="tg://user?id={uid}">{human.name}</a>' for uid in ids)
            else:
                mention = f"<b>{human.name}</b>"

        text = (
            f"👤 <b>وظیفهٔ انسانی</b> → {mention or task.assignee}\n"
            f"<b>عنوان:</b> {task.title}\n"
            f"<b>از:</b> {task.requester or 'ناشناس'}\n"
            f"<code>{task.trace_id}</code>\n\n"
            "<i>این وظیفه اجرای خودکار ندارد. وقتی انجام شد، وضعیتش را در Notion عوض کنید.</i>"
        )
        try:
            await self._notify(
                task.chat_id,
                text,
                task.message_id,
                thread_id=getattr(task, "thread_id", None),
            )
        except TypeError:
            try:
                await self._notify(task.chat_id, text, task.message_id)
            except Exception:  # noqa: BLE001
                logger.exception("اعلان وظیفهٔ انسانی %s ناموفق بود", task.trace_id)
        except Exception:  # noqa: BLE001
            logger.exception("اعلان وظیفهٔ انسانی %s ناموفق بود", task.trace_id)

    async def _run_now(self, task: Task) -> None:
        """اجرای فوری وظیفهٔ ساخته‌شده از تلگرام (پولر هم بعداً می‌بیندش)."""
        try:
            if task.assignee == "AG09":
                extra = build_task_context("AG09", task)
                answer = await self.run_agent(
                    "AG09",
                    task.description or task.title,
                    extra + "\n\n" + _subtask_instruction(),
                )
                task.result = answer
                await self.engine.handle_orchestrator_task(task, answer)
            else:
                siblings = [task]
                extra = build_task_context(task.assignee, task, siblings=siblings)
                await self.engine.run_task(task, extra)
        except Exception:  # noqa: BLE001
            logger.exception("اجرای فوری وظیفه ناموفق بود: %s", task.trace_id)

    # ------------------------------------------------------------------ #
    #  ۴) پولر
    # ------------------------------------------------------------------ #
    def start_poller(self) -> bool:
        if self.poller is None or not self.task_store or not self.task_store.available:
            logger.info("پولر Notion راه‌اندازی نشد (Notion Tasks یا NOTION_API_KEY تنظیم نشده).")
            return False
        self.poller.start()
        return True

    async def stop_poller(self) -> None:
        if self.poller is not None:
            await self.poller.stop()

    # ------------------------------------------------------------------ #
    def status(self) -> dict[str, Any]:
        return {
            "notion_tasks_db": bool(getattr(settings, "notion_tasks_db", "")),
            "task_store_available": bool(self.task_store and self.task_store.available),
            "poller_running": bool(self.poller and self.poller.running),
            "poller_stats": dict(self.poller.stats) if self.poller else {},
            "auto_close": bool(getattr(settings, "tasks_auto_close", False)),
            "tasks_in_memory": len(self.index.all()),
        }


def _subtask_instruction() -> str:
    from services.tasks import SUBTASK_JSON_SPEC

    return (
        "## تو AG09 هستی — هماهنگ‌کنندهٔ زنجیره\n"
        "این وظیفه را به وظایف کوچک‌تر قابل اجرا بشکن و به ایجنت درست بسپار.\n\n"
        + SUBTASK_JSON_SPEC
    )


#: نگه‌داری تسک‌های پس‌زمینه تا garbage collector آن‌ها را نبرد
_background_tasks: set[Any] = set()
