#!/bin/bash
# bisect_sxbc.sh — Binary search for which .sxbc file breaks reactive rendering.
# Runs test_wasm.sh with SX_TEST_BYTECODE=1, toggling individual files between
# bytecode and source to find the culprit.
set -euo pipefail

cd "$(dirname "$0")/../../.."

SXBC_DIR="shared/static/wasm/sx"
BACKUP_DIR="/tmp/sxbc-bisect-backup"

# All .sxbc files in load order
FILES=(
  render core-signals signals deps router page-helpers freeze
  bytecode compiler vm dom browser
  adapter-html adapter-sx adapter-dom
  boot-helpers hypersx
  harness harness-reactive harness-web
  engine orchestration boot
)

# Backup all sxbc files
mkdir -p "$BACKUP_DIR"
for f in "${FILES[@]}"; do
  cp "$SXBC_DIR/$f.sxbc" "$BACKUP_DIR/$f.sxbc" 2>/dev/null || true
done

# Test function: returns 0 if the reactive scoped test passes
test_passes() {
  local result
  result=$(SX_TEST_BYTECODE=1 bash hosts/ocaml/browser/test_wasm.sh 2>&1) || true
  if echo "$result" | grep -q "scoped static class"; then
    # Test mentioned = it failed
    return 1
  else
    return 0
  fi
}

# Restore all bytecodes
restore_all() {
  for f in "${FILES[@]}"; do
    cp "$BACKUP_DIR/$f.sxbc" "$SXBC_DIR/$f.sxbc" 2>/dev/null || true
  done
}

# Remove specific bytecodes (force source loading for those)
remove_sxbc() {
  for f in "$@"; do
    rm -f "$SXBC_DIR/$f.sxbc"
  done
}

echo "=== Bytecode bisect: finding which .sxbc breaks reactive rendering ==="
echo "    ${#FILES[@]} files to search"
echo ""

# First: verify all-bytecode fails
restore_all
echo "--- All bytecode (should fail) ---"
if test_passes; then
  echo "UNEXPECTED: all-bytecode passes! Nothing to bisect."
  exit 0
fi
echo "  Confirmed: fails with all bytecode"

# Second: verify all-source passes
for f in "${FILES[@]}"; do rm -f "$SXBC_DIR/$f.sxbc"; done
echo "--- All source (should pass) ---"
if ! test_passes; then
  echo "UNEXPECTED: all-source also fails! Bug is not bytecode-specific."
  restore_all
  exit 1
fi
echo "  Confirmed: passes with all source"

# Binary search: find minimal set of bytecode files that causes failure
# Strategy: start with all source, add bytecode files one at a time
echo ""
echo "=== Individual file test ==="
culprits=()
for f in "${FILES[@]}"; do
  # Start from all-source, add just this one file as bytecode
  for g in "${FILES[@]}"; do rm -f "$SXBC_DIR/$g.sxbc"; done
  cp "$BACKUP_DIR/$f.sxbc" "$SXBC_DIR/$f.sxbc"

  if test_passes; then
    printf "  %-20s bytecode OK\n" "$f"
  else
    printf "  %-20s *** BREAKS ***\n" "$f"
    culprits+=("$f")
  fi
done

# Restore
restore_all

echo ""
if [ ${#culprits[@]} -eq 0 ]; then
  echo "No single file causes the failure — it's a combination."
  echo "Run with groups to narrow down."
else
  echo "=== CULPRIT FILE(S): ${culprits[*]} ==="
  echo "These .sxbc files individually cause the reactive rendering to break."
fi
