#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DataOps Platform 项目状态检查脚本
用于诊断Cursor项目识别问题
"""

import os
import sys
import json
from pathlib import Path

def check_python_environment():
    """检查Python环境"""
    print("=" * 60)
    print("Python环境检查")
    print("=" * 60)
    
    print(f"Python版本: {sys.version}")
    print(f"Python路径: {sys.executable}")
    print(f"Python可执行文件: {os.path.exists(sys.executable)}")
    
    # 检查虚拟环境
    in_venv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
    print(f"是否在虚拟环境中: {in_venv}")
    
    if in_venv:
        print(f"虚拟环境路径: {sys.prefix}")
    
    print()

def check_project_structure():
    """检查项目结构"""
    print("=" * 60)
    print("项目结构检查")
    print("=" * 60)
    
    project_root = Path(__file__).parent
    print(f"项目根目录: {project_root}")
    
    # 关键文件检查
    key_files = [
        "pyproject.toml",
        "setup.py", 
        "requirements.txt",
        "application.py",
        ".cursorrules",
        ".gitignore",
        "README.md"
    ]
    
    for file_name in key_files:
        file_path = project_root / file_name
        exists = file_path.exists()
        print(f"{file_name}: {'✓' if exists else '✗'} ({'存在' if exists else '缺失'})")
    
    print()
    
    # 目录结构检查
    key_dirs = [
        "app",
        "app/api",
        "app/config", 
        "app/models",
        "app/services",
        "database",
        "docs",
        "tests",
        ".vscode"
    ]
    
    for dir_name in key_dirs:
        dir_path = project_root / dir_name
        exists = dir_path.exists()
        print(f"{dir_name}/: {'✓' if exists else '✗'} ({'存在' if exists else '缺失'})")
    
    print()

def check_cursor_compatibility():
    """检查Cursor兼容性"""
    print("=" * 60)
    print("Cursor兼容性检查")
    print("=" * 60)
    
    project_root = Path(__file__).parent
    
    # 检查pyproject.toml
    pyproject_path = project_root / "pyproject.toml"
    if pyproject_path.exists():
        print("✓ pyproject.toml 存在 - 现代Python项目标准")
        try:
            with open(pyproject_path, 'r', encoding='utf-8') as f:
                content = f.read()
                if "build-system" in content and "project" in content:
                    print("  ✓ 文件格式正确")
                else:
                    print("  ✗ 文件格式可能有问题")
        except Exception as e:
            print(f"  ✗ 读取文件失败: {e}")
    else:
        print("✗ pyproject.toml 缺失 - 可能导致项目识别问题")
    
    # 检查setup.py
    setup_path = project_root / "setup.py"
    if setup_path.exists():
        print("✓ setup.py 存在 - 提供向后兼容性")
    else:
        print("✗ setup.py 缺失 - 可能影响旧版本工具识别")
    
    # 检查.cursorrules
    cursorrules_path = project_root / ".cursorrules"
    if cursorrules_path.exists():
        print("✓ .cursorrules 存在 - Cursor编辑器配置")
    else:
        print("✗ .cursorrules 缺失 - Cursor编辑器配置不完整")
    
    # 检查.vscode配置
    vscode_dir = project_root / ".vscode"
    if vscode_dir.exists():
        print("✓ .vscode 目录存在 - 工作区配置")
        settings_path = vscode_dir / "settings.json"
        if settings_path.exists():
            print("  ✓ settings.json 存在")
        else:
            print("  ✗ settings.json 缺失")
        
        launch_path = vscode_dir / "launch.json"
        if launch_path.exists():
            print("  ✓ launch.json 存在")
        else:
            print("  ✗ launch.json 缺失")
    else:
        print("✗ .vscode 目录缺失 - 工作区配置不完整")
    
    print()

def check_dependencies():
    """检查依赖配置"""
    print("=" * 60)
    print("依赖配置检查")
    print("=" * 60)
    
    project_root = Path(__file__).parent
    requirements_path = project_root / "requirements.txt"
    
    if requirements_path.exists():
        print("✓ requirements.txt 存在")
        try:
            with open(requirements_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                flask_deps = [line for line in lines if 'flask' in line.lower()]
                if flask_deps:
                    print(f"  ✓ 包含Flask依赖: {len(flask_deps)} 个")
                else:
                    print("  ✗ 缺少Flask依赖")
        except Exception as e:
            print(f"  ✗ 读取文件失败: {e}")
    else:
        print("✗ requirements.txt 缺失")
    
    # 检查虚拟环境
    venv_path = project_root / "venv"
    if venv_path.exists():
        print("✓ 虚拟环境存在")
        python_exe = venv_path / "Scripts" / "python.exe" if os.name == 'nt' else venv_path / "bin" / "python"
        if python_exe.exists():
            print("  ✓ 虚拟环境Python可执行文件存在")
        else:
            print("  ✗ 虚拟环境Python可执行文件缺失")
    else:
        print("✗ 虚拟环境不存在 - 需要创建")
    
    print()

def generate_cursor_workspace():
    """生成Cursor工作区文件"""
    print("=" * 60)
    print("生成Cursor工作区文件")
    print("=" * 60)
    
    project_root = Path(__file__).parent
    workspace_path = project_root / "DataOps-platform.code-workspace"
    
    workspace_config = {
        "folders": [
            {
                "name": "DataOps Platform",
                "path": "."
            }
        ],
        "settings": {
            "python.defaultInterpreterPath": "./venv/Scripts/python.exe",
            "python.terminal.activateEnvironment": True,
            "python.linting.enabled": True,
            "python.linting.flake8Enabled": True,
            "python.formatting.provider": "black",
            "python.testing.pytestEnabled": True,
            "python.testing.pytestArgs": ["tests"],
            "files.exclude": {
                "**/__pycache__": True,
                "**/*.pyc": True,
                "**/venv": True,
                "**/.git": True
            },
            "search.exclude": {
                "**/venv": True,
                "**/__pycache__": True,
                "**/*.pyc": True
            }
        },
        "extensions": {
            "recommendations": [
                "ms-python.python",
                "ms-python.flake8",
                "ms-python.black-formatter",
                "ms-python.mypy-type-checker",
                "ms-python.pytest-adapter"
            ]
        }
    }
    
    try:
        with open(workspace_path, 'w', encoding='utf-8') as f:
            json.dump(workspace_config, f, indent=2, ensure_ascii=False)
        print(f"✓ 工作区文件已生成: {workspace_path}")
        print("  现在可以使用 'File > Open Workspace from File...' 打开此文件")
    except Exception as e:
        print(f"✗ 生成工作区文件失败: {e}")
    
    print()

def main():
    """主函数"""
    print("DataOps Platform 项目状态检查工具")
    print("用于诊断Cursor项目识别问题")
    print()
    
    check_python_environment()
    check_project_structure()
    check_cursor_compatibility()
    check_dependencies()
    generate_cursor_workspace()
    
    print("=" * 60)
    print("检查完成！")
    print("=" * 60)
    print()
    print("如果发现问题，请按照以下步骤操作：")
    print("1. 运行 run_project.bat 创建虚拟环境并安装依赖")
    print("2. 使用 'File > Open Workspace from File...' 打开 .code-workspace 文件")
    print("3. 或者直接使用 'File > Open Folder...' 打开项目目录")
    print("4. 确保Cursor使用正确的Python解释器（虚拟环境中的Python）")
    print()
    print("如果问题仍然存在，请检查：")
    print("- Python版本是否为3.8+")
    print("- 是否有足够的磁盘空间")
    print("- 防火墙设置是否阻止了端口访问")
    print("- 系统环境变量是否正确设置")

if __name__ == "__main__":
    main()
