"""
app/__init__.py
----------------
The "application factory". Rather than creating the Flask app as a
global variable, we build it inside a function (create_app). This is a
standard Flask pattern that keeps things clean and avoids import-order
headaches as the app grows (e.g. running tests with a different config).

To run the app locally: `flask --app run.py run --debug`
(see run.py and README.md for the full instructions)
"""

from flask import Flask

from config import Config
from app.extensions import db, login_manager


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # Wire up the extensions we created in extensions.py to this specific app
    db.init_app(app)
    login_manager.init_app(app)

    # --- Register blueprints ---
    # Each blueprint is a self-contained set of routes/templates for one
    # part of the site. url_prefix means every route inside that blueprint
    # automatically starts with that path, e.g. admin.dashboard -> /admin/
    from app.auth.routes import auth_bp
    from app.admin.routes import admin_bp
    from app.player.routes import player_bp

    app.register_blueprint(auth_bp, url_prefix="/auth")
    app.register_blueprint(admin_bp, url_prefix="/admin")
    app.register_blueprint(player_bp, url_prefix="/")

    # Make the club name available in every template without passing it
    # into render_template() manually every single time.
    @app.context_processor
    def inject_club_name():
        return {"club_name": app.config["CLUB_NAME"]}

    return app
