import os
from datetime import datetime

from flask import Flask

from config import Config
from app.extensions import db, migrate, mail, csrf

# Register models early so Alembic/Flask-Migrate detects them
from app import models


def create_app(config_class=Config):
    """Create and configure the Flask application."""

    app = Flask(__name__)
    app.config.from_object(config_class)

    # Ensure instance folder exists for SQLite
    try:
        os.makedirs(app.instance_path, exist_ok=True)
    except OSError:
        pass

    # Initialize extensions
    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    csrf.init_app(app)

    # Register blueprints
    from app.main import main_bp
    from app.about import about_bp
    from app.services import services_bp
    from app.divisions import divisions_bp
    from app.opportunities import opportunities_bp
    from app.programs import programs_bp
    from app.contact import contact_bp
    from app.predev import predev_bp
    from app.work_with_us import work_with_us_bp
    from app.subscribe import subscribe_bp

    app.register_blueprint(main_bp)
    app.register_blueprint(about_bp)
    app.register_blueprint(services_bp)
    app.register_blueprint(divisions_bp)
    app.register_blueprint(opportunities_bp)
    app.register_blueprint(programs_bp)
    app.register_blueprint(contact_bp)
    app.register_blueprint(predev_bp)
    app.register_blueprint(work_with_us_bp)
    app.register_blueprint(subscribe_bp)

    @app.context_processor
    def inject_global_template_values():
        from app.subscribe.forms import SubscribeForm
        return {
            "current_year": datetime.now().year,
            "subscribe_form": SubscribeForm(),
        }

    return app