"""Telegram Forum Topic management — create topics + persist mapping."""

import json
import os
from pathlib import Path

import httpx
import structlog

log = structlog.get_logger()

TELEGRAM_API_BASE = "https://api.telegram.org"
TOPICS_FILE = Path.home() / ".fliiq" / "telegram_topics.json"


def _load_topic_map() -> dict[str, int]:
    """Load {chat_id}:{topic_name} -> message_thread_id mapping."""
    if TOPICS_FILE.is_file():
        return json.loads(TOPICS_FILE.read_text())
    return {}


def _save_topic_map(mapping: dict[str, int]) -> None:
    TOPICS_FILE.parent.mkdir(parents=True, exist_ok=True)
    TOPICS_FILE.write_text(json.dumps(mapping, indent=2))


def get_topic_thread_id(chat_id: str, topic_name: str) -> int | None:
    """Look up a cached message_thread_id for a chat+topic pair."""
    mapping = _load_topic_map()
    return mapping.get(f"{chat_id}:{topic_name}")


async def resolve_or_create_topic(
    chat_id: str,
    topic_name: str,
    bot_token: str | None = None,
) -> int | None:
    """Resolve existing topic thread_id or create a new Forum Topic.

    Returns message_thread_id on success, None if the group doesn't
    support topics or creation fails.
    """
    cached = get_topic_thread_id(chat_id, topic_name)
    if cached is not None:
        return cached

    token = bot_token or os.environ.get("TELEGRAM_BOT_TOKEN")
    if not token:
        log.warning("telegram_topics.no_token")
        return None

    url = f"{TELEGRAM_API_BASE}/bot{token}/createForumTopic"
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.post(
                url,
                json={"chat_id": chat_id, "name": topic_name},
            )
        if resp.status_code == 200:
            thread_id = resp.json()["result"]["message_thread_id"]
            mapping = _load_topic_map()
            mapping[f"{chat_id}:{topic_name}"] = thread_id
            _save_topic_map(mapping)
            log.info(
                "telegram_topic_created",
                chat_id=chat_id,
                topic=topic_name,
                thread_id=thread_id,
            )
            return thread_id

        error_desc = resp.json().get("description", resp.text[:200])
        log.warning(
            "telegram_topic_create_failed",
            chat_id=chat_id,
            topic=topic_name,
            status=resp.status_code,
            error=error_desc,
        )
        return None
    except Exception as e:
        log.warning("telegram_topic_create_error", chat_id=chat_id, error=str(e))
        return None
