# ！/usr/bin/ python
# -*- coding: utf-8 -*-
'''
@Project    : lq-agent-api
@File       :__init__.py.py
@IDE        :PyCharm
@Author     :
@Date       :2025/7/10 17:04
'''

import uuid
from contextlib import asynccontextmanager
from contextvars import ContextVar

from fastapi import FastAPI, APIRouter
from foundation.infrastructure.mysql.async_mysql_conn_pool import AsyncMySQLPool
from foundation.observability.logger.loggering import server_logger

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时加载工具
    #await mcp_server.get_mcp_tools()
    # 全局数据库连接池实例
    async_db_pool = None
    # async_db_pool = AsyncMySQLPool()
    # await async_db_pool.initialize()
    # app.state.async_db_pool = async_db_pool
    #server_logger.info(f"✅ MySQL数据库连接池:{app.state.async_db_pool}")

    # 初始化敏感词检测器
    try:
        from core.construction_review.component.reviewers.utils import SensitiveWordChecker
        server_logger.info("开始初始化敏感词检测器...")
        stats = SensitiveWordChecker.initialize()
        server_logger.info(f"敏感词检测器初始化成功: 加载 {stats.get('total', 0)} 个敏感词，来自 {stats.get('files', 0)} 个文件")
    except Exception as e:
        server_logger.error(f"敏感词检测器初始化失败: {e}", exc_info=True)

    yield
    # 关闭时清理
    if async_db_pool and async_db_pool.close:
        await async_db_pool.close()


current_operation_id: ContextVar[str] = ContextVar("operation_id", default=str(uuid.uuid4()))



def get_operation_id() -> str:
    """依赖项：获取当前操作ID"""
    return current_operation_id.get()
