# -*- coding: utf-8 -*-
"""
FastAPI 应用入口
组装中间件、CORS、路由，启动 ASGI 应用。
"""

import logging

from contextlib import asynccontextmanager

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

from app.api.v1.router import api_v1_router
from app.core.config import settings
from app.middleware.audit import AuditMiddleware

# ---- 日志配置 ----
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(name)-12s | %(levelname)-5s | %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)


# ---- 生命周期管理 (替代已废弃的 on_event) ----
@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用启动/关闭时执行的钩子"""
    logger.info("SHBL-CRM 后端服务启动 | 版本: %s", settings.APP_VERSION)
    logger.info("数据库连接: %s@%s:%s/%s",
                settings.DB_USER, settings.DB_HOST, settings.DB_PORT, settings.DB_NAME)
    yield
    logger.info("SHBL-CRM 后端服务关闭")


# ---- 创建 FastAPI 实例 ----
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="天津硕博霖客户信息管理系统 - 后端 API",
    docs_url="/api/docs",       # Swagger UI 路径
    redoc_url="/api/redoc",     # ReDoc 路径
    openapi_url="/api/openapi.json",
    lifespan=lifespan,
)

# ---- 1. 审计中间件 (最先添加，确保拦截所有请求) ----
app.add_middleware(AuditMiddleware)

# ---- 2. CORS 跨域 (严格白名单模式，禁止 allow_origins=["*"]) ----
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,  # 仅允许配置中指定的来源
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
    allow_headers=["Authorization", "Content-Type"],
)

# ---- 3. 挂载 API 路由 ----
app.include_router(api_v1_router, prefix="/api/v1")


# ---- 根路径 (可选，方便快速验证服务是否存活) ----
@app.get("/", tags=["系统"])
async def root():
    return {
        "service": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "docs": "/api/docs",
    }
