#!/usr/bin/env python3
"""
项目结构验证脚本
验证重构后的项目结构是否符合要求
"""
import os
import sys
from pathlib import Path

# 项目根目录
PROJECT_ROOT = Path(__file__).parent.parent

# 期望的目录结构
EXPECTED_STRUCTURE = {
    "src/app/server": ["__init__.py", "app.py"],
    "src/app/logger": ["__init__.py", "loggering.py"],
    "src/app/base": [
        "__init__.py",
        "async_mysql_connection.py",
        "async_redis_connection.py",
        "milvus_connection.py"
    ],
    "src/app/core": ["__init__.py", "exceptions.py"],
    "src/app/models": [
        "__init__.py",
        "base.py",
        "user.py",
        "app.py",
        "token.py",
        "log.py",
        "knowledge_base.py"
    ],
    "src/app/schemas": [
        "__init__.py",
        "base.py",
        "user.py",
        "auth.py"
    ],
    "src/app/utils": ["__init__.py", "security.py"],
    "src/app/config": [
        "__init__.py",
        "settings.py",
        "database.py",
        "simple_settings.py"
    ],
    "src/app/system": ["__init__.py"],
    "src/app/system/models": ["__init__.py"],
    "src/app/system/schemas": ["__init__.py"],
    "src/app/oauth": ["__init__.py"],
    "src/app/oauth/models": ["__init__.py"],
    "src/app/oauth/schemas": ["__init__.py"],
    "src/app/sample": ["__init__.py"],
    "src/app/sample/models": ["__init__.py"],
    "src/app/sample/schemas": ["__init__.py"],
    "src/views": [
        "__init__.py",
        "system_view.py",
        "oauth_view.py",
        "sample_view.py"
    ],
}

# 期望的根目录文件
EXPECTED_ROOT_FILES = [
    "run_server.py",
    "full_server.py",
    "README.md",
    "REFACTOR_README.md",
    "MIGRATION_GUIDE.md",
    ".env.example",
    ".gitignore"
]


def check_directory_structure():
    """检查目录结构"""
    print("=" * 60)
    print("检查项目目录结构")
    print("=" * 60)
    
    all_passed = True
    
    for directory, files in EXPECTED_STRUCTURE.items():
        dir_path = PROJECT_ROOT / directory
        
        # 检查目录是否存在
        if not dir_path.exists():
            print(f"❌ 目录不存在: {directory}")
            all_passed = False
            continue
        
        print(f"✅ 目录存在: {directory}")
        
        # 检查文件是否存在
        for file in files:
            file_path = dir_path / file
            if not file_path.exists():
                print(f"  ❌ 文件缺失: {directory}/{file}")
                all_passed = False
            else:
                print(f"  ✅ 文件存在: {file}")
    
    return all_passed


def check_root_files():
    """检查根目录文件"""
    print("\n" + "=" * 60)
    print("检查根目录文件")
    print("=" * 60)
    
    all_passed = True
    
    for file in EXPECTED_ROOT_FILES:
        file_path = PROJECT_ROOT / file
        if not file_path.exists():
            print(f"⚠️  文件缺失: {file}")
            if file not in [".env.example"]:  # 某些文件可选
                all_passed = False
        else:
            print(f"✅ 文件存在: {file}")
    
    return all_passed


def check_imports():
    """检查关键模块是否可以导入"""
    print("\n" + "=" * 60)
    print("检查模块导入")
    print("=" * 60)
    
    # 添加 src 到路径
    sys.path.insert(0, str(PROJECT_ROOT / "src"))
    
    modules_to_check = [
        "app.server.app",
        "app.logger.loggering",
        "app.base",
        "app.core.exceptions",
        "app.system",
        "app.oauth",
        "app.sample",
        "views.system_view",
        "views.oauth_view",
        "views.sample_view",
    ]
    
    all_passed = True
    
    for module in modules_to_check:
        try:
            __import__(module)
            print(f"✅ 模块可导入: {module}")
        except ImportError as e:
            print(f"❌ 模块导入失败: {module}")
            print(f"   错误: {e}")
            all_passed = False
        except Exception as e:
            print(f"⚠️  模块导入警告: {module}")
            print(f"   错误: {e}")
    
    return all_passed


def check_module_structure():
    """检查模块结构是否符合要求"""
    print("\n" + "=" * 60)
    print("检查模块结构")
    print("=" * 60)
    
    modules = ["system", "oauth", "sample"]
    all_passed = True
    
    for module in modules:
        module_path = PROJECT_ROOT / "src" / "app" / module
        
        # 检查是否有 models 和 schemas 子目录
        models_path = module_path / "models"
        schemas_path = module_path / "schemas"
        
        if models_path.exists() and (models_path / "__init__.py").exists():
            print(f"✅ {module}/models 结构正确")
        else:
            print(f"❌ {module}/models 结构不正确")
            all_passed = False
        
        if schemas_path.exists() and (schemas_path / "__init__.py").exists():
            print(f"✅ {module}/schemas 结构正确")
        else:
            print(f"❌ {module}/schemas 结构不正确")
            all_passed = False
    
    return all_passed


def main():
    """主函数"""
    print("\n" + "=" * 60)
    print("LQAdminPlatform 项目结构验证")
    print("=" * 60)
    print(f"项目根目录: {PROJECT_ROOT}")
    print("=" * 60 + "\n")
    
    results = []
    
    # 执行各项检查
    results.append(("目录结构", check_directory_structure()))
    results.append(("根目录文件", check_root_files()))
    results.append(("模块结构", check_module_structure()))
    results.append(("模块导入", check_imports()))
    
    # 输出总结
    print("\n" + "=" * 60)
    print("验证结果总结")
    print("=" * 60)
    
    all_passed = True
    for name, passed in results:
        status = "✅ 通过" if passed else "❌ 失败"
        print(f"{name}: {status}")
        if not passed:
            all_passed = False
    
    print("=" * 60)
    
    if all_passed:
        print("\n🎉 所有检查通过！项目结构符合要求。")
        return 0
    else:
        print("\n⚠️  部分检查未通过，请查看上面的详细信息。")
        return 1


if __name__ == "__main__":
    sys.exit(main())
