#!/bin/bash

echo "======================================"
echo "Lab1 语法树构建 - 完整批量测试"
echo "时间: $(date)"
echo "======================================"

PASS=0
FAIL=0
FAILED_FILES=()
TOTAL=0

# 递归查找所有 .sy 文件
while IFS= read -r file; do
    ((TOTAL++))
    filename=$(basename "$file")
    rel_path=${file#test/test_case/}
    
    echo -n "[$TOTAL] 测试 $rel_path ... "
    
    # 运行编译器检查解析是否成功
    if ./build/bin/compiler --emit-parse-tree "$file" > /dev/null 2>&1; then
        echo "✓ 通过"
        ((PASS++))
    else
        echo "✗ 失败"
        ((FAIL++))
        FAILED_FILES+=("$rel_path")
        
        # 输出错误信息到临时文件以便调试
        echo "    错误详情:" >&2
        ./build/bin/compiler --emit-parse-tree "$file" 2>&1 | head -5 | sed 's/^/      /' >&2
    fi
done < <(find test/test_case -name "*.sy" -type f | sort)

echo "======================================"
echo "测试结果统计"
echo "======================================"
echo "总计: $TOTAL"
echo "通过: $PASS"
echo "失败: $FAIL"
echo "成功率: $(awk "BEGIN {printf \"%.2f\", ($PASS/$TOTAL)*100}")%"
echo "======================================"

if [ $FAIL -gt 0 ]; then
    echo ""
    echo "失败的测试用例 ($FAIL 个):"
    for f in "${FAILED_FILES[@]}"; do
        echo "  ✗ $f"
    done
    exit 1
fi

echo ""
echo "🎉 所有测试用例通过！"
exit 0
