#!/usr/bin/env bash
set -euo pipefail

ROOT=$(cd "$(dirname "$0")/.." && pwd)
FUNC_DIR="$ROOT/test/test_case/functional"
OUT_BASE="$ROOT/test/test_result/function/ir"
LOG_DIR="$ROOT/test/test_result/function/ir_logs"
VERIFY="$ROOT/scripts/verify_ir.sh"

mkdir -p "$OUT_BASE"
mkdir -p "$LOG_DIR"

if [ ! -x "$VERIFY" ]; then
  echo "verify script not executable, trying to run with bash: $VERIFY"
fi

files=("$FUNC_DIR"/*.sy)
if [ ${#files[@]} -eq 0 ]; then
  echo "No .sy files found in $FUNC_DIR" >&2
  exit 1
fi

total=0
pass=0
fail=0
failed_list=()

for f in "${files[@]}"; do
  ((total++))
  name=$(basename "$f")
  echo "=== Test: $name ==="
  log="$LOG_DIR/${name%.sy}.log"
  set +e
  bash "$VERIFY" "$f" "$OUT_BASE" --run >"$log" 2>&1
  rc=$?
  set -e
  if [ $rc -eq 0 ]; then
    echo "PASS: $name"
    ((pass++))
  else
    echo "FAIL: $name (log: $log)"
    failed_list+=("$name")
    ((fail++))
  fi
done

echo
echo "Summary: total=$total pass=$pass fail=$fail"
if [ $fail -ne 0 ]; then
  echo "Failed tests:"; for t in "${failed_list[@]}"; do echo " - $t"; done
  echo "Tail of failure logs (last 200 lines each):"
  for t in "${failed_list[@]}"; do
    logfile="$LOG_DIR/${t%.sy}.log"
    echo
    echo "--- $t ---"
    tail -n 200 "$logfile" || true
  done
fi

exit $fail
