"""
基础设施环境检查报告
"""
import sys
import os
import platform
import importlib
from typing import Dict, List, Tuple
from loguru import logger


def check_python_version() -> Tuple[bool, str]:
    """检查 Python 版本"""
    version = sys.version
    major, minor = sys.version_info[:2]
    is_ok = major >= 3 and minor >= 8
    status = "✅" if is_ok else "❌"
    message = f"{status} Python 版本: {version}"
    if not is_ok:
        message += " (需要 Python 3.8+)"
    return is_ok, message


def check_dependencies() -> List[Tuple[bool, str]]:
    """检查依赖包"""
    dependencies = [
        ("numpy", "2.0.0"),
        ("pandas", "2.0.0"),
        ("sqlalchemy", "2.0.0"),
        ("loguru", "0.7.0"),
        ("pydantic", "2.0.0"),
        ("fastapi", "0.100.0"),
        ("uvicorn", "0.20.0"),
    ]
    
    results = []
    for package, min_version in dependencies:
        try:
            module = importlib.import_module(package)
            version = getattr(module, "__version__", "未知")
            is_ok = True  # 简化检查，实际应该比较版本
            status = "✅" if is_ok else "⚠️"
            results.append((is_ok, f"{status} {package}: {version}"))
        except ImportError:
            results.append((False, f"❌ {package}: 未安装"))
    
    return results


def check_directories() -> List[Tuple[bool, str]]:
    """检查目录结构"""
    dirs = [
        "vnpy_project/logs",
        "vnpy_project/data",
        "vnpy_project/strategies",
        "vnpy_project/backup",
        "logs",
    ]
    
    results = []
    for dir_path in dirs:
        exists = os.path.exists(dir_path) and os.path.isdir(dir_path)
        status = "✅" if exists else "❌"
        results.append((exists, f"{status} 目录: {dir_path}"))
    
    return results


def check_virtual_environment() -> Tuple[bool, str]:
    """检查虚拟环境"""
    in_venv = hasattr(sys, 'real_prefix') or (
        hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
    )
    status = "✅" if in_venv else "⚠️"
    message = f"{status} 虚拟环境: {'已激活' if in_venv else '未激活 (建议使用虚拟环境)'}"
    return in_venv, message


def check_system_info() -> Dict[str, str]:
    """获取系统信息"""
    return {
        "系统": platform.system(),
        "系统版本": platform.version(),
        "架构": platform.machine(),
        "处理器": platform.processor(),
    }


def generate_report():
    """生成环境检查报告"""
    logger.info("=" * 60)
    logger.info("      量化交易系统 - 基础设施环境检查报告")
    logger.info("=" * 60)
    
    # 系统信息
    logger.info("\n📊 系统信息:")
    system_info = check_system_info()
    for key, value in system_info.items():
        logger.info(f"   {key}: {value}")
    
    # 虚拟环境
    logger.info("\n🔧 环境状态:")
    _, venv_msg = check_virtual_environment()
    logger.info(f"   {venv_msg}")
    
    # Python 版本
    _, py_msg = check_python_version()
    logger.info(f"   {py_msg}")
    
    # 依赖检查
    logger.info("\n📦 依赖包检查:")
    dep_results = check_dependencies()
    for _, msg in dep_results:
        logger.info(f"   {msg}")
    
    # 目录检查
    logger.info("\n📂 目录结构检查:")
    dir_results = check_directories()
    for _, msg in dir_results:
        logger.info(f"   {msg}")
    
    # 汇总
    all_checks = dep_results + dir_results + [check_python_version()]
    passed = sum(1 for ok, _ in all_checks if ok)
    total = len(all_checks)
    
    logger.info("\n" + "=" * 60)
    logger.info(f"📈 检查结果: {passed}/{total} 项通过")
    if passed == total:
        logger.info("🎉 恭喜！所有检查项都通过了，环境准备就绪！")
    else:
        logger.warning("⚠️  部分检查项未通过，请根据提示修复")
    logger.info("=" * 60)


if __name__ == "__main__":
    # 配置日志
    logger.remove()
    logger.add(sys.stderr, format="<level>{message}</level>")
    
    generate_report()
