#!/usr/bin/env python3
"""
检查 E2E 测试文件中的断言使用情况

使用方法:
    python scripts/check-test-assertions.py [测试目录路径]
    
示例:
    # 使用默认路径
    python scripts/check-test-assertions.py
    
    # 指定路径
    python scripts/check-test-assertions.py testing/e2e/legacy/specs/organization
"""

import re
import sys
import os
from pathlib import Path

def analyze_test_file(file_path):
    """分析单个测试文件"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 找到所有 test() 定义
    test_pattern = r"test(?:\.only)?\s*\(['\"](.+?)['\"].*?async.*?\{(.*?)(?=\n\s*test\(|\n\s*test\.|\n\}\);)"
    tests = re.finditer(test_pattern, content, re.DOTALL)
    
    results = []
    for match in tests:
        test_name = match.group(1)
        test_body = match.group(2)
        
        # 检查是否有断言
        has_expect = 'expect(' in test_body
        has_assertion = has_expect or 'assert' in test_body.lower()
        
        # 检查是否只有 console.log
        has_console_only = 'console.log' in test_body and not has_assertion
        
        # 检查是否有 test.skip
        has_skip = 'test.skip' in test_body
        
        results.append({
            'name': test_name,
            'has_assertion': has_assertion,
            'has_expect': has_expect,
            'has_console_only': has_console_only,
            'has_skip': has_skip,
            'body_length': len(test_body)
        })
    
    return results

def main():
    # 支持命令行参数或使用相对路径
    if len(sys.argv) > 1:
        base_path = Path(sys.argv[1])
    else:
        # 使用相对于脚本的路径
        script_dir = Path(os.path.dirname(os.path.abspath(__file__)))
        base_path = script_dir.parent / 'testing' / 'e2e' / 'legacy' / 'specs' / 'organization'
    
    if not base_path.exists():
        print(f"❌ 错误：路径不存在: {base_path}")
        print(f"\n使用方法:")
        print(f"  python {sys.argv[0]} [测试目录路径]")
        sys.exit(1)
    
    test_files = list(base_path.glob('*.spec.ts'))
    
    if not test_files:
        print(f"❌ 错误：未找到测试文件 (*.spec.ts) 在: {base_path}")
        sys.exit(1)
    
    print("=" * 80)
    print("E2E 测试断言检查报告")
    print(f"检查目录: {base_path}")
    print("=" * 80)
    print()
    
    total_tests = 0
    tests_without_assertions = 0
    
    for test_file in sorted(test_files):
        print(f"\n📄 {test_file.name}")
        print("-" * 80)
        
        results = analyze_test_file(test_file)
        total_tests += len(results)
        
        # 统计
        no_assertion_tests = [r for r in results if not r['has_assertion']]
        tests_without_assertions += len(no_assertion_tests)
        
        if no_assertion_tests:
            print(f"⚠️  发现 {len(no_assertion_tests)} 个没有断言的测试:")
            for test in no_assertion_tests:
                print(f"  - {test['name']}")
                if test['has_console_only']:
                    print(f"    (只有 console.log，没有断言)")
        else:
            print(f"✅ 所有 {len(results)} 个测试都有断言")
    
    print("\n" + "=" * 80)
    print(f"总结: {total_tests} 个测试, {tests_without_assertions} 个缺少断言")
    print("=" * 80)

if __name__ == '__main__':
    main()
