import logging
import os
from flask import Flask
from flask_security import SQLAlchemyUserDatastore
from werkzeug.middleware.proxy_fix import ProxyFix
import logging.config

from common.extensions import db, migrate, security, csrf
from config.logging_config import configure_logging
from config.config import get_config
import common.models.user
import common.models.interaction
import common.models.entitlements
import common.models.document

from common.models.user import User, Role

def create_app(config_file=None):
    app = Flask(__name__, static_url_path='/static')

    # Ensure all necessary headers are handled
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)

    environment = os.getenv('FLASK_ENV', 'development')

    match environment:
        case 'development':
            app.config.from_object(get_config('dev'))
        case 'test':
            app.config.from_object(get_config('test'))
        case 'staging':
            app.config.from_object(get_config('staging'))
        case 'production':
            app.config.from_object(get_config('prod'))
        case _:
            app.config.from_object(get_config('dev'))

    app.config['SESSION_KEY_PREFIX'] = 'eveai_ops_'

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Configureer logging op basis van de omgeving (K8s of traditioneel)
    try:
        configure_logging()
        logger = logging.getLogger(__name__)
        # Test dat logging werkt
        logger.debug("Logging test in eveai_ops")
    except Exception as e:
        print(f"Critical Error Initialising Error: {str(e)}")
        import traceback
        traceback.print_exc()

    logger.info("eveai_ops starting up")

    # Register extensions

    register_extensions(app)

    # Setup Flask-Security-Too
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore)

    # Register Blueprints
    register_blueprints(app)

    # Register Cache Handlers
    register_cache_handlers(app)

    # Debugging settings
    if app.config['DEBUG'] is True:
        app.logger.setLevel(logging.DEBUG)
        security_logger = logging.getLogger('flask_security')
        security_logger.setLevel(logging.DEBUG)
        sqlalchemy_logger = logging.getLogger('sqlalchemy.engine')
        sqlalchemy_logger.setLevel(logging.DEBUG)
        # log_request_middleware(app)   # Add this when debugging nginx or another proxy

    app.logger.info(f"EveAI Ops Server Started Successfully (PID: {os.getpid()})")
    app.logger.info("-------------------------------------------------------------------------------------------------")
    return app


def register_extensions(app):
    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)


def register_blueprints(app):
    # minimal health blueprint
    from .healthz import healthz_bp
    app.register_blueprint(healthz_bp)


def register_cache_handlers(app):
    pass
