"""Telegram Bot — send messages via Bot API."""
import httpx
from app.config import settings


def _base_url() -> str:
    return f"https://api.telegram.org/bot{settings.TELEGRAM_BOT_TOKEN}"


async def send_telegram(chat_id: str, message: str, message_thread_id: int | None = None) -> bool:
    """
    Send a plain-text message to a Telegram chat_id.
    Returns True on success, False on failure.
    Supports basic Markdown (bold, italic).
    Pass message_thread_id to target a specific topic in a forum/supergroup.
    """
    if not settings.TELEGRAM_BOT_TOKEN:
        print("[telegram] bot token not configured — skipping")
        return False
    if not chat_id:
        return False

    payload: dict = {
        "chat_id": chat_id,
        "text": message,
        "parse_mode": "Markdown",
        "disable_web_page_preview": True,
    }
    if message_thread_id:
        payload["message_thread_id"] = message_thread_id

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(
                f"{_base_url()}/sendMessage",
                json=payload,
            )
            if resp.status_code != 200:
                print(f"[telegram] API error {resp.status_code}: {resp.text[:200]}")
                return False
        return True
    except Exception as e:
        print(f"[telegram] send error: {e}")
        return False


async def send_document(chat_id: str, file_bytes: bytes, filename: str, caption: str = "", message_thread_id: int | None = None) -> bool:
    """Send a document (file) to a Telegram chat."""
    if not settings.TELEGRAM_BOT_TOKEN or not chat_id:
        return False
    data: dict = {"chat_id": chat_id, "caption": caption, "parse_mode": "Markdown"}
    if message_thread_id:
        data["message_thread_id"] = str(message_thread_id)
    try:
        async with httpx.AsyncClient(timeout=30) as client:
            resp = await client.post(
                f"{_base_url()}/sendDocument",
                data=data,
                files={"document": (filename, file_bytes, "application/pdf")},
            )
            if resp.status_code != 200:
                print(f"[telegram] sendDocument error {resp.status_code}: {resp.text[:200]}")
                return False
        return True
    except Exception as e:
        print(f"[telegram] send_document error: {e}")
        return False


async def send_photo(chat_id: str, file_bytes: bytes, filename: str, caption: str = "", message_thread_id: int | None = None) -> bool:
    """Send a photo to a Telegram chat."""
    if not settings.TELEGRAM_BOT_TOKEN or not chat_id:
        return False
    data: dict = {"chat_id": chat_id, "caption": caption, "parse_mode": "Markdown"}
    if message_thread_id:
        data["message_thread_id"] = str(message_thread_id)
    try:
        async with httpx.AsyncClient(timeout=30) as client:
            resp = await client.post(
                f"{_base_url()}/sendPhoto",
                data=data,
                files={"photo": (filename, file_bytes, "image/jpeg")},
            )
            if resp.status_code != 200:
                print(f"[telegram] sendPhoto error {resp.status_code}: {resp.text[:200]}")
                return False
        return True
    except Exception as e:
        print(f"[telegram] send_photo error: {e}")
        return False


async def set_webhook(webhook_url: str) -> bool:
    """Register a webhook URL with Telegram so the bot receives updates."""
    if not settings.TELEGRAM_BOT_TOKEN:
        return False
    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(
                f"{_base_url()}/setWebhook",
                json={"url": webhook_url},
            )
            ok = resp.json().get("ok", False)
            print(f"[telegram] setWebhook → {resp.json()}")
            return ok
    except Exception as e:
        print(f"[telegram] setWebhook error: {e}")
        return False
