# Copyright (c) 2026 Nous Research
"""Real Telegram fixtures for channel-inbox tests."""

from __future__ import annotations

import sys
from dataclasses import dataclass

from pydantic import JsonValue

for module_name in tuple(sys.modules):
    if module_name == "telegram" or module_name.startswith("telegram."):
        del sys.modules[module_name]

from telegram import Message, Update, User
from telegram.ext import Application, CallbackContext, ContextTypes

from gateway.config import PlatformConfig
from gateway.platforms.telegram import TelegramAdapter
from gateway.platforms.telegram_channel_inbox_config import (
    ChannelInboxAuthority,
    channel_inbox_capability_digest,
)

CHAT_ID = "-1009000000001"
PARENT_CHANNEL_ID = "-1008000000001"
BOT_ID = "8599834213"
TOPIC_ID = 9_007_199_254_740
CANDIDATE_DIGEST = "b" * 64
AUTHORITY = ChannelInboxAuthority(
    direct_messages_chat_id=CHAT_ID,
    parent_channel_id=PARENT_CHANNEL_ID,
    bot_id=BOT_ID,
    candidate_digest=CANDIDATE_DIGEST,
)
CAPABILITY_DIGEST = channel_inbox_capability_digest(AUTHORITY)


@dataclass(frozen=True, slots=True)
class ChannelMessageSpec:
    """Bot API fields varied by channel-inbox tests."""

    chat_id: str = CHAT_ID
    sender_id: int = 42
    topic_user_id: int = 42
    topic_id: int = TOPIC_ID
    is_direct_messages: bool = True
    chat_type: str = "channel"
    include_topic: bool = True
    text: str = "오늘 체크인"


def config_payload(*, enabled: bool = True) -> dict[str, JsonValue]:
    """Return a canonical channel-inbox config payload."""
    return {
        "schema": "nutricoach-channel-inbox-v1",
        "enabled": enabled,
        "direct_messages_chat_id": CHAT_ID,
        "parent_channel_id": PARENT_CHANNEL_ID,
        "bot_id": BOT_ID,
        "candidate_digest": CANDIDATE_DIGEST,
        "capability_digest": CAPABILITY_DIGEST,
    }


def config_extra(*, enabled: bool = True) -> dict[str, JsonValue]:
    """Return the platform extra mapping."""
    return {"nutricoach_channel_inbox": config_payload(enabled=enabled)}


def channel_message(spec: ChannelMessageSpec = ChannelMessageSpec()) -> Message:
    """Build a real python-telegram-bot message."""
    payload: dict[str, JsonValue] = {
        "message_id": 101,
        "date": 1_787_702_400,
        "chat": {
            "id": int(spec.chat_id),
            "type": spec.chat_type,
            "title": "뉴트리코치" if spec.chat_type == "channel" else None,
            "first_name": "고객" if spec.chat_type == "private" else None,
            "is_direct_messages": spec.is_direct_messages,
        },
        "from": {
            "id": spec.sender_id,
            "is_bot": spec.sender_id == 999,
            "first_name": "고객",
        },
        "text": spec.text,
    }
    if spec.include_topic:
        payload["direct_messages_topic"] = {
            "topic_id": spec.topic_id,
            "user": {
                "id": spec.topic_user_id,
                "is_bot": False,
                "first_name": "고객",
            },
        }
    return Message.de_json(payload)


def channel_adapter(*, enabled: bool = True) -> TelegramAdapter:
    """Build an isolated adapter with simulated verified authority."""
    adapter = TelegramAdapter(
        PlatformConfig(
            enabled=True,
            token="test-token",
            extra=config_extra(enabled=enabled),
        )
    )
    adapter._channel_inbox_authority_verified = enabled
    return adapter


def channel_update(message: Message) -> Update:
    """Wrap a real message in a real Telegram update."""
    return Update(update_id=1, message=message)


def channel_user(user_id: int) -> User:
    """Build a real Telegram user."""
    return User.de_json(
        {
            "id": user_id,
            "is_bot": False,
            "first_name": "고객",
        },
    )


def channel_context() -> ContextTypes.DEFAULT_TYPE:
    """Build a real callback context without network startup."""
    application = Application.builder().token("123:test").build()
    return CallbackContext(application)
