from typing import Any

from ..environment import CHIRPPY_TELEGRAM_CHAT_ID, CHIRPPY_TELEGRAM_TOKEN
from ..models import Message
from ..utils.config import resolve_from_env
from .factory import make_provider

PROVIDER_NAME = "telegram"


def _resolve_url(token: str | None = None) -> str:
    """Resolve Telegram API URL."""
    token = resolve_from_env(token, CHIRPPY_TELEGRAM_TOKEN)
    return f"https://api.telegram.org/bot{token}/sendMessage"


def _build_payload(
    message: Message,
    title: str | None = None,
    chat_id: str | None = None,
) -> dict[str, Any]:
    """Construct a message payload to send to Telegram.

    Args:
        message: Message object.
        chat_id: ID of the destination chat instance.
        title: Optional title to display with the message.

    Returns:
        Message payload as a dictionary.
    """
    chat_id = resolve_from_env(chat_id, CHIRPPY_TELEGRAM_CHAT_ID)

    text: str = message.text
    title = title or message.title
    if title:
        text = f"*{title}*\n{text}"

    return {
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "Markdown",
    }


send, async_send = make_provider(
    PROVIDER_NAME,
    resolve_url=_resolve_url,
    build_payload=_build_payload,
)
