#!/bin/sh
# retroDE_ps2 — Ch340 host gate. No board, no real dump needed (uses content-clean synthetic
# fixtures). Proves: (1) byte-exact container/GIF parse, (2) census classifies supported vs
# unsupported, (3) the translator emits a ps2_feeder scene for supported input that the Ch339
# encoder accepts, and (4) fail-closed on unsupported input.
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
fail=0

echo "== 1. byte-exact parser test =="
python3 "$HERE/test_gs_parse.py" >/tmp/_gp.txt 2>&1
grep -q "RESULT: PASS" /tmp/_gp.txt && echo "  parser byte-exact PASS" || { echo "  parser FAIL"; tail -5 /tmp/_gp.txt; fail=1; }

echo "== 2. translator chain on the SUPPORTED fixture =="
python3 "$HERE/gs_make_synthetic.py" >/dev/null 2>&1
python3 "$HERE/gs_translate.py" "$HERE/../captures/gs/synthetic/mini_supported.gs" --scene /tmp/_sup.scene > /tmp/_sup.txt 2>&1
grep -q "census classes : translated=2" /tmp/_sup.txt && echo "  census: translated=2 OK" || { echo "  census wrong"; grep -a "census classes" /tmp/_sup.txt; fail=1; }
grep -q "EARLIEST SUPPORTED SEGMENT: 2 triangles" /tmp/_sup.txt && echo "  earliest segment: 2 tris OK" || { echo "  segment wrong"; fail=1; }
gcc -O2 -o /tmp/_psf "$HERE/ps2_feeder.c" 2>/dev/null
if /tmp/_psf --dry-run -f /tmp/_sup.scene >/tmp/_psf.txt 2>&1 && grep -q "tris=2 rects=0" /tmp/_psf.txt; then
  echo "  ps2_feeder accepts the emitted scene (2 tris) OK"
else echo "  ps2_feeder rejected the scene"; tail -3 /tmp/_psf.txt; fail=1; fi

echo "== 3. fail-closed on UNSUPPORTED fixture (mini.gs: textured triangle) =="
python3 "$HERE/gs_translate.py" "$HERE/../captures/gs/synthetic/mini.gs" --scene /tmp/_uns.scene > /tmp/_uns.txt 2>&1
grep -q "NO SUPPORTED SEGMENT" /tmp/_uns.txt && echo "  no segment + fail-closed OK" || { echo "  should have been unsupported"; grep -a "SEGMENT" /tmp/_uns.txt; fail=1; }
[ ! -f /tmp/_uns.scene ] && echo "  no scene file written (fail-closed) OK" || { echo "  scene wrongly emitted"; fail=1; }

echo "RESULT: $([ $fail -eq 0 ] && echo PASS || echo FAIL)"
exit $fail
