#!/usr/bin/env bash
# JS SPV compile · Kate Output pane · NO Konsole · structure + |1 law
# Usage: js_spv_compile.sh [file.js|all]
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
WB="$(cd "$HERE/.." && pwd)"
SPVS="$WB/spvs"
fail=0
ok=0

check_one() {
  local f="$1"
  local base name t
  base="$(basename "$f")"
  name="${base%.js}"
  echo "── compile $base"
  if [[ ! -f "$f" ]]; then
    echo "FAIL missing $f"
    fail=$((fail + 1))
    return
  fi
  t="$(cat "$f")"
  # required SPV surface
  if ! grep -q 'BGRTX_SPV_PLUGS' <<<"$t"; then
    echo "FAIL $base · no BGRTX_SPV_PLUGS registry"
    fail=$((fail + 1))
    return
  fi
  if ! grep -qE 'function[[:space:]]+mount|mount[[:space:]]*[:=]' <<<"$t"; then
    echo "FAIL $base · no mount()"
    fail=$((fail + 1))
    return
  fi
  if ! grep -q 'rides' <<<"$t" && ! grep -q 'BGF' <<<"$t"; then
    echo "WARN $base · no rides/BGF mention (ok if intentional)"
  fi
  # brace balance
  local o c
  o=$(grep -o '{' <<<"$t" | wc -l | tr -d ' ')
  c=$(grep -o '}' <<<"$t" | wc -l | tr -d ' ')
  if [[ "$o" != "$c" ]]; then
    echo "FAIL $base · brace imbalance {=$o }= $c"
    fail=$((fail + 1))
    return
  fi
  # paren balance rough
  local p q
  p=$(grep -o '(' <<<"$t" | wc -l | tr -d ' ')
  q=$(grep -o ')' <<<"$t" | wc -l | tr -d ' ')
  if [[ "$p" != "$q" ]]; then
    echo "FAIL $base · paren imbalance (= $p )= $q"
    fail=$((fail + 1))
    return
  fi
  # IIFE style preferred
  if ! grep -qE '\(function|=>\s*\{' <<<"$t"; then
    echo "WARN $base · no IIFE wrapper (still ok if global module)"
  fi
  # free law hint
  if grep -qE '\|\s*1' <<<"$t"; then
    echo "  law |1 live marks present"
  fi
  # matching dom optional
  if [[ -f "$SPVS/${name}.dom.html" ]]; then
    echo "  dom ${name}.dom.html ok"
  else
    echo "WARN $base · no ${name}.dom.html (mount may use root)"
  fi
  # node syntax if ever present
  if command -v node >/dev/null 2>&1; then
    if node --check "$f" 2>/tmp/js_spv_err.txt; then
      echo "  node --check ok"
    else
      echo "FAIL $base · node --check"
      cat /tmp/js_spv_err.txt
      fail=$((fail + 1))
      return
    fi
  fi
  echo "OK $base · SPV JS compile"
  ok=$((ok + 1))
}

target="${1:-all}"
echo "=== JS SPV compile · Kate · SPV land ==="
if [[ "$target" == "all" ]]; then
  shopt -s nullglob
  for f in "$SPVS"/*.js; do
    check_one "$f"
  done
elif [[ -f "$target" ]]; then
  check_one "$target"
elif [[ -f "$SPVS/$target" ]]; then
  check_one "$SPVS/$target"
elif [[ -f "$SPVS/${target}.js" ]]; then
  check_one "$SPVS/${target}.js"
else
  echo "usage: js_spv_compile.sh [file.js|plug_id|all]"
  exit 2
fi
echo "── result ok=$ok fail=$fail"
if [[ "$fail" -gt 0 ]]; then
  exit 1
fi
echo "GRIN free=1 · JS SPV ready for seat"
exit 0
