"""notion_mention.py — نوشتن منشن واقعی ایجنت در Notion.

چرا لازم است: اگر فقط متن «@AG03» را در یک ستون rich_text بنویسیم، Notion آن را
**متن ساده** می‌بیند، نه منشن. منشن واقعی Notion ساختار متفاوتی دارد:

    {"type": "mention", "mention": {"type": "user", "user": {"id": "<uuid>"}}}

برای اینکه ایجنت در Notion واقعاً «منشن‌شده» باشد، سه راه داریم:

    راه ۱ — منشن کاربر Notion (رایج‌ترین):
        هر ایجنت یک حساب کاربری Notion (یا یک کاربر مهمان) دارد.
        UUID او را در NOTION_AGENT_USERS می‌گذارید: AG03=uuid
        → ستون به‌صورت mention واقعی نوشته می‌شود و آبی می‌شود.

    راه ۲ — صفحهٔ ایجنت:
        برای هر ایجنت یک صفحه بسازید و به‌صورت mention type=page منشن کنید.

    راه ۳ — متن ساده (همیشه کار می‌کند):
        اگر UUID ندارید، متن «@AG03» نوشته می‌شود. اتوماسیون خودمان
        با regex تشخیص می‌دهد — برای کارکرد ما کافی است، فقط در Notion
        آبی/کلیک‌شدنی نیست.

این ماژول هر سه را پشتیبانی می‌کند و به‌طور خودکار بهترین را انتخاب می‌کند.
"""

from __future__ import annotations

import logging
import re
from typing import Any, Optional

from config.settings import settings

logger = logging.getLogger(__name__)

UUID_RE = re.compile(
    r"^[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}$"
)


# --------------------------------------------------------------------------- #
#  نگاشت ایجنت → کاربر/صفحهٔ Notion
# --------------------------------------------------------------------------- #
def parse_agent_users(raw: str = "") -> dict[str, dict[str, str]]:
    """«AG03=uuid-user, AG04=page:uuid-page» → {AG03: {type, id}}"""
    raw = raw or settings.notion_agent_users or ""
    out: dict[str, dict[str, str]] = {}
    for piece in raw.replace(";", ",").split(","):
        piece = piece.strip()
        if not piece or "=" not in piece:
            continue
        agent, _, target = piece.partition("=")
        agent = agent.strip().upper()
        target = target.strip()
        if not target:
            continue
        if target.lower().startswith("page:"):
            out[agent] = {"type": "page", "id": target[5:].strip()}
        elif target.lower().startswith("user:"):
            out[agent] = {"type": "user", "id": target[5:].strip()}
        elif UUID_RE.match(target):
            out[agent] = {"type": "user", "id": target}
        else:
            logger.warning("نگاشت نامعتبر برای %s: %r", agent, target)
    return out


def normalize_uuid(value: str) -> str:
    """UUID بدون خط تیره را به شکل استاندارد برگرداند."""
    v = (value or "").strip()
    if len(v) == 32 and all(c in "0123456789abcdefABCDEF" for c in v):
        return f"{v[:8]}-{v[8:12]}-{v[12:16]}-{v[16:20]}-{v[20:]}"
    return v


# --------------------------------------------------------------------------- #
#  ساخت rich_text
# --------------------------------------------------------------------------- #
def agent_mention_rich(agent_id: str, users: Optional[dict[str, dict[str, str]]] = None) -> dict[str, Any]:
    """یک آیتم rich_text برای منشن ایجنت.

    اگر UUID داشته باشیم → mention واقعی؛ وگرنه متن ساده «@AG03».
    """
    users = users if users is not None else parse_agent_users()
    target = users.get(agent_id.upper())

    if target:
        uid = normalize_uuid(target["id"])
        mtype = target["type"]
        if mtype == "page":
            return {
                "type": "mention",
                "mention": {"type": "page", "page": {"id": uid}},
            }
        return {
            "type": "mention",
            "mention": {"type": "user", "user": {"id": uid}},
        }

    # fallback: متن ساده
    return {"type": "text", "text": {"content": f"@{agent_id.upper()}"}}


def text_rich(content: str) -> dict[str, Any]:
    return {"type": "text", "text": {"content": content}}


def build_rich_text(
    *,
    agent_id: str,
    parts: list[tuple[str, str]],
    users: Optional[dict[str, dict[str, str]]] = None,
) -> list[dict[str, Any]]:
    """ساخت آرایهٔ rich_text با منشن ایجنت در ابتدا.

    parts: [(متن, «متن») | (agent, «ایجنت»)] — هر «ایجنت» به منشن تبدیل می‌شود.
    """
    out: list[dict[str, Any]] = []
    for value, kind in parts:
        if kind == "agent":
            out.append(agent_mention_rich(value, users))
        else:
            if value:
                out.append(text_rich(value))
    return out


# --------------------------------------------------------------------------- #
#  ساخت متن منشن برای یک وظیفه
# --------------------------------------------------------------------------- #
def mention_line(agent_id: str, task_title: str) -> str:
    """متن سادهٔ منشن (برای جایی که rich_text ممکن نیست)."""
    return f"@{agent_id.upper()} {task_title}".strip()


def build_assignee_rich(
    agent_id: str, users: Optional[dict[str, dict[str, str]]] = None
) -> list[dict[str, Any]]:
    """آرایهٔ rich_text فقط شامل منشن ایجنت."""
    return [agent_mention_rich(agent_id, users)]


def has_real_mention(rich: list[dict[str, Any]]) -> bool:
    """آیا این rich_text شامل منشن واقعی است؟"""
    return any(rt.get("type") == "mention" for rt in (rich or []))


def describe_mapping(raw: str = "") -> str:
    """گزارش خوانا از نگاشت، برای عیب‌یابی."""
    users = parse_agent_users(raw)
    if not users:
        return (
            "نگاشت ایجنت→کاربر Notion خالی است.\n"
            "منشن‌ها به‌صورت متن «@AG03» نوشته می‌شوند (کار می‌کند، ولی در Notion آبی نیست).\n"
            "برای منشن واقعی: NOTION_AGENT_USERS=AG03=<uuid>,AG04=page:<uuid>"
        )
    lines = ["نگاشت ایجنت → Notion:"]
    for agent, target in sorted(users.items()):
        lines.append(f"  {agent} → {target['type']}:{target['id'][:8]}…")
    return "\n".join(lines)
