"""Thin wrapper around the Telegram Bot API. No SDK needed — it's plain HTTPS,
and a bot token from @BotFather is free and doesn't need Meta-style business
verification, unlike WhatsApp Cloud API.
"""
import requests
from flask import current_app

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


def _api_url(method: str) -> str:
    token = current_app.config["TELEGRAM_BOT_TOKEN"]
    return f"{API_BASE}/bot{token}/{method}"


def send_message(chat_id: str, text: str) -> None:
    response = requests.post(
        _api_url("sendMessage"),
        json={"chat_id": chat_id, "text": text[:4096]},
        timeout=10,
    )
    response.raise_for_status()


def download_file(file_id: str) -> bytes:
    """Two-step per the Bot API: resolve file_id -> file_path, then download it."""
    token = current_app.config["TELEGRAM_BOT_TOKEN"]

    get_file_resp = requests.get(_api_url("getFile"), params={"file_id": file_id}, timeout=10)
    get_file_resp.raise_for_status()
    file_path = get_file_resp.json()["result"]["file_path"]

    file_resp = requests.get(f"{API_BASE}/file/bot{token}/{file_path}", timeout=30)
    file_resp.raise_for_status()
    return file_resp.content
