"""Прозрачный Bot API tee: парсинг getUpdates + персист обнаруженных групп профиля.

Read-only — поток не модифицируем. Группы оседают в profiles/<slug>/discovered_groups.json
(дефолтный профиль — в корне HERMES_HOME), переживают рестарт gateway. Файл читаем лениво
один раз на (home, slug) в in-memory кеш; на диск пишем ТОЛЬКО при изменении набора групп —
активная группа, уже известная, не порождает I/O. Расчёт на один uvicorn-воркер (так и есть).
"""
import json
import logging
import os
from pathlib import Path
from typing import Literal, NamedTuple

_GROUP_TYPES = ("group", "supergroup")
# Статусы бота в группе: присутствует vs выбыл.
_PRESENT = ("member", "administrator", "creator", "restricted")
_ABSENT = ("left", "kicked")


class TopicName(NamedTuple):
    chat_id: str
    thread_id: str
    name: str
    # service — служебка создания или переименования; reply — ссылка обычного сообщения на служебку создания.
    source: Literal["service", "reply"]


# Имена топиков форум-групп: {chatId: {threadId: name}}. Читает плагин agentek_runtime (telegram_topic).
TOPICS_FILE = "telegram_topics.json"

logger = logging.getLogger(__name__)

# Кеш групп по (str(home), slug). Home в ключе — чтобы тесты с разными tmp-каталогами не делили состояние.
_CACHE: dict[tuple[str, str], dict[str, dict]] = {}
_TOPICS_CACHE: dict[tuple[str, str], dict[str, dict[str, str]]] = {}


def _profile_home(home: Path, slug: str) -> Path:
    # default-профиль живёт в корне HERMES_HOME, именованный — в profiles/<slug>.
    return home if slug == "default" else home / "profiles" / slug


def groups_path(home: Path, slug: str) -> Path:
    return _profile_home(home, slug) / "discovered_groups.json"


def topics_path(home: Path, slug: str) -> Path:
    return _profile_home(home, slug) / TOPICS_FILE


def _load(home: Path, slug: str) -> dict[str, dict]:
    key = (str(home), slug)
    cached = _CACHE.get(key)
    if cached is None:
        try:
            rows = json.loads(groups_path(home, slug).read_text())
        except (FileNotFoundError, ValueError):
            rows = []
        cached = {g["chatId"]: g for g in rows if g.get("chatId")}
        _CACHE[key] = cached
    return cached


def read_groups(home: Path, slug: str) -> list[dict]:
    return list(_load(home, slug).values())


def reset_cache() -> None:
    # Для тестов: сбросить кеш, чтобы прочитать с диска заново.
    _CACHE.clear()
    _TOPICS_CACHE.clear()


def _write_groups(home: Path, slug: str, groups: list[dict]) -> None:
    path = groups_path(home, slug)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(".json.tmp")
    tmp.write_text(json.dumps(groups))
    os.replace(tmp, path)


def _chat_to_group(chat: dict) -> dict | None:
    if chat.get("type") not in _GROUP_TYPES:
        return None
    return {"chatId": str(chat.get("id")), "title": chat.get("title"), "type": chat.get("type")}


def extract_group_events(payload: dict) -> list[tuple[str, dict]]:
    """('add'|'remove', group) из ответа getUpdates. Read-only."""
    events: list[tuple[str, dict]] = []
    for upd in (payload or {}).get("result") or []:
        mcm = upd.get("my_chat_member")
        if isinstance(mcm, dict):
            group = _chat_to_group(mcm.get("chat") or {})
            if group:
                status = ((mcm.get("new_chat_member") or {}).get("status"))
                if status in _ABSENT:
                    events.append(("remove", group))
                elif status in _PRESENT:
                    events.append(("add", group))
            continue
        for key in ("message", "edited_message", "channel_post"):
            msg = upd.get(key)
            if isinstance(msg, dict):
                group = _chat_to_group(msg.get("chat") or {})
                if group:
                    events.append(("add", group))
                break
    return events


def apply_group_event(home: Path, slug: str, event: tuple[str, dict]) -> None:
    action, group = event
    cache = _load(home, slug)
    cid = group["chatId"]
    if action == "add":
        if cache.get(cid) == group:
            return  # уже знаем ровно эту группу — горячий путь активной группы без записи на диск
        cache[cid] = group
    else:
        if cid not in cache:
            return
        del cache[cid]
    _write_groups(home, slug, list(cache.values()))


def extract_topic_names(payload: dict) -> list[TopicName]:
    """Имена топиков форум-групп из ответа getUpdates. Read-only.

    Метода «имя топика по id» в Bot API нет: имя приходит служебкой о создании или переименовании,
    а обычное сообщение топика ссылается reply_to_message на служебку о его создании — с исходным именем.
    """
    names: list[TopicName] = []
    for update in (payload or {}).get("result") or []:
        for key in ("message", "edited_message"):
            message = update.get(key)
            if not isinstance(message, dict):
                continue
            chat = message.get("chat") or {}
            thread_id = message.get("message_thread_id")
            if chat.get("type") != "supergroup" or thread_id is None:
                continue
            topic = _topic_name(message)
            if topic:
                names.append(TopicName(str(chat.get("id")), str(thread_id), *topic))
    return names


def apply_topic_name(home: Path, slug: str, topic: TopicName) -> None:
    topics = _load_topics(home, slug)
    known = topics.get(topic.chat_id, {}).get(topic.thread_id)
    # Обычное сообщение несёт исходное имя: перезаписать им переименованный топик — откатить имя.
    if known == topic.name or (topic.source == "reply" and known):
        return
    topics.setdefault(topic.chat_id, {})[topic.thread_id] = topic.name
    path = topics_path(home, slug)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(".json.tmp")
    tmp.write_text(json.dumps(topics, ensure_ascii=False))
    os.replace(tmp, path)


def _topic_name(message: dict) -> tuple[str, Literal["service", "reply"]] | None:
    service = (message.get("forum_topic_edited") or {}).get("name") or (message.get("forum_topic_created") or {}).get("name")
    if service:
        return service, "service"
    reply = ((message.get("reply_to_message") or {}).get("forum_topic_created") or {}).get("name")
    return (reply, "reply") if reply else None


def _load_topics(home: Path, slug: str) -> dict[str, dict[str, str]]:
    key = (str(home), slug)
    cached = _TOPICS_CACHE.get(key)
    if cached is None:
        try:
            cached = json.loads(topics_path(home, slug).read_text())
        except FileNotFoundError:
            cached = {}
        except ValueError as exc:
            logger.warning("%s of %r is not valid JSON, topic names start over: %s", TOPICS_FILE, slug, exc)
            cached = {}
        _TOPICS_CACHE[key] = cached
    return cached


TELEGRAM_API = "https://api.telegram.org"


def upstream_url(rest: str) -> str:
    return f"{TELEGRAM_API}/{rest.lstrip('/')}"


def proxy_for_telegram() -> str | None:
    # Имя своё, не TELEGRAM_PROXY: её читает адаптер движка в этом же контейнере и погнал бы
    # через прокси свои localhost-запросы к бриджу.
    proxy = os.environ.get("HERMES_BRIDGE_TELEGRAM_PROXY", "").strip()
    return proxy or None


def is_get_updates(rest: str) -> bool:
    return rest.rstrip("/").endswith("/getUpdates")
