#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CSV 数据验证脚本
用于检查 CSV 文件的列数是否正确，防止数据错位

Usage: python validate_csv.py [filepath]
"""

import csv
import sys
from pathlib import Path

# 各 domain 的预期列数
EXPECTED_COLS = {
    "tke-components.csv": 12,  # Category, Component, Keywords, Class Names, Usage, Use Case, Context, Minimal Example, Full Example, Do, Don't, Severity
    "tke-forms.csv": 11,  # Category, Element, Keywords, Layout, Use Case, Context, Minimal Example, Full Example, Best Practice, Common Mistake, Severity
    "tke-tables.csv": 11,  # Category, Type, Keywords, Class Names, Use Case, Context, Minimal Example, Full Example, Configuration, Best Practice, Severity
    "tke-layouts.csv": 8,  # Pattern, Keywords, Structure, Use Case, Context, Minimal Example, Full Example, Notes
    "tke-icons.csv": 7,  # Icon Name, Icon Class, Category, Keywords, Usage, Example, Notes
    "tke-practices.csv": 9,  # Category, Issue, Keywords, Description, Do, Don't, Code Good, Code Bad, Severity
    "tke-patterns.csv": 9,  # Pattern, Components, Keywords, Structure, Use Case, Context, Minimal Example, Full Example, Notes
    "tke-colors.csv": None,  # 需要根据实际文件确定
    "tke-typography.csv": None,  # 需要根据实际文件确定
    "tke-responsive.csv": None,  # 需要根据实际文件确定
}


def validate_csv(filepath, expected_cols=None):
    """验证 CSV 文件的列数"""
    filepath = Path(filepath)
    
    if not filepath.exists():
        print(f"❌ 文件不存在: {filepath}")
        return False
    
    filename = filepath.name
    
    # 如果没有指定预期列数，尝试从配置中获取
    if expected_cols is None:
        expected_cols = EXPECTED_COLS.get(filename)
        if expected_cols is None:
            print(f"⚠️  未找到 {filename} 的预期列数配置，将自动检测")
    
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            header = next(reader)
            header_cols = len(header)
            
            print(f"📄 文件: {filepath.name}")
            print(f"📊 表头列数: {header_cols}")
            print(f"📋 表头: {', '.join(header[:5])}{'...' if len(header) > 5 else ''}")
            print()
            
            # 如果未指定预期列数，使用表头列数
            if expected_cols is None:
                expected_cols = header_cols
                print(f"ℹ️  使用表头列数作为预期值: {expected_cols}")
            
            errors = []
            warnings = []
            
            for line_num, row in enumerate(reader, start=2):
                actual_cols = len(row)
                
                if actual_cols != expected_cols:
                    error_msg = f"❌ 第 {line_num} 行: 预期 {expected_cols} 列，实际 {actual_cols} 列"
                    errors.append((line_num, actual_cols, row))
                    print(error_msg)
                    
                    # 显示前几列的内容，帮助定位问题
                    preview = row[:5] if len(row) >= 5 else row
                    print(f"   前几列: {preview}")
                    print()
            
            # 总结
            print("=" * 70)
            if errors:
                print(f"❌ 发现 {len(errors)} 个错误")
                print(f"   错误行号: {', '.join(str(e[0]) for e in errors)}")
                return False
            else:
                print(f"✅ 验证通过！所有 {line_num - 1} 行数据列数正确")
                return True
                
    except Exception as e:
        print(f"❌ 读取文件时出错: {e}")
        return False


def validate_all():
    """验证所有 CSV 文件"""
    data_dir = Path(__file__).parent.parent / "data"
    
    print("🔍 开始验证所有 CSV 文件...")
    print("=" * 70)
    print()
    
    all_passed = True
    
    for filename, expected_cols in EXPECTED_COLS.items():
        if expected_cols is None:
            continue
            
        filepath = data_dir / filename
        if filepath.exists():
            print(f"\n{'=' * 70}")
            result = validate_csv(filepath, expected_cols)
            if not result:
                all_passed = False
        else:
            print(f"⚠️  文件不存在: {filename}")
    
    print()
    print("=" * 70)
    if all_passed:
        print("✅ 所有文件验证通过！")
    else:
        print("❌ 部分文件验证失败，请检查上述错误")
    
    return all_passed


if __name__ == "__main__":
    if len(sys.argv) > 1:
        # 验证指定文件
        filepath = sys.argv[1]
        expected_cols = int(sys.argv[2]) if len(sys.argv) > 2 else None
        validate_csv(filepath, expected_cols)
    else:
        # 验证所有文件
        validate_all()
