"""
telegram_api.py
===============

PURPOSE
-------
Thin wrapper functions around the Telegram Bot API. The rest of our code never
talks to Telegram directly — it calls friendly functions like
`send_message(chat_id, "hello")`. This keeps the messy HTTP details in one
place and makes the workflow code easy to read.

WHAT IS THE TELEGRAM BOT API?
-----------------------------
It is a normal HTTPS REST API. You make a request to a URL shaped like:

    https://api.telegram.org/bot<YOUR_TOKEN>/<methodName>

...passing parameters as JSON. For example, the method `sendMessage` sends a
text message to a chat. We build that base URL in config.py as
`TELEGRAM_API_BASE`.

INLINE KEYBOARDS
----------------
Telegram lets you attach buttons under a message ("inline keyboard"). When a
user taps a button, Telegram sends your webhook a special update called a
`callback_query` containing the button's `callback_data`. We use this for the
Confirm / Cancel buttons before applying a redirect change.
"""

import json       # Used only for pretty error logging.
import logging     # Standard Python logging so messages show up in cPanel logs.

import requests    # The HTTP client library.

# Pull the prebuilt base URL and timeout from our central config.
from config import TELEGRAM_API_BASE, HTTP_TIMEOUT

# A module-level logger. Anything we log appears in your application's log file
# (cPanel shows this under the Python App's "stderr.log").
log = logging.getLogger(__name__)


def _call(method: str, payload: dict) -> dict:
    """
    Low-level helper: POST a payload to one Telegram Bot API method.

    Every public function below ultimately funnels through this one helper,
    so all our error handling and logging lives in a single spot.

    Parameters
    ----------
    method : str
        The Telegram method name, e.g. "sendMessage" or "answerCallbackQuery".
    payload : dict
        The JSON body to send (parameters for that method).

    Returns
    -------
    dict
        The parsed JSON response from Telegram. On failure we return a dict
        with "ok": False so callers can keep running instead of crashing the
        whole webhook.
    """
    # Assemble the full URL: base + "/" + method name.
    url = f"{TELEGRAM_API_BASE}/{method}"

    try:
        # `json=payload` tells requests to JSON-encode the body and set the
        # Content-Type header to application/json automatically.
        response = requests.post(url, json=payload, timeout=HTTP_TIMEOUT)

        # Parse Telegram's JSON reply into a Python dict.
        data = response.json()

        # Telegram always includes an "ok" boolean. If it is False, log why.
        if not data.get("ok"):
            log.error("Telegram %s failed: %s", method, json.dumps(data))

        return data

    except requests.RequestException as exc:
        # Network problem (timeout, DNS, connection refused, ...).
        # We log it and return a safe fake response so the caller survives.
        log.exception("Network error calling Telegram %s: %s", method, exc)
        return {"ok": False, "error": str(exc)}


def send_message(chat_id: int, text: str, reply_markup: dict | None = None) -> dict:
    """
    Send a text message to a chat.

    Parameters
    ----------
    chat_id : int
        Who to send to. We get this from the incoming update.
    text : str
        The message body. We use "HTML" parse mode so you can use <b>bold</b>,
        <code>monospace</code>, etc.
    reply_markup : dict, optional
        An inline keyboard definition (see `inline_keyboard` below). If None,
        the message has no buttons.

    Returns
    -------
    dict
        Telegram's response.
    """
    payload = {
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "HTML",
        # Telegram tries to fetch link previews by default; turn that off so
        # URLs in our messages stay tidy.
        "disable_web_page_preview": True,
    }

    # Only attach the keyboard if one was provided.
    if reply_markup is not None:
        payload["reply_markup"] = reply_markup

    return _call("sendMessage", payload)


def edit_message_text(chat_id: int, message_id: int, text: str,
                      reply_markup: dict | None = None) -> dict:
    """
    Edit the text of a message we already sent.

    We use this after the user taps Confirm/Cancel so the old buttons get
    replaced by a result message (instead of leaving stale buttons around).

    Parameters
    ----------
    chat_id : int
        The chat containing the message.
    message_id : int
        Which message to edit (Telegram gives us this on the callback).
    text : str
        The new text.
    reply_markup : dict, optional
        New inline keyboard, or None to remove the buttons.
    """
    payload = {
        "chat_id": chat_id,
        "message_id": message_id,
        "text": text,
        "parse_mode": "HTML",
        "disable_web_page_preview": True,
    }
    if reply_markup is not None:
        payload["reply_markup"] = reply_markup

    return _call("editMessageText", payload)


def answer_callback_query(callback_query_id: str, text: str = "") -> dict:
    """
    Acknowledge a button tap.

    Telegram REQUIRES you to "answer" every callback_query, otherwise the
    user sees a little loading spinner on the button forever. Calling this
    stops the spinner and (optionally) shows a tiny toast/popup.

    Parameters
    ----------
    callback_query_id : str
        The id Telegram sent with the callback_query.
    text : str, optional
        A short message to flash to the user. Empty string = just stop the
        spinner silently.
    """
    payload = {"callback_query_id": callback_query_id}
    if text:
        payload["text"] = text
    return _call("answerCallbackQuery", payload)


def inline_keyboard(buttons: list[list[tuple[str, str]]]) -> dict:
    """
    Build an inline keyboard structure from a simple list of buttons.

    Telegram expects a specific nested JSON shape. This helper lets the rest
    of our code describe buttons simply and we convert to the required shape.

    Parameters
    ----------
    buttons : list of rows, where each row is a list of (label, data) tuples.
        Example:
            inline_keyboard([
                [("✅ Confirm", "confirm"), ("❌ Cancel", "cancel")],
            ])
        produces one row with two buttons.

    Returns
    -------
    dict
        A reply_markup dict ready to pass to send_message / edit_message_text.
    """
    return {
        "inline_keyboard": [
            # For each row, turn each (label, data) tuple into the dict
            # Telegram wants: text is the visible label, callback_data is the
            # hidden string sent back to us when tapped.
            [{"text": label, "callback_data": data} for (label, data) in row]
            for row in buttons
        ]
    }
