#!/usr/bin/env bash

set -euo pipefail

case_dir="${1:-test/test_case}"
log_dir="${2:-test/test_result/lab1_parse_logs}"

if [[ ! -d "$case_dir" ]]; then
  echo "测试目录不存在: $case_dir" >&2
  exit 1
fi

compiler="./build/bin/compiler"
if [[ ! -x "$compiler" ]]; then
  echo "未找到编译器: $compiler ，请先构建 parse-only 版本。" >&2
  exit 1
fi

mkdir -p "$log_dir"

mapfile -t cases < <(find "$case_dir" -name '*.sy' | sort)
if [[ ${#cases[@]} -eq 0 ]]; then
  echo "未找到任何 .sy 测试文件: $case_dir" >&2
  exit 1
fi

for f in "${cases[@]}"; do
  rel="${f#$case_dir/}"
  safe_name="${rel//\//__}"
  log_file="$log_dir/${safe_name%.sy}.parse.log"
  echo "TEST $f -> $log_file"
  if ! "$compiler" --emit-parse-tree "$f" >"$log_file" 2>&1; then
    echo "FAIL $f (see $log_file)" >&2
    exit 1
  fi
done

echo "ALL_PARSE_OK (${#cases[@]} cases) logs: $log_dir"
