"""Send a message via Telegram Bot API."""

import os

import httpx

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


async def handler(params: dict) -> dict:
    """Send a text message via Telegram Bot API."""
    chat_id = params["chat_id"]
    text = params["text"]
    message_thread_id = params.get("message_thread_id")

    bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")
    if not bot_token:
        raise ValueError(
            "TELEGRAM_BOT_TOKEN not set. Create a bot via @BotFather on Telegram "
            "and set the token in your .env file."
        )

    url = f"{TELEGRAM_API_BASE}/bot{bot_token}/sendMessage"

    async with httpx.AsyncClient(timeout=15) as client:
        resp = await client.post(
            url,
            json={
                "chat_id": chat_id,
                "text": text,
                "parse_mode": "Markdown",
                **({"message_thread_id": int(message_thread_id)} if message_thread_id else {}),
            },
        )

    if resp.status_code == 200:
        data = resp.json()
        result = data.get("result", {})
        return {
            "status": f"Message sent to chat {chat_id}",
            "message_id": result.get("message_id", 0),
        }

    try:
        error_data = resp.json()
        error_msg = error_data.get("description", resp.text)
    except Exception:
        error_msg = resp.text

    raise ValueError(f"Telegram API error ({resp.status_code}): {error_msg}")
