import logging
import logging.config
from flask import Flask
import os

from common.utils.celery_utils import make_celery, init_celery
from common.extensions import db, minio_client, cache_manager
from config.logging_config import configure_logging
from config.config import get_config


def create_app(config_file=None):
    app = Flask(__name__)

    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'))

    configure_logging()

    register_extensions(app)

    register_cache_handlers(app)

    celery = make_celery(app.name, app.config)
    init_celery(celery, app)

    from . import tasks

    app.logger.info("EveAI Entitlements Server Started Successfully")
    app.logger.info("-------------------------------------------------------------------------------------------------")

    return app, celery


def register_extensions(app):
    db.init_app(app)
    cache_manager.init_app(app)


def register_cache_handlers(app):
    from common.utils.cache.license_cache import register_license_cache_handlers
    register_license_cache_handlers(cache_manager)
    from common.utils.cache.config_cache import register_config_cache_handlers
    register_config_cache_handlers(cache_manager)


app, celery = create_app()
