from __future__ import annotations

import atexit
import logging

from flask import Flask

from .config import AppConfig, load_config
from .routes import register_routes
from .scheduler import StatusScheduler
from .storage import Storage


def create_app(config: AppConfig | None = None) -> Flask:
    app_config = config or load_config()
    storage = Storage(app_config.db_path, app_config.node_id_prefix)
    scheduler = StatusScheduler(storage, app_config)

    app = Flask(__name__)
    app.config["APP_CONFIG"] = app_config
    app.config["STORAGE"] = storage
    app.config["SCHEDULER"] = scheduler

    register_routes(app, storage, scheduler, app_config)

    scheduler.start()

    def _cleanup() -> None:
        logging.getLogger("argus.master").info("Shutting down master app")
        try:
            scheduler.stop()
        except Exception:  # pragma: no cover - defensive
            logging.getLogger("argus.master").exception("Failed to stop scheduler")
        try:
            storage.close()
        except Exception:  # pragma: no cover - defensive
            logging.getLogger("argus.master").exception("Failed to close storage")

    atexit.register(_cleanup)

    return app
