#!/bin/bash

# 项目根目录
PROJECT_ROOT=$(cd "$(dirname $0)";pwd)/..

# 输出目录
TEST_RESULT_DIR="$PROJECT_ROOT/test/test_result"

# 编译g4文件生成C++代码
echo "=== 编译ANTLR grammar文件 ==="
java -jar "$PROJECT_ROOT/third_party/antlr-4.13.2-complete.jar" \
    -Dlanguage=Cpp \
    -visitor \
    -no-listener \
    -Xexact-output-dir \
    -o "$PROJECT_ROOT/build/generated/antlr4" \
    "$PROJECT_ROOT/src/antlr4/SysY.g4"

if [ $? -ne 0 ]; then
    echo "错误：ANTLR编译失败"
    exit 1
fi

# 构建项目
echo "=== 构建项目 ==="
cmake -S "$PROJECT_ROOT" -B "$PROJECT_ROOT/build" \
    -DCMAKE_BUILD_TYPE=Release \
    -DCOMPILER_PARSE_ONLY=ON

if [ $? -ne 0 ]; then
    echo "错误：CMake配置失败"
    exit 1
fi

cmake --build "$PROJECT_ROOT/build" -j "$(nproc)"

if [ $? -ne 0 ]; then
    echo "错误：项目构建失败"
    exit 1
fi

# 遍历测试用例
echo "=== 运行测试用例 ==="
find "$PROJECT_ROOT/test/test_case" -name "*.sy" | while read -r test_file; do
    # 计算相对路径
    relative_path=$(realpath --relative-to="$PROJECT_ROOT/test/test_case" "$test_file")
    # 计算输出文件路径
    output_file="$TEST_RESULT_DIR/$relative_path.tree"
    # 创建输出目录
    mkdir -p "$(dirname "$output_file")"
    
    # 运行编译器
    echo "处理：$relative_path"
    "$PROJECT_ROOT/build/bin/compiler" --emit-parse-tree "$test_file" > "$output_file"
    
    if [ $? -ne 0 ]; then
        echo "警告：处理 $relative_path 时出错"
    fi
done

echo "=== 测试完成 ==="
echo "结果保存在：$TEST_RESULT_DIR"