"""
MCP Server 主程序

题目管理与检索系统的主入口程序，负责：
- 初始化配置和日志系统
- 创建和启动 FastMCP Server
- 注册 MCP Tools
- 实现优雅启动和关闭
"""

import sys
import os
from pathlib import Path
from typing import Optional, List
import importlib.metadata

# Windows 控制台编码处理
if sys.platform == 'win32':
    try:
        # 设置 stdout/stderr/stdin 为 UTF-8 编码，用于 MCP STDIO 通信
        import io
        # line_buffering=True 确保每行立即刷新，这对 JSON-RPC 通信至关重要
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace', line_buffering=True)
        sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace', line_buffering=True)
        # 同时设置 stdin 编码，确保能正确读取 MCP 消息
        sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8', errors='replace')
    except Exception as e:
        # 如果设置失败，记录错误但继续运行
        print(f"Warning: Failed to set UTF-8 encoding: {e}", file=sys.stderr)

# 尝试导入 TOML 解析库（仅用于开发环境）
try:
    if sys.version_info >= (3, 11):
        import tomllib
    else:
        import tomli as tomllib
except ImportError:
    tomllib = None

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from fastmcp import FastMCP

from src.core.config import get_config
from src.core.logger import get_logger, set_request_id, setup_logger

from src.database.database_manager import DatabaseManager
from src.database.sqlite_dao import SQLiteDAO
from src.database.chroma_dao import ChromaDAO
from src.services.embedding_service import EmbeddingService
from src.services.management_service import ManagementService
from src.services.search_service import SearchService
from src.services.import_service import ImportService
from src.services.analytics_service import AnalyticsService
from src.services.export_service import ExportService

# 全局变量
mcp_server = None
config = None
logger = None
db_manager = None
management_service = None
search_service = None
import_service = None
analytics_service = None
export_service = None


def get_version() -> str:
    """
    获取包版本号
    
    优先使用包元数据，失败时尝试从 pyproject.toml 读取
    
    Returns:
        str: 版本号，读取失败时返回 "1.0.0"
    """
    try:
        # 方法1：从包元数据读取（适用于已安装的包）
        try:
            version = importlib.metadata.version("questions-mcp-server")
            return version
        except importlib.metadata.PackageNotFoundError:
            pass
        
        # 方法2：从 pyproject.toml 读取（适用于开发环境）
        possible_paths = [
            Path(__file__).parent.parent / "pyproject.toml",
            Path(__file__).parent.parent.parent / "pyproject.toml",
        ]
        
        for pyproject_path in possible_paths:
            if pyproject_path.exists():
                # 使用 TOML 库解析
                if tomllib is not None:
                    with open(pyproject_path, "rb") as f:
                        data = tomllib.load(f)
                        return data.get("project", {}).get("version", "1.0.0")
                else:
                    # 降级方案：手动解析 version 行
                    with open(pyproject_path, "r", encoding="utf-8") as f:
                        for line in f:
                            if line.strip().startswith("version"):
                                # 提取 version = "1.0.3" 中的版本号
                                version = line.split("=")[1].strip().strip('"').strip("'")
                                return version
        
        return "1.0.0"
    except Exception:
        return "1.0.0"


def initialize_system():
    """
    初始化系统配置和日志

    Returns:
        tuple: (config, logger) 配置和日志实例
    """
    global config, logger
    
    # 检测是否在 MCP 模式下运行
    is_mcp_mode = not sys.stdin.isatty() if hasattr(sys.stdin, 'isatty') else False

    try:
        # 1. 加载配置
        if not is_mcp_mode:
            print("正在加载配置...")
        config = get_config()
        if not is_mcp_mode:
            print("[OK] 配置加载成功")

        # 2. 初始化日志系统
        if not is_mcp_mode:
            print("正在初始化日志系统...")
        logger = setup_logger(config)
        logger.info("日志系统初始化成功")
        if not is_mcp_mode:
            print("[OK] 日志系统初始化成功")

        # 3. 验证关键配置
        logger.info("验证关键配置...")
        logger.info(f"- SQLite 数据库路径: {config.sqlite_db_path}")
        logger.info(f"- ChromaDB 持久化目录: {config.chromadb_persist_dir}")
        logger.info(f"- ChromaDB Collection 名称: {config.chromadb_collection_name}")
        logger.info(f"- Embedding API 端点: {config.embedding_api_endpoint}")
        logger.info(f"- 日志级别: {config.log_level}")
        if not is_mcp_mode:
            print("[OK] 配置验证完成")

        return config, logger

    except Exception as e:
        error_msg = f"[ERROR] 系统初始化失败: {e}"
        if is_mcp_mode:
            # MCP 模式下，输出到 stderr
            print(error_msg, file=sys.stderr)
        else:
            print(error_msg)
        sys.exit(1)


def create_mcp_server(config, logger):
    """
    创建 FastMCP Server 实例

    Returns:
        FastMCP: Server 实例
    """
    try:
        logger.info("创建 FastMCP Server...")

        # 创建 MCP Server
        server = FastMCP(
            name=config.get("server.name", "questions_mcp_server"),
            version=config.get("server.version", "1.0.0"),
        )

        logger.info("[OK] FastMCP Server 创建成功")
        return server

    except Exception as e:
        logger.error(f"创建 FastMCP Server 失败: {e}")
        raise


def initialize_services(config, logger):
    """
    初始化数据库、Embedding、管理、搜索、导入、统计分析和导出服务

    Args:
        config: 配置对象
        logger: 日志记录器

    Returns:
        tuple: 所有服务实例
    """
    global db_manager, management_service, search_service, import_service, analytics_service, export_service

    try:
        logger.info("初始化数据库和services...")

        # 1. 初始化数据库访问对象
        logger.info("初始化数据库DAO...")
        sqlite_dao = SQLiteDAO(config.sqlite_db_path, logger)
        chroma_dao = ChromaDAO(
            persist_dir=config.chromadb_persist_dir,
            collection_name=config.chromadb_collection_name,
            logger=logger
        )

        # 2. 初始化Embedding服务
        logger.info("初始化Embedding服务...")
        embedding_service = EmbeddingService(config_manager=config)

        # 3. 初始化数据库管理器
        logger.info("初始化数据库管理器...")
        db_manager = DatabaseManager(
            sqlite_dao=sqlite_dao,
            chroma_dao=chroma_dao,
            embedding_service=embedding_service,
            logger=logger
        )

        # 4. 初始化数据库
        logger.info("初始化数据库...")
        db_manager.initialize_databases()

        # 5. 初始化管理服务
        logger.info("初始化题目管理服务...")
        management_service = ManagementService(
            db_manager=db_manager,
            embedding_service=embedding_service,
            logger=logger
        )

        # 6. 初始化搜索服务
        logger.info("初始化题目检索服务...")
        search_service = SearchService(
            db_manager=db_manager,
            embedding_service=embedding_service,
            logger=logger
        )

        # 7. 初始化导入服务
        logger.info("初始化批量导入服务...")
        import_service = ImportService(
            db_manager=db_manager,
            embedding_service=embedding_service,
            management_service=management_service,
            search_service=search_service,
            config=config,
            logger=logger
        )

        # 8. 初始化统计分析服务
        logger.info("初始化统计分析服务...")
        analytics_service = AnalyticsService(
            db_manager=db_manager,
            logger=logger
        )

        # 9. 初始化导出服务
        logger.info("初始化导出服务...")
        export_service = ExportService(
            config=config,
            logger=logger
        )

        logger.info("[OK] 所有服务初始化完成")
        return db_manager, management_service, search_service, import_service, analytics_service, export_service

    except Exception as e:
        logger.error(f"服务初始化失败: {e}")
        raise


def register_tools(server: FastMCP, config, logger):
    """
    注册 MCP Tools

    Args:
        server: FastMCP Server 实例
        config: 配置对象
        logger: 日志记录器
    """
    global db_manager, management_service, search_service, import_service, analytics_service, export_service

    logger.info("注册 MCP Tools...")

    # 注册健康检查工具
    @server.tool()
    def health_check() -> dict:
        """
        健康检查

        检查 MCP Server 的运行状态和各组件的健康状况。

        Returns:
            dict: 健康检查结果
        """
        request_id = set_request_id()
        logger.info(f"执行健康检查 [request_id: {request_id}]")

        try:
            result = {
                "status": "healthy",
                "service": "questions_mcp_server",
                "version": config.get("server.version", "1.0.0"),
                "components": {
                    "config": "loaded",
                    "logger": "active",
                    "database": "not_initialized",  # 阶段2实现后更新
                    "embedding_api": "not_configured",  # 阶段3实现后更新
                },
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

            logger.info("健康检查完成: 系统运行正常")
            return result

        except Exception as e:
            logger.error(f"健康检查失败: {e}")
            return {
                "status": "unhealthy",
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # 注册获取服务器信息工具
    @server.tool()
    def get_server_info() -> dict:
        """
        获取服务器信息

        返回 MCP Server 的详细配置和状态信息。

        Returns:
            dict: 服务器信息
        """
        request_id = set_request_id()
        logger.info(f"获取服务器信息 [request_id: {request_id}]")

        try:
            info = {
                "name": config.get("server.name", "questions_mcp_server"),
                "version": config.get("server.version", "1.0.0"),
                "description": config.get(
                    "server.description", "题目管理与检索系统 MCP Server"
                ),
                "configuration": {
                    "database": {
                        "sqlite_path": config.sqlite_db_path,
                        "chromadb_dir": config.chromadb_persist_dir,
                        "collection_name": config.chromadb_collection_name,
                    },
                    "embedding": {
                        "api_endpoint": config.embedding_api_endpoint,
                        "model": config.embedding_model,
                        "batch_size": config.embedding_batch_size,
                    },
                    "performance": {
                        "search_default_top_k": config.get(
                            "performance.search.default_top_k", 10
                        ),
                        "search_max_top_k": config.get(
                            "performance.search.max_top_k", 100
                        ),
                        "pagination_default_size": config.get(
                            "performance.pagination.default_page_size", 20
                        ),
                    },
                },
                "features": {
                    "search": "available",
                    "management": "available",
                    "statistics": "available",
                    "batch_import": "available",
                },
                "status": "running",
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

            logger.info("服务器信息获取成功")
            return info

        except Exception as e:
            logger.error(f"获取服务器信息失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # 注册测试工具（用于验证系统功能）
    @server.tool()
    def test_configuration() -> dict:
        """
        测试配置

        验证系统配置是否正确加载和有效。

        Returns:
            dict: 配置测试结果
        """
        request_id = set_request_id()
        logger.info(f"测试配置 [request_id: {request_id}]")

        try:
            tests = []
            all_passed = True

            # 测试1: 配置文件是否加载
            tests.append(
                {
                    "name": "配置文件加载",
                    "status": "passed" if config else "failed",
                    "details": "配置对象存在" if config else "配置对象不存在",
                }
            )

            # 测试2: 必需配置项是否存在
            required_configs = [
                ("embedding.api_key", "Embedding API 密钥"),
                ("database.sqlite.db_path", "SQLite 数据库路径"),
                ("database.chromadb.persist_dir", "ChromaDB 持久化目录"),
            ]

            for key, description in required_configs:
                value = config.get(key)
                passed = bool(value)
                if not passed:
                    all_passed = False
                tests.append(
                    {
                        "name": f"配置项: {description}",
                        "status": "passed" if passed else "failed",
                        "details": f"值: {'已配置' if passed else '未配置'}",
                    }
                )

            # 测试3: 数据目录是否可访问
            from pathlib import Path

            db_path = Path(config.sqlite_db_path)
            db_dir_exists = db_path.parent.exists()
            tests.append(
                {
                    "name": "数据库目录可访问性",
                    "status": "passed" if db_dir_exists else "warning",
                    "details": f"目录: {db_path.parent}",
                }
            )

            chroma_path = Path(config.chromadb_persist_dir)
            chroma_dir_exists = chroma_path.exists()
            tests.append(
                {
                    "name": "ChromaDB 目录可访问性",
                    "status": "passed" if chroma_dir_exists else "warning",
                    "details": f"目录: {chroma_path}",
                }
            )

            result = {
                "overall_status": "passed" if all_passed else "failed",
                "total_tests": len(tests),
                "passed": sum(1 for t in tests if t["status"] == "passed"),
                "failed": sum(1 for t in tests if t["status"] == "failed"),
                "warnings": sum(1 for t in tests if t["status"] == "warning"),
                "tests": tests,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

            logger.info(f"配置测试完成: {result['overall_status']}")
            return result

        except Exception as e:
            logger.error(f"配置测试失败: {e}")
            return {
                "overall_status": "error",
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # -------------------------------------------------------------------------
    # 题目检索工具
    # -------------------------------------------------------------------------

    @server.tool()
    def search_questions(
        query: str,
        search_type: str = "hybrid",
        top_k: int = 10,
        filters: Optional[dict] = None,
        semantic_weight: float = 0.6,
        keyword_weight: float = 0.4,
        min_similarity: float = 0.0,
        include_metadata: bool = True
    ) -> dict:
        """
        题目检索工具

        支持语义检索、关键词检索和混合检索三种模式。

        Args:
            query: 检索查询文本
            search_type: 检索类型，可选值：'semantic'（语义）、'keyword'（关键词）、'hybrid'（混合，默认）
            top_k: 返回结果数量（1-100，默认10）
            filters: 过滤条件字典，可包含：category, difficulty, question_type, status, tags
            semantic_weight: 语义检索权重（仅混合模式，0-1，默认0.6）
            keyword_weight: 关键词检索权重（仅混合模式，0-1，默认0.4）
            min_similarity: 最低相似度阈值（仅语义和混合模式，0-1，默认0.0）
            include_metadata: 是否包含答案和解析（默认True）

        Returns:
            dict: 检索结果，包含题目列表和元信息
        """
        request_id = set_request_id()
        logger.info(f"执行题目检索 [request_id: {request_id}]")

        try:
            # 准备过滤条件
            from src.database.models import QuestionSearchFilter
            search_filter = None
            if filters:
                search_filter = QuestionSearchFilter(
                    category=filters.get('category'),
                    difficulty=filters.get('difficulty'),
                    question_type=filters.get('question_type'),
                    status=filters.get('status'),
                    tags=filters.get('tags')
                )

            # 根据检索类型调用相应服务
            if search_type == "semantic":
                result = search_service.search_by_semantic(
                    query=query,
                    top_k=top_k,
                    filters=search_filter,
                    min_similarity=min_similarity,
                    include_metadata=include_metadata
                )
            elif search_type == "keyword":
                result = search_service.search_by_keyword(
                    query=query,
                    top_k=top_k,
                    filters=search_filter,
                    include_metadata=include_metadata
                )
            else:  # hybrid
                result = search_service.search_hybrid(
                    query=query,
                    top_k=top_k,
                    filters=search_filter,
                    semantic_weight=semantic_weight,
                    keyword_weight=keyword_weight,
                    min_similarity=min_similarity,
                    include_metadata=include_metadata
                )

            logger.info(f"题目检索完成: 类型={search_type}, 查询='{query}', 返回{result['total_results']}个结果")
            return result

        except ValueError as e:
            logger.error(f"题目检索参数验证失败: {e}")
            return {
                "error": str(e),
                "search_type": search_type,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }
        except Exception as e:
            logger.error(f"题目检索失败: {e}")
            return {
                "error": str(e),
                "search_type": search_type,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # -------------------------------------------------------------------------
    # 题目管理工具
    # -------------------------------------------------------------------------

    @server.tool()
    def list_questions(
        page: int = 1,
        page_size: int = 20,
        category: Optional[str] = None,
        difficulty: Optional[str] = None,
        question_type: Optional[str] = None,
        status: Optional[str] = None
    ) -> dict:
        """
        查询题目列表

        Args:
            page: 页码（从1开始）
            page_size: 每页数量（1-100，默认20）
            category: 分类过滤
            difficulty: 难度过滤
            question_type: 题型过滤
            status: 状态过滤

        Returns:
            dict: 题目列表和分页信息
        """
        request_id = set_request_id()
        logger.info(f"查询题目列表 [request_id: {request_id}]")

        try:
            from src.database.models import QuestionSearchFilter

            filters = QuestionSearchFilter(
                category=category,
                difficulty=difficulty,
                question_type=question_type,
                status=status
            )

            questions, total = management_service.list_questions(
                filters=filters,
                page=page,
                page_size=page_size
            )

            result = {
                "questions": questions,
                "pagination": {
                    "page": page,
                    "page_size": page_size,
                    "total": total,
                    "total_pages": (total + page_size - 1) // page_size
                },
                "filters_applied": {
                    "category": category,
                    "difficulty": difficulty,
                    "question_type": question_type,
                    "status": status
                },
                "timestamp": from_src_utils_import_get_current_timestamp()
            }

            logger.info(f"查询题目列表完成: 第{page}页, 共{total}个结果")
            return result

        except Exception as e:
            logger.error(f"查询题目列表失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # -------------------------------------------------------------------------
    # 批量导入工具 (阶段6)
    # -------------------------------------------------------------------------

    @server.tool()
    def create_import_session(
        source_type: str,
        source_config: dict,
        options: Optional[dict] = None
    ) -> dict:
        """
        创建批量导入会话

        创建一个新的批量导入任务，支持多种数据源类型。

        Args:
            source_type: 数据源类型 ('external_api', 'json_file', 'csv_file', 'manual')
            source_config: 数据源配置字典
                - external_api: {'endpoint': 'API端点', 'api_key': '密钥(可选，从环境变量获取)'}
                - json_file: {'file_path': 'JSON文件路径'}
                - csv_file: {'file_path': 'CSV文件路径'}
                - manual: {'questions': [题目列表]}
            options: 导入选项字典
                - skip_duplicates: 是否跳过重复题目 (默认True)
                - validate_only: 是否仅验证不导入 (默认False)
                - replace_existing: 是否替换已存在题目 (默认False)
                - import_answers: 是否导入答案 (默认True)
                - import_explanations: 是否导入解析 (默认True)

        Returns:
            dict: 导入会话信息
        """
        request_id = set_request_id()
        logger.info(f"创建导入会话 [request_id: {request_id}]")

        try:
            session_id = import_service.create_import_session(
                source_type=source_type,
                source_config=source_config,
                options=options
            )

            result = {
                "session_id": session_id,
                "source_type": source_type,
                "status": "pending",
                "timestamp": from_src_utils_import_get_current_timestamp()
            }

            logger.info(f"创建导入会话成功: {session_id}")
            return result

        except Exception as e:
            logger.error(f"创建导入会话失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def start_import(session_id: str) -> dict:
        """
        开始批量导入

        开始执行指定的导入会话。

        Args:
            session_id: 导入会话ID

        Returns:
            dict: 导入结果统计
        """
        request_id = set_request_id()
        logger.info(f"开始导入 [request_id: {request_id}]")

        try:
            result = import_service.start_import(session_id)

            logger.info(
                f"导入完成: {session_id}, "
                f"成功{result['successful']}, 失败{result['failed']}"
            )
            return result

        except Exception as e:
            logger.error(f"导入失败: {e}")
            return {
                "error": str(e),
                "session_id": session_id,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def pause_import(session_id: str) -> dict:
        """
        暂停导入任务

        暂停正在运行的导入任务，可稍后恢复。

        Args:
            session_id: 导入会话ID

        Returns:
            dict: 操作结果
        """
        request_id = set_request_id()
        logger.info(f"暂停导入 [request_id: {request_id}]")

        try:
            success = import_service.pause_import(session_id)

            result = {
                "session_id": session_id,
                "paused": success,
                "timestamp": from_src_utils_import_get_current_timestamp()
            }

            logger.info(f"暂停导入: {session_id}, 成功: {success}")
            return result

        except Exception as e:
            logger.error(f"暂停导入失败: {e}")
            return {
                "error": str(e),
                "session_id": session_id,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def resume_import(session_id: str) -> dict:
        """
        恢复导入任务

        恢复之前暂停的导入任务。

        Args:
            session_id: 导入会话ID

        Returns:
            dict: 导入结果统计
        """
        request_id = set_request_id()
        logger.info(f"恢复导入 [request_id: {request_id}]")

        try:
            result = import_service.resume_import(session_id)

            logger.info(f"恢复导入完成: {session_id}")
            return result

        except Exception as e:
            logger.error(f"恢复导入失败: {e}")
            return {
                "error": str(e),
                "session_id": session_id,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def cancel_import(session_id: str) -> dict:
        """
        取消导入任务

        取消正在运行或暂停的导入任务。

        Args:
            session_id: 导入会话ID

        Returns:
            dict: 操作结果
        """
        request_id = set_request_id()
        logger.info(f"取消导入 [request_id: {request_id}]")

        try:
            success = import_service.cancel_import(session_id)

            result = {
                "session_id": session_id,
                "cancelled": success,
                "timestamp": from_src_utils_import_get_current_timestamp()
            }

            logger.info(f"取消导入: {session_id}, 成功: {success}")
            return result

        except Exception as e:
            logger.error(f"取消导入失败: {e}")
            return {
                "error": str(e),
                "session_id": session_id,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_import_session(session_id: str) -> dict:
        """
        获取导入会话详情

        获取指定导入会话的详细信息。

        Args:
            session_id: 导入会话ID

        Returns:
            dict: 会话详情
        """
        request_id = set_request_id()
        logger.info(f"获取导入会话 [request_id: {request_id}]")

        try:
            session = import_service.get_import_session(session_id)

            if session:
                logger.info(f"获取导入会话成功: {session_id}")
                return session
            else:
                return {
                    "error": f"导入会话不存在: {session_id}",
                    "timestamp": from_src_utils_import_get_current_timestamp()
                }

        except Exception as e:
            logger.error(f"获取导入会话失败: {e}")
            return {
                "error": str(e),
                "session_id": session_id,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def list_import_sessions(status: Optional[str] = None) -> dict:
        """
        列出导入会话

        列出所有导入会话或按状态过滤。

        Args:
            status: 状态过滤 ('pending', 'running', 'completed', 'failed', 'paused', 'cancelled')

        Returns:
            dict: 会话列表
        """
        request_id = set_request_id()
        logger.info(f"列出导入会话 [request_id: {request_id}]")

        try:
            sessions = import_service.list_import_sessions(status=status)

            result = {
                "sessions": sessions,
                "total": len(sessions),
                "timestamp": from_src_utils_import_get_current_timestamp()
            }

            logger.info(f"列出导入会话完成: 共{len(sessions)}个")
            return result

        except Exception as e:
            logger.error(f"列出导入会话失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def generate_import_report(session_id: str) -> dict:
        """
        生成导入报告

        生成指定导入会话的详细报告。

        Args:
            session_id: 导入会话ID

        Returns:
            dict: 导入报告
        """
        request_id = set_request_id()
        logger.info(f"生成导入报告 [request_id: {request_id}]")

        try:
            report = import_service.generate_import_report(session_id)

            logger.info(f"生成导入报告完成: {session_id}")
            return report

        except Exception as e:
            logger.error(f"生成导入报告失败: {e}")
            return {
                "error": str(e),
                "session_id": session_id,
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def export_import_statistics() -> dict:
        """
        导出导入统计

        导出所有导入会话的统计信息。

        Returns:
            dict: 统计报告
        """
        request_id = set_request_id()
        logger.info(f"导出导入统计 [request_id: {request_id}]")

        try:
            report = import_service.export_import_statistics()

            logger.info(f"导出导入统计完成")
            return report

        except Exception as e:
            logger.error(f"导出导入统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # =====================================================================
    # 阶段7：统计分析和导出相关的MCP Tools
    # =====================================================================

    @server.tool()
    def get_overall_statistics() -> dict:
        """
        获取整体统计概览

        获取题库的整体统计指标，包括题目总数、发布状态分布等。

        Returns:
            dict: 整体统计数据
        """
        request_id = set_request_id()
        logger.info(f"获取整体统计概览 [request_id: {request_id}]")

        try:
            result = analytics_service.get_overall_statistics()
            logger.info(f"整体统计获取完成")
            return result

        except Exception as e:
            logger.error(f"获取整体统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_category_statistics() -> dict:
        """
        获取分类统计

        统计各分类的题目数量、难度分布等信息。

        Returns:
            dict: 分类统计数据
        """
        request_id = set_request_id()
        logger.info(f"获取分类统计 [request_id: {request_id}]")

        try:
            result = analytics_service.get_category_statistics()
            logger.info(f"分类统计获取完成: {result['total_categories']}个分类")
            return result

        except Exception as e:
            logger.error(f"获取分类统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_difficulty_statistics() -> dict:
        """
        获取难度分布统计

        统计各难度等级的题目数量和分布情况。

        Returns:
            dict: 难度统计数据
        """
        request_id = set_request_id()
        logger.info(f"获取难度统计 [request_id: {request_id}]")

        try:
            result = analytics_service.get_difficulty_statistics()
            logger.info(f"难度统计获取完成")
            return result

        except Exception as e:
            logger.error(f"获取难度统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_tag_statistics(top_n: int = 20) -> dict:
        """
        获取标签统计

        统计各标签的使用情况，按使用次数排序。

        Args:
            top_n: 返回前N个标签

        Returns:
            dict: 标签统计数据
        """
        request_id = set_request_id()
        logger.info(f"获取标签统计 [request_id: {request_id}]")

        try:
            result = analytics_service.get_tag_statistics(top_n=top_n)
            logger.info(f"标签统计获取完成: {len(result['tags'])}个标签")
            return result

        except Exception as e:
            logger.error(f"获取标签统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_quality_metrics() -> dict:
        """
        获取题目质量评估

        评估题目的质量和完整度，计算质量评分。

        Returns:
            dict: 质量评估数据
        """
        request_id = set_request_id()
        logger.info(f"获取质量评估 [request_id: {request_id}]")

        try:
            result = analytics_service.get_quality_metrics()
            logger.info(f"质量评估完成: 评估{result['total_questions_evaluated']}道题目")
            return result

        except Exception as e:
            logger.error(f"获取质量评估失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_time_series_analysis(days: int = 30, period: str = "day") -> dict:
        """
        获取时间序列分析

        分析指定时间范围内的题目创建、更新趋势。

        Args:
            days: 分析过去多少天的数据 (默认30天)
            period: 时间粒度 ('day', 'week', 'month')

        Returns:
            dict: 时间序列分析数据
        """
        request_id = set_request_id()
        logger.info(f"获取时间序列分析 [request_id: {request_id}]")

        try:
            result = analytics_service.get_time_series_analysis(days=days, period=period)
            logger.info(f"时间序列分析完成: {result['total_records']}条记录")
            return result

        except Exception as e:
            logger.error(f"获取时间序列分析失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_question_type_statistics() -> dict:
        """
        获取题目类型统计

        统计各题目类型的数量分布。

        Returns:
            dict: 题目类型统计数据
        """
        request_id = set_request_id()
        logger.info(f"获取题目类型统计 [request_id: {request_id}]")

        try:
            result = analytics_service.get_question_type_statistics()
            logger.info(f"题目类型统计完成: {result['total_types']}种类型")
            return result

        except Exception as e:
            logger.error(f"获取题目类型统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def get_status_statistics() -> dict:
        """
        获取状态分布统计

        统计各状态（草稿、已发布、已归档）的题目分布。

        Returns:
            dict: 状态统计数据
        """
        request_id = set_request_id()
        logger.info(f"获取状态分布统计 [request_id: {request_id}]")

        try:
            result = analytics_service.get_status_statistics()
            logger.info(f"状态分布统计完成")
            return result

        except Exception as e:
            logger.error(f"获取状态分布统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def generate_analysis_report() -> dict:
        """
        生成综合分析报告

        生成包含所有统计数据的综合分析报告。

        Returns:
            dict: 综合分析报告
        """
        request_id = set_request_id()
        logger.info(f"生成综合分析报告 [request_id: {request_id}]")

        try:
            result = analytics_service.generate_analysis_report()
            logger.info(f"综合分析报告生成完成")
            return result

        except Exception as e:
            logger.error(f"生成综合分析报告失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    # =====================================================================
    # 导出相关的MCP Tools
    # =====================================================================

    @server.tool()
    def export_overall_statistics(formats: Optional[List[str]] = None, base_filename: str = "statistics") -> dict:
        """
        导出整体统计数据

        将统计数据导出为JSON或CSV格式。

        Args:
            formats: 导出格式列表 ['json', 'csv']
            base_filename: 基础文件名

        Returns:
            dict: 导出结果
        """
        request_id = set_request_id()
        logger.info(f"导出整体统计 [request_id: {request_id}]")

        try:
            # 先获取统计数据
            data = analytics_service.get_overall_statistics()
            # 导出数据
            result = export_service.export_overall_statistics(
                data=data,
                formats=formats or ['json'],
                base_filename=base_filename
            )
            logger.info(f"整体统计导出完成")
            return result

        except Exception as e:
            logger.error(f"导出整体统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def export_category_statistics(formats: Optional[List[str]] = None, base_filename: str = "category_statistics") -> dict:
        """
        导出分类统计数据

        将分类统计数据导出为JSON或CSV格式。

        Args:
            formats: 导出格式列表
            base_filename: 基础文件名

        Returns:
            dict: 导出结果
        """
        request_id = set_request_id()
        logger.info(f"导出分类统计 [request_id: {request_id}]")

        try:
            data = analytics_service.get_category_statistics()
            result = export_service.export_category_statistics(
                data=data,
                formats=formats or ['json'],
                base_filename=base_filename
            )
            logger.info(f"分类统计导出完成")
            return result

        except Exception as e:
            logger.error(f"导出分类统计失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def export_quality_metrics(formats: Optional[List[str]] = None, base_filename: str = "quality_metrics") -> dict:
        """
        导出质量评估数据

        将质量评估数据导出为JSON或CSV格式。

        Args:
            formats: 导出格式列表
            base_filename: 基础文件名

        Returns:
            dict: 导出结果
        """
        request_id = set_request_id()
        logger.info(f"导出质量评估 [request_id: {request_id}]")

        try:
            data = analytics_service.get_quality_metrics()
            result = export_service.export_quality_metrics(
                data=data,
                formats=formats or ['json'],
                base_filename=base_filename
            )
            logger.info(f"质量评估导出完成")
            return result

        except Exception as e:
            logger.error(f"导出质量评估失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def export_time_series(formats: Optional[List[str]] = None, base_filename: str = "time_series") -> dict:
        """
        导出时间序列数据

        将时间序列分析数据导出为JSON或CSV格式。

        Args:
            formats: 导出格式列表
            base_filename: 基础文件名

        Returns:
            dict: 导出结果
        """
        request_id = set_request_id()
        logger.info(f"导出时间序列 [request_id: {request_id}]")

        try:
            data = analytics_service.get_time_series_analysis(days=30, period='day')
            result = export_service.export_time_series(
                data=data,
                formats=formats or ['json'],
                base_filename=base_filename
            )
            logger.info(f"时间序列导出完成")
            return result

        except Exception as e:
            logger.error(f"导出时间序列失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def list_export_files() -> dict:
        """
        列出导出的文件

        列出所有已导出的数据文件。

        Returns:
            dict: 文件列表
        """
        request_id = set_request_id()
        logger.info(f"列出导出文件 [request_id: {request_id}]")

        try:
            result = export_service.list_export_files()
            logger.info(f"导出文件列表获取完成: {result['total_files']}个文件")
            return result

        except Exception as e:
            logger.error(f"列出导出文件失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    @server.tool()
    def cleanup_old_exports(days: int = 30) -> dict:
        """
        清理旧的导出文件

        删除指定天数之前的导出文件。

        Args:
            days: 保留多少天以内的文件

        Returns:
            dict: 清理结果
        """
        request_id = set_request_id()
        logger.info(f"清理旧导出文件 [request_id: {request_id}]")

        try:
            result = export_service.cleanup_old_exports(days=days)
            logger.info(f"旧导出文件清理完成: 删除{result['deleted_count']}个文件")
            return result

        except Exception as e:
            logger.error(f"清理旧导出文件失败: {e}")
            return {
                "error": str(e),
                "timestamp": from_src_utils_import_get_current_timestamp(),
            }

    logger.info(f"[OK] 已注册 MCP Tools")


def from_src_utils_import_Optional_and_List():
    """导入Optional和List类型"""
    from typing import Optional, List
    return Optional, List


def from_src_utils_import_get_current_timestamp():
    """辅助函数：获取当前时间戳"""
    from src.utils.helpers import get_current_timestamp

    return get_current_timestamp()


def main():
    """
    主函数

    程序入口，负责初始化系统并启动 MCP Server。
    """
    global mcp_server, config, logger
    
    # 检测是否在 MCP 模式下运行（通过 STDIO 通信）
    # 如果 stdin 不是 tty，则可能是 MCP 客户端连接
    is_mcp_mode = not sys.stdin.isatty() if hasattr(sys.stdin, 'isatty') else False
    
    # 只在非-MCP 模式下显示启动信息
    if not is_mcp_mode:
        print("=" * 60)
        print("Questions MCP Server - 题目管理与检索系统")
        print(f"Version: {get_version()}")
        print("=" * 60)
        print()

    try:
        # 1. 初始化系统
        if not is_mcp_mode:
            print("阶段 1: 初始化系统...")
        config, logger = initialize_system()
        if not is_mcp_mode:
            print()

        # 2. 创建 MCP Server
        if not is_mcp_mode:
            print("阶段 2: 创建 MCP Server...")
        mcp_server = create_mcp_server(config, logger)
        if not is_mcp_mode:
            print("[OK] MCP Server 创建成功")
            print()

        # 3. 初始化服务
        if not is_mcp_mode:
            print("阶段3: 初始化服务...")
        db_manager, management_service, search_service, import_service, analytics_service, export_service = initialize_services(config, logger)
        if not is_mcp_mode:
            print("[OK] 服务初始化完成")
            print()

        # 4. 注册 Tools
        if not is_mcp_mode:
            print("阶段 4: 注册 MCP Tools...")
        register_tools(mcp_server, config, logger)
        if not is_mcp_mode:
            print("[OK] Tools 注册完成")
            print()

        # 5. 注册信号处理器（用于优雅关闭）
        def shutdown_handler(signum, frame):
            """
            优雅关闭处理器

            Args:
                signum: 信号编号
                frame: 当前栈帧
            """
            if logger:
                logger.info(f"收到关闭信号 ({signum})，正在优雅关闭...")
                logger.info("清理资源...")
                # 这里可以添加数据库连接关闭等清理逻辑
                logger.info("清理完成，服务已停止")
            else:
                print(f"收到关闭信号 ({signum})，正在关闭...", file=sys.stderr)

            sys.exit(0)

        import signal

        signal.signal(signal.SIGINT, shutdown_handler)
        signal.signal(signal.SIGTERM, shutdown_handler)

        # 6. 启动服务器
        if not is_mcp_mode:
            print("=" * 60)
            print("[OK] Questions MCP Server 启动成功!")
            print("=" * 60)
        logger.info("Questions MCP Server 启动成功")
        logger.info("服务器正在运行，等待客户端连接...")
        if not is_mcp_mode:
            print()
            print("服务器正在运行...")
            print("按 Ctrl+C 停止服务器")
            print()

        # 运行 MCP Server（这会阻塞直到服务器停止）
        # 在 MCP 模式下，隐藏 banner 避免干扰 STDIO 通信
        mcp_server.run(show_banner=not is_mcp_mode)

    except KeyboardInterrupt:
        if not is_mcp_mode:
            print("\n\n收到中断信号，正在关闭...")
        if logger:
            logger.info("收到中断信号，正在关闭服务器...")
    except Exception as e:
        if not is_mcp_mode:
            print(f"\n[ERROR] 启动失败: {e}")
        if logger:
            logger.error(f"服务器启动失败: {e}")
            import traceback
            logger.error(traceback.format_exc())
        sys.exit(1)
    finally:
        if logger:
            logger.info("Questions MCP Server 已停止")
        if not is_mcp_mode:
            print("\n服务器已停止")


if __name__ == "__main__":
    main()
