#!/bin/bash
# selfhost_minimal.sh — Minimal selfhost Stage‑B→VM path using stage1_run_min.hako

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
if ROOT_GIT=$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null); then
  ROOT="$ROOT_GIT"
else
  ROOT="$(cd "$SCRIPT_DIR/../../../../.." && pwd)"
fi

BIN="${NYASH_BIN:-$ROOT/target/release/nyash}"
SELFHOST="$ROOT/tools/selfhost/selfhost_build.sh"
TARGET="$ROOT/apps/tests/stage1_run_min.hako"

warn() { echo -e "[WARN] $*" >&2; }
info() { echo -e "[INFO] $*" >&2; }
fail() { echo -e "[FAIL] $*" >&2; exit 1; }
pass() { echo -e "[PASS] $*" >&2; }

if [ ! -x "$BIN" ]; then
  warn "[SKIP] nyash binary not found at $BIN (build release first)"
  exit 0
fi

if [ ! -x "$SELFHOST" ]; then
  warn "[SKIP] selfhost_build.sh missing at $SELFHOST"
  exit 0
fi

if [ ! -f "$TARGET" ]; then
  warn "[SKIP] target fixture not found: $TARGET"
  exit 0
fi

info "Running minimal selfhost path via selfhost_build.sh"
set +e
NYASH_FEATURES="${NYASH_FEATURES:-stage3}" \
NYASH_USE_NY_COMPILER="${NYASH_USE_NY_COMPILER:-1}" \
NYASH_NY_COMPILER_EMIT_ONLY="${NYASH_NY_COMPILER_EMIT_ONLY:-1}" \
  "$SELFHOST" --in "$TARGET" --run
rc=$?
set -e

if [ $rc -ne 0 ]; then
  fail "selfhost_minimal failed (rc=$rc)"
fi

pass "selfhost_minimal passed (stage1_run_min.hako)"
exit 0
