# File: app/__init__.py

import os
import logging
from datetime import datetime

from dotenv import load_dotenv, find_dotenv
from flask import Flask, request

from .config           import Config
from .extensions       import db, migrate, login_manager, csrf
from .plugin_loader    import register_plugins

def create_app():
    # 1) load .env
    if p := find_dotenv():
        load_dotenv(p, override=True)

    # 2) create Flask
    app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), '..', 'static'))
    app.config.from_object(Config)

    # 3) logging
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    app.logger.setLevel(logging.INFO)
    app.logger.addHandler(handler)
    app.logger.info("🚀 Starting Flask app")

    # 4) init extensions
    csrf.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    app.logger.info("🔗 Extensions initialized")

    # 5) register core routes, errors, etc.
    from .errors import bp as errors_bp  # noqa: E402
    app.register_blueprint(errors_bp)
    from .routes import init_app as register_core_routes  # noqa: E402
    register_core_routes(app)

    # 6) register all plugins
    register_plugins(app)

    # 8) any context-processors, before/after teardown…
    @app.context_processor
    def inject_now():
        return {'utcnow': datetime.utcnow()}

    return app
