#!/usr/bin/env bash
# Golden-seed regression. For each seed in goldens.txt, regenerate the map and
# compare (sha256 of map + summary line). Non-zero exit on any mismatch.
set -u
cd "$(dirname "$0")/.."
BIN=./bin/genesis
GOLDENS=test/goldens.txt

if [[ ! -x "$BIN" ]]; then
    echo "error: $BIN not built. Run 'make' first." >&2
    exit 2
fi
if [[ ! -f "$GOLDENS" ]]; then
    echo "error: $GOLDENS missing. Run test/update_goldens.sh to create." >&2
    exit 2
fi

fail=0
total=0
while IFS='|' read -r key expected_hash expected_summary; do
    [[ -z "${key:-}" || "${key:0:1}" == "#" ]] && continue
    seed="${key%:*}"
    depth="${key#*:}"
    [[ "$depth" == "$seed" ]] && depth=1
    total=$((total + 1))
    actual_hash=$("$BIN" --seed "$seed" --depth "$depth" 2>/dev/null | sha256sum | awk '{print $1}')
    actual_summary=$("$BIN" --seed "$seed" --depth "$depth" --quiet 2>&1 >/dev/null)
    if [[ "$actual_hash" != "$expected_hash" ]]; then
        echo "FAIL $key  hash mismatch"
        echo "  expected: $expected_hash"
        echo "  actual:   $actual_hash"
        fail=$((fail + 1))
        continue
    fi
    if [[ "$actual_summary" != "$expected_summary" ]]; then
        echo "FAIL $key  summary mismatch"
        echo "  expected: $expected_summary"
        echo "  actual:   $actual_summary"
        fail=$((fail + 1))
        continue
    fi
    echo "PASS $key"
done < "$GOLDENS"

echo "----"
echo "$((total - fail))/$total passed"

# Invariant sweep: run a wider stress check to catch regressions the goldens
# might miss.
echo "---- stress (connectivity invariant, 1000 seeds) ----"
"$BIN" --stress 1000 2>&1 | tail -1

exit $fail
