#!/usr/bin/env bash

set -euo pipefail

mode="${1:-positive}"
log_dir="${2:-test/test_result/lab2_sema_logs}"

checker="./build-sema/sema_check"
if [[ ! -x "$checker" ]]; then
  echo "未找到语义测试驱动: $checker" >&2
  echo "请先准备 build-sema/sema_check。" >&2
  exit 1
fi

mkdir -p "$log_dir"

case_files=()
expected_prefix=""

case "$mode" in
  positive)
    expected_prefix="OK"
    case_files=(
      "test/test_case/functional/simple_add.sy"
      "test/test_case/functional/09_func_defn.sy"
      "test/test_case/functional/25_scope3.sy"
      "test/test_case/functional/29_break.sy"
      "test/test_case/functional/05_arr_defn4.sy"
      "test/test_case/functional/95_float.sy"
    )
    ;;
  negative)
    expected_prefix="ERR"
    case_files=(
      "test/test_case/sema_negative/undef.sy"
      "test/test_case/sema_negative/break.sy"
      "test/test_case/sema_negative/ret.sy"
      "test/test_case/sema_negative/call.sy"
    )
    ;;
  *)
    echo "用法: $0 [positive|negative] [log_dir]" >&2
    exit 1
    ;;
esac

if [[ ${#case_files[@]} -eq 0 ]]; then
  echo "没有可执行的测试用例" >&2
  exit 1
fi

for f in "${case_files[@]}"; do
  if [[ ! -f "$f" ]]; then
    echo "测试文件不存在: $f" >&2
    exit 1
  fi
done

all_ok=true
for f in "${case_files[@]}"; do
  base="$(basename "${f%.sy}")"
  log_file="$log_dir/${base}.sema.log"
  echo "TEST $f -> $log_file"
  set +e
  "$checker" "$f" >"$log_file" 2>&1
  status=$?
  set -e

  if ! grep -q "^${expected_prefix} $f$" "$log_file"; then
    echo "FAIL $f (see $log_file)" >&2
    all_ok=false
    continue
  fi

  if [[ "$mode" == "positive" && $status -ne 0 ]]; then
    echo "FAIL $f (expected success, see $log_file)" >&2
    all_ok=false
    continue
  fi

  if [[ "$mode" == "negative" && $status -eq 0 ]]; then
    echo "FAIL $f (expected semantic error, see $log_file)" >&2
    all_ok=false
    continue
  fi
done

if [[ "$all_ok" != true ]]; then
  exit 1
fi

echo "ALL_SEMA_${mode^^}_OK (${#case_files[@]} cases) logs: $log_dir"
