from __future__ import annotations

import logging
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI

from evalkit.server.db.session import init_db
from evalkit.server.routes import api as api_routes
from evalkit.server.routes import dashboard, evaluations, projects
from evalkit.server.routes.traces import api_router as traces_api_router
from evalkit.server.routes.traces import html_router as traces_html_router

logger = logging.getLogger("evalkit.server")


def _configure_logging() -> None:
    level_name = os.environ.get("EVALKIT_LOG_LEVEL", "INFO").upper()
    level = getattr(logging, level_name, logging.INFO)
    logging.getLogger("evalkit").setLevel(level)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s"))
    root = logging.getLogger("evalkit")
    if not root.handlers:
        root.addHandler(handler)


@asynccontextmanager
async def lifespan(app: FastAPI):
    _configure_logging()
    logger.info("Initializing database")
    init_db()
    logger.info("Server ready")
    yield


def create_app() -> FastAPI:
    app = FastAPI(title="evalkit", version="0.1.0", lifespan=lifespan)
    app.include_router(dashboard.router)
    app.include_router(projects.router)
    app.include_router(evaluations.router)
    app.include_router(api_routes.router, prefix="/api/v1")
    app.include_router(traces_api_router, prefix="/api/v1")
    app.include_router(traces_html_router)
    return app


app = create_app()
