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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

make -C "$ROOT" -s >/dev/null

BIN="$ROOT/flowlog"

fail() {
  echo "fail: $1" >&2
  exit 1
}

tmpdir="$(mktemp -d -t flowlog_orpar_nesting_wam.XXXXXX)"
cleanup() {
  rm -rf "$tmpdir" >/dev/null 2>&1 || true
}
trap cleanup EXIT

log="$tmpdir/orpar.log"

# Use a small deterministic goal that triggers nested select/3 OR-par:
# - outer select_: 9 alternatives (spawns OR-par)
# - inner select_: 8 alternatives within an OR-par chunk (requires nesting)
out="$(
  FLOWLOG_DEBUG_ORPAR=all \
  FLOWLOG_DEBUG_ORPAR_LOG="$log" \
  "$BIN" --threads 10 --engine wam --parallel-profile fast -g \
    'set_prolog_flag(flowlog_parallel_or_nesting, 1), countall((select_(X,[1,2,3,4,5,6,7,8,9],R), select_(Y,R,_)), C).' \
    | tr -d '\r'
)"

out="${out%$'\n'}"
if [[ "$out" != "C = 72" ]]; then
  echo "--- expected ---" >&2
  echo "C = 72" >&2
  echo "--- got ---" >&2
  printf '%s\n' "$out" >&2
  fail "orpar_nesting_output_wam"
fi

starts="$(grep -c '^flowlog: ORPAR start' "$log" 2>/dev/null || true)"
if [[ "${starts:-0}" -lt 2 ]]; then
  echo "--- expected ORPAR starts >= 2 ---" >&2
  echo "--- got log ---" >&2
  cat "$log" >&2 || true
  fail "orpar_nesting_missing_nested_start_wam"
fi

echo "ok"
