"""YakPanel - Main FastAPI application"""
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import select

from app.core.config import get_settings, set_runtime_config_overrides
from app.core.database import init_db, AsyncSessionLocal
from app.models.config import Config
from app.api import (
    auth,
    backup,
    dashboard,
    user,
    site,
    ftp,
    database,
    files,
    crontab,
    firewall,
    ssl,
    monitor,
    docker,
    plugin,
    soft,
    terminal,
    config,
    logs,
    node,
    service,
    public_installer,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan - init DB on startup, load config from DB"""
    await init_db()
    # Load panel config from DB (persisted settings from Settings page)
    async with AsyncSessionLocal() as db:
        result = await db.execute(select(Config))
        rows = result.scalars().all()
        overrides = {r.key: r.value for r in rows if r.value is not None}
        set_runtime_config_overrides(overrides)
    yield
    # Cleanup if needed


settings = get_settings()
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    lifespan=lifespan,
)

_cors_origins = ["http://localhost:5173", "http://127.0.0.1:5173"]
_extra = (settings.cors_extra_origins or "").strip()
if _extra:
    _cors_origins.extend([o.strip() for o in _extra.split(",") if o.strip()])

app.add_middleware(
    CORSMiddleware,
    allow_origins=_cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(auth.router, prefix="/api/v1")
app.include_router(backup.router, prefix="/api/v1")
app.include_router(dashboard.router, prefix="/api/v1")
app.include_router(site.router, prefix="/api/v1")
app.include_router(ftp.router, prefix="/api/v1")
app.include_router(database.router, prefix="/api/v1")
app.include_router(files.router, prefix="/api/v1")
app.include_router(crontab.router, prefix="/api/v1")
app.include_router(firewall.router, prefix="/api/v1")
app.include_router(ssl.router, prefix="/api/v1")
app.include_router(monitor.router, prefix="/api/v1")
app.include_router(docker.router, prefix="/api/v1")
app.include_router(plugin.router, prefix="/api/v1")
app.include_router(soft.router, prefix="/api/v1")
app.include_router(node.router, prefix="/api/v1")
app.include_router(service.router, prefix="/api/v1")
app.include_router(terminal.router, prefix="/api/v1")
app.include_router(config.router, prefix="/api/v1")
app.include_router(user.router, prefix="/api/v1")
app.include_router(logs.router, prefix="/api/v1")
app.include_router(public_installer.router, prefix="/api/v1")


@app.get("/")
async def root():
    return {"app": settings.app_name, "version": settings.app_version}


@app.get("/api/health")
async def health():
    return {"status": "ok"}
