"""<<project_name>> FastAPI 应用工厂 (app factory).

负责创建 FastAPI 实例、初始化日志、挂载 app/routes/ 下的所有业务路由。
★ 普通用户无需修改本文件 ★ —— 加接口请到 app/routes/ 新建文件。
You normally never edit this file — add endpoints under app/routes/.
"""

from contextlib import asynccontextmanager

from fastapi import FastAPI

from app.logging import get_logger, init_logging
from app.routes import register_routes
from app.settings import settings

# 启动时初始化日志系统一次 (initialize logging once at import/startup)
init_logging(settings.log)
logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期：启动/关闭时记录结构化日志."""
    logger.info(
        "application starting",
        title=settings.app.title,
        host=settings.server.host,
        port=settings.server.port,
    )
    yield
    logger.info("application stopped")


def create_app() -> FastAPI:
    """构建并返回 FastAPI 应用实例."""
    app = FastAPI(
        title=settings.app.title,
        version="<<project_version>>",
        lifespan=lifespan,
    )

    # 自动挂载 app/routes/ 下注册的全部路由
    register_routes(app)

    return app


app = create_app()
