"""Send an audio file via Telegram Bot API."""

import os
from pathlib import Path

import httpx

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


async def handler(params: dict) -> dict:
    """Send an audio file to a Telegram chat using sendAudio API."""
    chat_id = params["chat_id"]
    audio_file = params["audio_file"]
    caption = params.get("caption")
    title = params.get("title")
    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."
        )

    audio_path = Path(audio_file)
    if not audio_path.exists():
        raise ValueError(f"Audio file not found: {audio_file}")

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

    data = {"chat_id": chat_id}
    if message_thread_id:
        data["message_thread_id"] = int(message_thread_id)
    if caption:
        data["caption"] = caption
    if title:
        data["title"] = title

    async with httpx.AsyncClient(timeout=30) as client:
        with open(audio_path, "rb") as f:
            resp = await client.post(
                url,
                data=data,
                files={"audio": (audio_path.name, f, "audio/mpeg")},
            )

    # Clean up temp file after upload
    try:
        audio_path.unlink()
    except OSError:
        pass

    if resp.status_code == 200:
        result = resp.json().get("result", {})
        return {
            "status": f"Audio 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}")
