"""تشخیص ایجنت هدف از متن پیام (Routing)."""

from __future__ import annotations

import logging
import re
from dataclasses import dataclass
from enum import Enum
from typing import Optional

from services.agents import AgentRegistry

logger = logging.getLogger(__name__)


class RouteKind(str, Enum):
    IGNORE = "ignore"          # فقط ذخیره
    SINGLE = "single"          # یک ایجنت منشن شده
    ALL = "all"                # /all
    DAILY = "daily"            # /daily
    HELP = "help"              # /start /help
    TASKS = "tasks"            # /tasks — دیدن وظایف زنجیره
    WIRING = "wiring"          # /wiring — عیب‌یابی اتصال Notion
    DISABLED = "disabled"      # منشن به ایجنتی که فعلاً غیرفعال است
    HUMAN = "human"            # منشن به یک انسان (H01..H03) — نه پاسخ ایجنت


@dataclass(frozen=True)
class Route:
    kind: RouteKind
    agent_id: Optional[str] = None
    mention_text: Optional[str] = None
    agent_name: Optional[str] = None
    extra_args: str = ""

    @property
    def should_reply(self) -> bool:
        return self.kind in {
            RouteKind.SINGLE,
            RouteKind.ALL,
            RouteKind.DAILY,
            RouteKind.HELP,
            RouteKind.TASKS,
            RouteKind.WIRING,
            RouteKind.DISABLED,
            RouteKind.HUMAN,
        }


#: منشن ایجنت: @ag03 / @a03 / @a3
_MENTION_RE = re.compile(r"@(?:ag|a)0?([1-9])\b", re.IGNORECASE)
#: منشن انسان: @h02 / @h2
_HUMAN_MENTION_RE = re.compile(r"@h0?([1-9])\b", re.IGNORECASE)
# دستورها ممکن است با نام ربات همراه باشند: /all@MyBot
_COMMAND_RE = re.compile(r"^\s*/(all|daily|help|start|tasks|wiring|diagnose)\b(?:@\w+)?\s*(.*)$", re.IGNORECASE | re.DOTALL)


def route_message(text: str, registry: AgentRegistry) -> Route:
    """قواعد روتینگ:
    - منشن @ag01..@ag08 → فقط همان ایجنت
    - /all → همه ایجنت‌های فعال
    - /daily → خلاصه روزانه از Notion
    - بقیه → فقط ذخیره
    """
    if not text or not text.strip():
        return Route(RouteKind.IGNORE)

    command_match = _COMMAND_RE.match(text)
    if command_match:
        command = command_match.group(1).lower()
        args = (command_match.group(2) or "").strip()
        if command == "all":
            return Route(RouteKind.ALL, extra_args=args)
        if command == "daily":
            return Route(RouteKind.DAILY)
        if command in {"help", "start"}:
            return Route(RouteKind.HELP)
        if command == "tasks":
            return Route(RouteKind.TASKS)
        if command in {"wiring", "diagnose"}:
            return Route(RouteKind.WIRING)

    for match in _MENTION_RE.finditer(text):
        agent_id = f"AG{match.group(1).zfill(2)}"
        agent = registry.get(agent_id)
        if agent is None:
            continue
        if not agent.enabled:
            logger.info("منشن به ایجنت غیرفعال %s داده شد.", agent_id)
            return Route(
                RouteKind.DISABLED,
                agent_id=agent.id,
                mention_text=match.group(0),
                agent_name=agent.name,
            )
        return Route(RouteKind.SINGLE, agent_id=agent.id, mention_text=match.group(0))

    # منشن انسان: @h02 — ربات پاسخ نمی‌دهد، فقط می‌فهمد که پیام به یک انسان است
    human_match = _HUMAN_MENTION_RE.search(text)
    if human_match:
        from services.assignees import get_registry

        registry_humans = get_registry()
        code = f"H{human_match.group(1).zfill(2)}"
        assignee = registry_humans.get(code)
        if assignee is not None:
            return Route(
                RouteKind.HUMAN,
                agent_id=code,
                mention_text=human_match.group(0),
                agent_name=assignee.name,
            )

    return Route(RouteKind.IGNORE)


def strip_mentions(text: str) -> str:
    """حذف منشن‌ها و دستورها از متن برای ساخت «سؤال کاربر»."""
    cleaned = _MENTION_RE.sub(" ", text or "")
    cleaned = _HUMAN_MENTION_RE.sub(" ", cleaned)
    cleaned = cleaned.strip()
    return re.sub(r"\s{2,}", " ", cleaned).strip()


def extract_user_question(text: str, agent_mention: str | None = None, max_len: int = 220) -> str:
    """خلاصه سؤال کاربر برای ثبت در Notion (daily_log)."""
    cleaned = strip_mentions(text)
    if agent_mention:
        cleaned = cleaned.replace(agent_mention, "").strip()
    cleaned = re.sub(r"^/(all|daily)\b(@\w+)?", "", cleaned).strip()
    if not cleaned:
        return "(بدون متن / فقط منشن)"
    return cleaned[:max_len] + ("…" if len(cleaned) > max_len else "")
