from __future__ import annotations

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

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.core.openapi import API_DESCRIPTION, OPENAPI_TAGS
from app.middleware.logging import AccessLogMiddleware
from app.schemas.common import RootStatusRead
from app.services.agent_foundation import prepare_agent_foundation
from app.services.employee import prepare_employee_directory
from app.services.hermes_sync import sync_repository_hermes_skills
from app.services.knowledge import prepare_knowledge_library
from app.services.knowledge_index_tasks import knowledge_index_task_manager
from app.services.knowledge_rag import shutdown_knowledge_rag_runtime
from app.services.knowledge_scheduler import knowledge_index_scheduler


@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
    settings = get_settings()
    logger = get_logger("app.main")

    prepare_employee_directory()
    prepare_agent_foundation()
    prepare_knowledge_library()
    sync_repository_hermes_skills()
    knowledge_index_scheduler.start()
    logger.info(
        "Server ready - host=%s port=%s prefix=%s",
        settings.app_host,
        settings.app_port,
        settings.api_v1_prefix,
    )
    yield
    knowledge_index_scheduler.shutdown()
    knowledge_index_task_manager.shutdown()
    shutdown_knowledge_rag_runtime()


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",
        description=API_DESCRIPTION,
        openapi_tags=OPENAPI_TAGS,
        lifespan=lifespan,
    )

    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"],
        response_model=RootStatusRead,
        summary="服务根检查",
        description="用于快速确认后端服务进程已启动。",
    )
    def root() -> RootStatusRead:
        return RootStatusRead(message=f"{settings.app_name} is running")

    return app


app = create_app()
