"""threads.py — مدیریت تاپیک‌های گروه تلگرام (Forum Topics).

در گروه‌های دارای تاپیک، هر تاپیک یک `message_thread_id` دارد و یک
`is_topic_message` روی پیام. این ماژول:

    ۱) از پیام، تاپیک و نامش را استخراج می‌کند
    ۲) نام تاپیک‌ها را کش می‌کند (برای متن Notion)
    ۳) شناسهٔ تاپیک را برای پاسخ در همان تاپیک نگه می‌دارد

چرا مهم است: پیمایش پاسخ‌ها/وظایف بر اساس تاپیک، همان ساختار کاری
گروه شماست («تولید محتوا»، «طراحی»، «فروش» …). در Notion هم همین
تاپیک به‌عنوان ستون «تاپیک» ثبت می‌شود تا معلوم باشد کار از کجا آمده.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass
from typing import Any, Optional

logger = logging.getLogger(__name__)


@dataclass
class ThreadInfo:
    """اطلاعات تاپیک یک پیام."""

    thread_id: Optional[int] = None
    name: str = ""
    is_topic: bool = False

    @property
    def label(self) -> str:
        """نمایش خوانا برای Notion."""
        if not self.is_topic:
            return ""
        if self.name:
            return self.name
        return f"تاپیک {self.thread_id}" if self.thread_id else ""

    def as_dict(self) -> dict[str, Any]:
        return {
            "thread_id": self.thread_id,
            "thread_name": self.name,
            "is_topic": self.is_topic,
        }


class ThreadCache:
    """کش نام تاپیک‌ها: (chat_id, thread_id) → نام."""

    def __init__(self, max_items: int = 500) -> None:
        self._max = max_items
        self._names: dict[tuple[int, int], str] = {}

    def set_name(self, chat_id: int, thread_id: int, name: str) -> None:
        if not thread_id or not name:
            return
        if len(self._names) >= self._max:
            # ساده: قدیمی‌ترین را حذف کن
            self._names.pop(next(iter(self._names)), None)
        self._names[(chat_id, thread_id)] = name.strip()

    def get_name(self, chat_id: int, thread_id: int) -> str:
        return self._names.get((chat_id, thread_id), "")

    def learn_from_update(self, update: Any) -> None:
        """یادگیری نام تاپیک از سرویس‌پیام‌های تلگرام."""
        if update is None:
            return
        # forum_topic_created / edited / closed / reopened
        for attr in ("forum_topic_created", "forum_topic_edited"):
            obj = getattr(update, attr, None)
            if obj is not None:
                chat = getattr(update, "chat", None)
                tid = getattr(update, "message_thread_id", None)
                name = getattr(obj, "name", "") or ""
                if chat is not None and tid:
                    self.set_name(chat.id, int(tid), name)
                return


#: کش سراسری (یک نمونه برای کل پروسه)
thread_cache = ThreadCache()


def extract_thread(message: Any) -> ThreadInfo:
    """اطلاعات تاپیک را از یک پیام تلگرام بیرون می‌کشد.

    تلگرام این فیلدها را می‌دهد:
        message.is_topic_message: bool
        message.message_thread_id: int | None
        message.forum_topic_created: ForumTopicCreated | None
    """
    if message is None:
        return ThreadInfo()

    is_topic = bool(getattr(message, "is_topic_message", False))
    raw_tid = getattr(message, "message_thread_id", None)
    thread_id: Optional[int] = None
    if raw_tid is not None:
        try:
            thread_id = int(raw_tid)
        except (TypeError, ValueError):
            thread_id = None

    if thread_id is None and not is_topic:
        return ThreadInfo()

    # نام تاپیک: اگر همین پیام «ساخت تاپیک» است، از خودش بگیر
    name = ""
    created = getattr(message, "forum_topic_created", None)
    if created is not None:
        name = getattr(created, "name", "") or ""
    elif getattr(message, "forum_topic_edited", None) is not None:
        name = getattr(getattr(message, "forum_topic_edited"), "name", "") or ""

    chat = getattr(message, "chat", None)
    if chat is not None and thread_id:
        if name:
            thread_cache.set_name(chat.id, thread_id, name)
        else:
            name = thread_cache.get_name(chat.id, thread_id)

    # تاپیک «General» شناسه ۱ دارد و معمولاً نام ندارد
    if thread_id == 1 and not name:
        name = "عمومی"

    return ThreadInfo(thread_id=thread_id, name=name, is_topic=is_topic or thread_id is not None)


def reply_kwargs(message: Any) -> dict[str, Any]:
    """آرگومان‌های لازم برای پاسخ در همان تاپیک."""
    info = extract_thread(message)
    if info.thread_id:
        return {"message_thread_id": info.thread_id}
    return {}


def thread_link(chat_id: Optional[int], thread_id: Optional[int], message_id: Optional[int] = None) -> str:
    """لینک باز کردن تاپیک/پیام در تلگرام.

    فرمت: https://t.me/c/<internal_id>/<thread_id>/<message_id>
    internal_id = حذف -100 از ابتدای chat_id
    """
    if not chat_id or not thread_id:
        return ""
    raw = str(chat_id)
    internal = raw[4:] if raw.startswith("-100") else raw.lstrip("-")
    base = f"https://t.me/c/{internal}/{thread_id}"
    if message_id:
        return f"{base}/{message_id}"
    return base


def format_source_block(
    *,
    chat_title: str = "",
    topic: str = "",
    author: str = "",
    permalink: str = "",
    thread_id: Optional[int] = None,
) -> str:
    """بلوک «منبع» برای انتهای توضیحات وظیفه در Notion."""
    lines = ["─── منبع ───"]
    if chat_title:
        lines.append(f"گروه: {chat_title}")
    if topic:
        lines.append(f"تاپیک: {topic}")
    if thread_id:
        lines.append(f"شناسهٔ تاپیک: {thread_id}")
    if author:
        lines.append(f"فرستنده: {author}")
    if permalink:
        lines.append(f"لینک: {permalink}")
    return "\n".join(lines)
