from __future__ import annotations

import os

from fastapi import FastAPI
from sqladmin import Admin

from app.admin.routes import router as admin_router
from app.admin.views import JobAdmin, JobLogAdmin
from app.core.config import settings
from app.core.logging import setup_logging
from app.db.engine import engine
from app.db.schema import ensure_schema
from app.security.fernet import get_or_create_fernet_key


def _init_db() -> None:
    ensure_schema(engine)


def _ensure_runtime() -> None:
    # 确保 data 目录存在
    os.makedirs(settings.data_dir, exist_ok=True)
    if settings.log_dir:
        os.makedirs(settings.log_dir, exist_ok=True)
    # 确保 Fernet key 准备好（或自动生成）
    get_or_create_fernet_key(settings.fernet_key_path)
    _init_db()


def create_app() -> FastAPI:
    setup_logging()
    _ensure_runtime()

    app = FastAPI(title=settings.app_name)

    app.include_router(admin_router)

    admin = Admin(app=app, engine=engine, templates_dir="app/admin/templates")
    admin.add_view(JobAdmin)
    admin.add_view(JobLogAdmin)

    @app.get("/health")
    def health():
        return {"ok": True, "name": settings.app_name}

    return app


app = create_app()


