#!/usr/bin/env bash
# step2glb ralph-loop test
# Pass criteria per package (all four must hold):
#   - ok: true
#   - meshes >= 1
#   - materials.length >= 1   (the "not all white" criterion — guards against regressing to cadquery default export)
#   - sizeBytes > 1000        (non-trivial geometry)
# Overall: 5/5 packages pass.

set -u

TESTS=(
  "Package_TO_SOT_SMD/SOT-89-3"
  "Package_TO_SOT_SMD/TO-252-3_TabPin2"
  "Package_QFP/LQFP-100_14x14mm_P0.5mm"
  "Package_SO/SOIC-8_3.9x4.9mm_P1.27mm"
  "Connector_USB/USB_C_Receptacle_Amphenol_12401610E4-2A"
)

pass=0; fail=0
mkdir -p /tmp/step2glb-test
RESULTS=/tmp/step2glb-test/ralph-results.jsonl
> "$RESULTS"

for lib in "${TESTS[@]}"; do
  leaf="${lib##*/}"
  out="/tmp/step2glb-test/${leaf}.glb"
  echo "── $lib ──"
  # Capture both stdout (JSON on success) and stderr (JSON on failure).
  rm -f "$out"
  stdout=$(step2glb from-library "$lib" --out "$out" 2>/tmp/step2glb-test/${leaf}.stderr | tail -1)
  rc=$?

  # Evaluate pass criteria
  python3 - "$lib" "$stdout" "$rc" >> "$RESULTS" <<'PY'
import json, sys
lib = sys.argv[1]
stdout = sys.argv[2]
rc = int(sys.argv[3])

reasons = []
try:
    r = json.loads(stdout)
except Exception as e:
    r = {}
    reasons.append(f"non-JSON stdout: {e}")

ok = bool(r.get("ok"))
meshes = r.get("meshes", 0)
mats = len(r.get("materials") or [])
size = r.get("sizeBytes", 0)

if rc != 0: reasons.append(f"rc={rc}")
if not ok:  reasons.append("ok=false")
if meshes < 1: reasons.append(f"meshes={meshes}")
if mats < 1:   reasons.append(f"materials={mats}")
if size < 1000: reasons.append(f"sizeBytes={size}")

passed = len(reasons) == 0
row = {"lib": lib, "pass": passed, "meshes": meshes, "materials": mats, "sizeBytes": size, "durationMs": r.get("durationMs")}
if not passed: row["reasons"] = reasons
print(json.dumps(row))
PY
  tail -1 "$RESULTS"
done

echo
echo "=== summary ==="
python3 - "$RESULTS" <<'PY'
import json, sys
rows = [json.loads(l) for l in open(sys.argv[1])]
p = sum(1 for r in rows if r["pass"])
f = len(rows) - p
hdr = f"{'#':>2} {'pkg':<50} {'meshes':>6} {'mats':>4} {'size':>10} {'dur':>8}  status"
print(hdr); print('-'*len(hdr))
for i, r in enumerate(rows, 1):
    status = "✓" if r["pass"] else "✗ " + ",".join(r.get("reasons", []))
    sz = r.get("sizeBytes", 0)
    size_s = f"{sz/1024:.1f}KB" if sz >= 1024 else f"{sz}B"
    dur = r.get("durationMs")
    print(f"{i:>2} {r['lib']:<50} {r.get('meshes', '?'):>6} {r.get('materials', '?'):>4} {size_s:>10} {str(dur)+'ms':>8}  {status}")
print('-'*len(hdr))
print(f"pass: {p}   fail: {f}   total: {len(rows)}")
sys.exit(0 if f == 0 else 1)
PY
