from __future__ import annotations

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.router import api_router
from app.core.config import get_settings
from app.core.logging import get_logger, setup_logging
from app.middleware.logging import AccessLogMiddleware
from app.services.employee import prepare_employee_directory
from app.services.knowledge import prepare_knowledge_library


def create_app() -> FastAPI:
    settings = get_settings()

    setup_logging(
        level=settings.log_level,
        log_dir=settings.log_dir,
        enable_file=settings.log_file_enabled,
    )

    logger = get_logger("app.main")
    logger.info(
        "Starting %s (env=%s, debug=%s)", settings.app_name, settings.app_env, settings.app_debug
    )

    app = FastAPI(
        title=settings.app_name,
        debug=settings.app_debug,
        version="0.1.0",
    )

    app.add_middleware(AccessLogMiddleware)

    if settings.cors_origins:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=settings.cors_origins,
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    app.include_router(api_router, prefix=settings.api_v1_prefix)

    @app.get("/", tags=["root"])
    def root() -> dict[str, str]:
        return {"message": f"{settings.app_name} is running"}

    @app.on_event("startup")
    def _on_startup() -> None:
        prepare_employee_directory()
        prepare_knowledge_library()
        logger.info(
            "Server ready - host=%s port=%s prefix=%s",
            settings.app_host,
            settings.app_port,
            settings.api_v1_prefix,
        )

    return app


app = create_app()
