from __future__ import annotations
import sys; sys.path.append("..")
from flask import Flask, request, jsonify
from manager.MysqlManager import MysqlManager
from models.token_toke import TokenToke
from routes.HealtCheckRouter import blueprint as health_router
from routes.BaseRouter import blueprint as tarifs_router
from routes.EeccxRouter import blueprint as eeccx_router
from routes.FreenetUploadRouter import blueprint as upload_router

# This class bundles blueprint registration so that all route collections are attached to the Flask application.
class WebManager:

    # The constructor assigns the provided Flask instance and calls the private registration helper.
    def __init__(self, app: Flask) -> None:
        self.app = app
        self._register_blueprints()

    # This helper method iterates over all blueprints and registers each of them on the Flask application.
    def _register_blueprints(self) -> None:
        for bp in (health_router, tarifs_router, eeccx_router, upload_router):
            self.app.register_blueprint(bp)


# A new Flask application instance is created and handed to the WebManager for blueprint registration.
app = Flask(__name__)
WebManager(app)

# This handler executes before every request to enforce the compulsory token parameter and validate it against the database.
@app.before_request
def _require_token():

    # This branch allows requests for static files to proceed without token validation.
    if request.endpoint == "static":
        return None

    # The variable “token” stores the value of the ?token query parameter or None when absent.
    token = request.args.get("token")

    # This branch rejects the request when the token parameter is missing.
    if not token:
        return (
            jsonify({"status": "NOAUTH", "message": "Please enter a valid token."}),
            401,
        )

    # The variable “session” holds a new SQLAlchemy session obtained from the MysqlManager.
    session = MysqlManager().getSession()
    try:

        # The variable “token_exists” evaluates to True when a matching token record is found in the database.
        token_exists = (
            session.query(TokenToke)
            .filter_by(token_toke=token)
            .first()
            is not None
        )
    finally:
        session.close()

    # This branch rejects the request when the supplied token does not exist in the database.
    if not token_exists:
        return (
            jsonify({"status": "NOAUTH", "message": "Please enter a valid token."}),
            401,
        )

# The application starts on all network interfaces on port 80 when the module is executed directly.
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80)
