"""Langfuse Lens API — FastAPI application with domain-based routers."""
from __future__ import annotations

import os
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from api.routers import admin, auth, experiments, langfuse, pages, reports, settings
from src.env_settings import load_env_candidates
from src.bootstrap_config import apply_initial_env_from_config
from src.report_scheduler import start_scheduler, stop_scheduler
from src.user_store import (
    ensure_bootstrap_user,
    init_user_store,
    migrate_user_langfuse_settings_encryption,
)

ROOT = Path(__file__).resolve().parent.parent
API_DIR = Path(__file__).resolve().parent

# --- Module-level initialisation (runs at import time) ---
load_env_candidates()
apply_initial_env_from_config()
init_user_store()
ensure_bootstrap_user()
if str(os.getenv("AGENT_MIGRATE_LANGFUSE_SETTINGS_ON_STARTUP", "true")).strip().lower() in {"1", "true", "yes", "on"}:
    try:
        migrate_user_langfuse_settings_encryption(dry_run=False)
    except Exception:
        # Encryption key may be intentionally absent in local/dev bootstrap.
        pass


@asynccontextmanager
async def lifespan(app: FastAPI):
    import logging
    try:
        await start_scheduler()
    except Exception:
        logging.getLogger(__name__).exception("Report scheduler failed to start (non-fatal)")
    yield
    await stop_scheduler()


app = FastAPI(title="Langfuse Lens API", version="0.3.0", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=str(API_DIR / "static")), name="static")

# --- Register routers ---
app.include_router(auth.router)
app.include_router(pages.router)
app.include_router(settings.router)
app.include_router(langfuse.router)
app.include_router(reports.router)
app.include_router(experiments.router)
app.include_router(admin.router)
