#!/bin/sh
# retroDE_ps2 — Ch339 host-encoder gate. Compiles ps2_feeder and proves its staging output is
# BYTE-EQUIVALENT to the golden bake.py fixtures for every representative Ch333-338 scene, then
# checks that malformed / oversized / out-of-range commands are rejected cleanly. No board needed.
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
REPO="$(cd "$HERE/.." && pwd)"
MEM="$REPO/sim/data/top_psmct32_raster_demo"
BIN="$(mktemp -d)/ps2_feeder"
fail=0

echo "== compile =="
gcc -O2 -Wall -Werror -o "$BIN" "$HERE/ps2_feeder.c" || { echo "COMPILE FAILED"; exit 1; }

echo "== regenerate goldens =="
python3 "$MEM/bake.py" >/dev/null 2>&1 || { echo "bake.py failed"; exit 1; }

echo "== byte-equivalence vs golden .mem =="
check() {  # $1 scene  $2 golden.mem
    "$BIN" --dump "$1" > /tmp/_dump.txt 2>/tmp/_err.txt
    tail -n +3 "$MEM/$2" > /tmp/_gold.txt
    if diff /tmp/_dump.txt /tmp/_gold.txt >/dev/null 2>&1; then
        echo "  MATCH    $1 == $2"
    else
        echo "  MISMATCH $1 != $2"; fail=1
    fi
}
check color-tri      feeder_color_tri.mem
check native-rect    feeder_native_rect.mem
check gouraud-tri    feeder_gouraud_tri.mem
check accum          feeder_accum.mem
check retrigger-a    feeder_scene_a.mem
check retrigger-b    feeder_scene_b.mem
check zpersist-near  feeder_zpersist_near_first.mem
check zpersist-far   feeder_zpersist_far_first.mem
check zpersist-grad  feeder_zpersist_grad.mem
check sprite         feeder_sprite.mem      # Ch345a — runtime textured-alpha SPRITE staging

echo "== rejection of bad input (each must exit non-zero) =="
reject() {  # $1 label ; rest = file contents on stdin
    cat > /tmp/_sc.txt
    if "$BIN" --dry-run -f /tmp/_sc.txt >/dev/null 2>&1; then echo "  NOT-REJECTED $1"; fail=1; else echo "  rejected     $1"; fi
}
yes 'tritile 0 0x5000 255 0 0' | head -28 | reject "oversized (28 tris)"
printf 'tri 1 2 3\n'                  | reject "malformed tri"
printf 'tritile 99 0x5000 255 0 0\n'  | reject "tile out of range"
printf 'bogus 1 2 3\n'                | reject "unknown op"

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