#!/usr/bin/env bash
# check-blank.sh - Smoke-test the new-port template (src/blank/blank.c).
#
# A blank port has no toolchain, so we compile it with the HOST cc just to
# prove two things stay true as the library evolves:
#   1. The template + the JOEYLIB_PLATFORM_BLANK blocks in platform.h still
#      compile (catches a new platform-#if dispatch point that forgot a BLANK
#      case -- e.g. assetLoad.c's tile target, the sprite emitter selector).
#   2. blank.c + the generics LINK with no unresolved jlp* ops -- i.e. a new
#      chunky port really does get everything except the platform services for
#      free from src/generic/.
#
# Source set mirrors a real blank-port build: core + ALL of src/generic
# (including the stub sprite emitter) + blank.c; NOT src/codegen/spriteCompile.c
# (that's only for ports with a per-CPU JIT emitter).
set -euo pipefail

repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
cc=${CC:-cc}
work=$(mktemp -d -t joeylib-blank.XXXXXX)
trap 'rm -rf "$work"' EXIT

inc=(-Iinclude -Iinclude/joey -Isrc/core -Isrc/codegen)
cd "$repo"

fail=0
for f in src/core/*.c src/generic/*.c src/blank/blank.c; do
    o="$work/$(echo "$f" | tr / _).o"
    if ! "$cc" -DJOEYLIB_PLATFORM_BLANK "${inc[@]}" -Wall -c "$f" -o "$o" 2>"$work/err"; then
        echo "check-blank: COMPILE FAIL: $f" >&2
        sed 's/^/  /' "$work/err" >&2
        fail=1
    fi
done
[ "$fail" = 0 ] || { echo "check-blank: FAIL (template does not compile for BLANK)" >&2; exit 1; }

# Link-completeness: any JoeyLib symbol undefined across the whole object set
# (and not defined by any of them) is a real gap in blank.c or the generics.
missing=$(python3 - "$work" <<'PY'
import subprocess, sys, glob
defs=set(); und=set()
for o in glob.glob(sys.argv[1]+"/*.o"):
    for line in subprocess.run(["nm",o],capture_output=True,text=True).stdout.splitlines():
        p=line.split()
        if len(p)>=3 and p[1] in "TDBRtdbr": defs.add(p[2])
        elif len(p)>=3 and p[1]=="U": und.add(p[2])
        elif len(p)==2 and p[0]=="U": und.add(p[1])
print(" ".join(sorted(s for s in und-defs if s.startswith(("jlp","jlSprite","spriteCompiledDraw")))))
PY
)
if [ -n "$missing" ]; then
    echo "check-blank: FAIL - unresolved JoeyLib symbols (blank.c / generics gap):" >&2
    echo "  $missing" >&2
    exit 1
fi

echo "check-blank: PASS (blank template compiles + links; all ops resolve via blank.c + generics)"
