"""Webhook for the Telegram Bot API. Registered only when TELEGRAM_ENABLED=true.

The URL includes a secret path segment (TELEGRAM_WEBHOOK_SECRET) instead of
relying on a header, since Telegram's own webhook setup only lets you set the
URL itself — this keeps randos from POSTing fake updates to a guessable path.
"""
from flask import Blueprint, request, current_app, abort

from app.processing.telegram_intake import process_telegram_update
from app.telegram.telegram_client import send_message

telegram_bp = Blueprint("telegram", __name__, url_prefix="/telegram")


@telegram_bp.route("/webhook/<secret>", methods=["POST"])
def webhook(secret):
    if secret != current_app.config.get("TELEGRAM_WEBHOOK_SECRET"):
        abort(404)

    update = request.get_json(silent=True) or {}
    reply_text = process_telegram_update(update)

    chat_id = (update.get("message") or {}).get("chat", {}).get("id")
    if reply_text and chat_id:
        try:
            send_message(str(chat_id), reply_text)
        except Exception:  # noqa: BLE001 - a failed reply shouldn't break the webhook ack
            current_app.logger.exception("No se pudo responder en Telegram")

    return "OK", 200
