#!/usr/bin/env python3
"""Bounded Telegram getMe readiness gate; never calls getUpdates or writes state."""

from __future__ import annotations

import argparse
import asyncio
import importlib
import json
import os
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any, Final

EXPECTED_BOT: Final = "dual_coach_pilot_test_bot"
SUCCESSOR: Final = "e788f5d56aef04da3097007e2ab79614f2060607d4331162169733b1208d9377"


class ProbeFailure(RuntimeError):
    """Fail-closed transport readiness result."""


async def getme_gate(
    token: str,
    bot_factory: Callable[[str], Any],
    *,
    expected_username: str = EXPECTED_BOT,
    timeout: float = 10.0,
) -> dict[str, object]:
    """Call only Bot API getMe and require the bound bot identity."""
    if not token.strip():
        raise ProbeFailure("telegram token unavailable")
    bot = bot_factory(token)
    try:
        async with bot:
            identity = await asyncio.wait_for(bot.get_me(), timeout=timeout)
    except TimeoutError as exc:
        raise ProbeFailure("telegram getMe timeout") from exc
    except Exception as exc:
        raise ProbeFailure("telegram getMe transport failure") from exc
    username = getattr(identity, "username", None)
    if username != expected_username:
        raise ProbeFailure("telegram getMe bot identity mismatch")
    return {
        "schema": "task26-telegram-transport-readiness-v1",
        "status": "READY_TELEGRAM_TRANSPORT",
        "successor": SUCCESSOR,
        "method": "Bot.get_me",
        "consumes_updates": False,
        "mutates_cursor": False,
        "writes_state": False,
    }


def load_token(profile: Path) -> str:
    """Load the existing profile configuration without exposing its token."""
    os.environ["HERMES_HOME"] = str(profile.resolve())
    os.chdir(profile)
    gateway_config = importlib.import_module("gateway.config")
    config = gateway_config.load_gateway_config()
    platform = config.platforms.get(gateway_config.Platform.TELEGRAM)
    if platform is None or not platform.enabled or not platform.token:
        raise ProbeFailure("enabled Telegram configuration unavailable")
    return platform.token


def production_bot_factory(token: str) -> Any:
    telegram = importlib.import_module("telegram")
    telegram_request = importlib.import_module("telegram.request")
    request = telegram_request.HTTPXRequest(
        connect_timeout=5.0,
        read_timeout=5.0,
        write_timeout=5.0,
        pool_timeout=5.0,
    )
    return telegram.Bot(token=token, request=request)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--profile", required=True, type=Path)
    parser.add_argument("--timeout", default=10.0, type=float)
    args = parser.parse_args()
    if not 0 < args.timeout <= 10:
        print("FAIL_TELEGRAM_TRANSPORT: invalid timeout", file=sys.stderr)
        return 2
    try:
        result = asyncio.run(
            getme_gate(
                load_token(args.profile),
                production_bot_factory,
                timeout=args.timeout,
            )
        )
    except (ProbeFailure, OSError, ValueError) as exc:
        print(f"FAIL_TELEGRAM_TRANSPORT: {exc}", file=sys.stderr)
        return 3
    print(json.dumps(result, sort_keys=True, separators=(",", ":")))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
