#!/usr/bin/env bash
# Phase 0 validation — prove the native stack actually runs inside the container.
#
# For each bundled sample (MR16 / MR27 / MR28) it exercises every heavy path:
#   1. default run  -> CAD kernel load + BOM .xlsx (openpyxl) + 6 thumbnails (pyrender/OSMesa)
#   2. --query      -> geometry query engine
#   3. --diagram    -> dimensional sheet export (cairosvg)
#
# Outputs persist on the host in ./_phase0_out for inspection.
# Translation (--translate, needs ANTHROPIC_API_KEY) is intentionally skipped here.
set -uo pipefail
cd "$(dirname "$0")"

IMAGE="${IMAGE:-step-parser}"
TAG="${TAG:-dev}"
OUT="${OUT:-$PWD/_phase0_out}"
mkdir -p "$OUT"

SAMPLES=(
  "MR16s Gen1_EN.step"
  "MR27s Gen1_EN.step"
  "MR28uws Gen1_EN.step"
)

pass=0; fail=0
for s in "${SAMPLES[@]}"; do
  stem="${s%.step}"
  echo "──────────────────────────────────────────────────────────────"
  echo "  $s"
  echo "──────────────────────────────────────────────────────────────"

  # Copy the baked-in sample into the mounted dir, then process it there so all
  # generated files land on the host. `set -e` makes any failing path fail the run.
  docker run --rm -v "$OUT:/data" --entrypoint sh "$IMAGE:$TAG" -c "
    set -e
    cp '/app/skill.src/$s' '/data/$s'
    echo '--- run 1: BOM + thumbnails (kernel + openpyxl + pyrender/OSMesa) ---'
    python /app/skill.src/step_processor.py '/data/$s' --no-translate --verbose
    echo '--- run 2: geometry query ---'
    python /app/skill.src/step_processor.py '/data/$s' --query 'bounding box'
    echo '--- run 3: external dimensional diagram (cairosvg) ---'
    python /app/skill.src/step_processor.py '/data/$s' --no-thumbnails --no-bom --diagram
  "
  rc=$?

  # Verify the expected artifacts actually exist on the host.
  missing=""
  [ -f "$OUT/${stem}_bom.xlsx" ] || missing="$missing bom.xlsx"
  ls "$OUT/${stem}"_*.png        >/dev/null 2>&1 || missing="$missing thumbnails"
  [ -f "$OUT/${stem}__external-diagram.svg" ] || missing="$missing diagram.svg"

  if [ $rc -eq 0 ] && [ -z "$missing" ]; then
    echo "PASS: $s"
    pass=$((pass+1))
  else
    echo "FAIL: $s (exit=$rc, missing:${missing:- none})"
    fail=$((fail+1))
  fi
done

echo "=============================================================="
echo "  Phase 0 smoke test: ${pass} passed, ${fail} failed"
echo "  Artifacts: $OUT"
echo "=============================================================="
[ "$fail" -eq 0 ]
