"""
app.py
======

PURPOSE
-------
The Flask web application. Telegram delivers every message to your bot by
sending an HTTP POST ("webhook") to a URL you register. This file defines the
URL routes that receive those POSTs and hands them to the bot's brain
(bot_logic.handle_update).

WHY FLASK + WEBHOOKS (NOT POLLING)?
-----------------------------------
Long-polling bots run a forever-loop that constantly asks Telegram "any new
messages?". cPanel kills long-running background loops, so polling is unreliable
there. Webhooks flip it around: Telegram calls US only when there's a message,
which fits perfectly into a normal web request/response — exactly what cPanel's
Passenger is built to serve.

THE OBJECT PASSENGER NEEDS
--------------------------
cPanel's Passenger looks for a WSGI "application" object. Flask's `app` IS a
WSGI application. passenger_wsgi.py simply imports the `app` defined here.
"""

import logging

# Flask is the web framework. `request` gives us the incoming HTTP request;
# `jsonify`/`Response` let us send replies; `abort` lets us reject bad requests.
from flask import Flask, request, abort, Response

import bot_logic
import state
from config import WEBHOOK_SECRET


# --- Logging setup ----------------------------------------------------------
# Configure logging so our log.info/log.error calls show up in cPanel's
# stderr.log. INFO level is a good default; switch to DEBUG while debugging.
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger(__name__)


# --- Create the Flask application ------------------------------------------
# This single `app` object is what Passenger (and `flask run`) will serve.
app = Flask(__name__)

# Make sure the SQLite state table exists before we handle any request.
# Calling it at import time means it runs once when the app process starts.
state.init_db()


@app.route("/", methods=["GET"])
def health_check():
    """
    A simple health-check page.

    Visiting your bot's domain in a browser hits this. If you see the message,
    your Python app is running on cPanel. Telegram never uses this route.
    """
    return "Cloudflare Redirect Bot is running. ✅"


@app.route("/webhook", methods=["POST"])
def webhook():
    """
    THE important route. Telegram POSTs every update here as JSON.

    SECURITY:
        When we registered the webhook we gave Telegram a secret token.
        Telegram sends it back in the header
            X-Telegram-Bot-Api-Secret-Token
        on every call. We compare it to our WEBHOOK_SECRET and reject anything
        that doesn't match — this stops strangers from POSTing fake updates to
        your public URL.

    FAST RESPONSE:
        Telegram expects a quick HTTP 200. We process the update and then
        return "OK". (Our Cloudflare work usually finishes in a few seconds,
        which is fine. If you later have very slow operations, you'd offload
        them to a background task — see the README's "Going further" note.)
    """
    # 1) Verify the secret header (only if a secret is configured).
    if WEBHOOK_SECRET:
        sent_secret = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
        if sent_secret != WEBHOOK_SECRET:
            log.warning("Rejected webhook call with bad/missing secret token.")
            # 403 Forbidden — do not process this request.
            abort(403)

    # 2) Parse the JSON body into a Python dict.
    #    silent=True -> return None instead of raising if the body isn't JSON.
    update = request.get_json(silent=True)
    if update is None:
        log.warning("Webhook received a request with no JSON body.")
        abort(400)  # Bad Request

    # 3) Hand the update to the bot's brain. handle_update never raises
    #    (it catches its own errors), so we can safely return 200 afterwards.
    bot_logic.handle_update(update)

    # 4) Tell Telegram we received it. A plain 200 with any body is fine.
    return Response("OK", status=200)


# --- Local development convenience -----------------------------------------
# This block ONLY runs if you execute `python app.py` directly on your own
# computer. On cPanel, Passenger imports `app` and this block is skipped.
if __name__ == "__main__":
    # debug=True gives helpful error pages and auto-reloads on code changes.
    # NEVER use debug=True in production.
    app.run(host="127.0.0.1", port=5000, debug=True)
