"""
Flask WSGI application — webhook endpoint for the Telegram bot.

Passenger (cPanel) imports this module and calls `app` as the WSGI callable.
`app.run()` is intentionally absent from the production path; it is only
invoked when the file is executed directly for local testing.
"""

import logging

from flask import Flask, jsonify, request

from . import config
from .core.router import dispatch
from .setup_webhook import register_route

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger("financegpt_bot")

app = Flask(__name__)
register_route(app)   # /setup-webhook (only active when REGISTER_WEBHOOK=true)


def _process(update: dict) -> None:
    try:
        dispatch(update)
    except Exception:
        log.exception("error while processing update %s", update.get("update_id"))


# --- Routes --------------------------------------------------------------------

@app.route("/", methods=["GET"])
@app.route("/health", methods=["GET"])
@app.route("/healthz", methods=["GET"])
def health():
    """Simple liveness probe — open this in a browser to confirm the app is up."""
    return jsonify({"status": "ok", "bot": "FinanceGPT"}), 200


@app.route(config.WEBHOOK_PATH, methods=["POST"])
def webhook():
    """
    Telegram calls this endpoint for every update.
    We process the update synchronously and return 200 immediately.
    Synchronous processing is safer under Passenger (no daemon-thread risk).
    Telegram's webhook timeout is 60 s, which is far more than needed here.
    """
    update = request.get_json(force=True, silent=True) or {}
    _process(update)
    return ("", 200)


# --- Local-only entry point ----------------------------------------------------

if __name__ == "__main__":
    # Only used when running locally: python -m financegpt_bot.app
    # Passenger never reaches this block.
    app.run(host=config.HOST, port=config.PORT, debug=False)
