#!/bin/bash
# Phase 29ab P2: Pattern2 LoopBodyLocal Trim (seg) minimal (VM backend)
# Tests: LoopBodyLocal seg in break condition promoted via Trim A-3

source "$(dirname "$0")/../../../lib/test_runner.sh"
export SMOKES_USE_PYVM=0
require_env || exit 2

INPUT="$NYASH_ROOT/apps/tests/phase29ab_pattern2_loopbodylocal_seg_min.hako"
RUN_TIMEOUT_SECS=${RUN_TIMEOUT_SECS:-10}

set +e
OUTPUT=$(timeout "$RUN_TIMEOUT_SECS" env NYASH_DISABLE_PLUGINS=1 HAKO_JOINIR_STRICT=1 "$NYASH_BIN" "$INPUT" 2>&1)
EXIT_CODE=$?
set -e

if [ "$EXIT_CODE" -eq 124 ]; then
    test_fail "phase29ab_pattern2_loopbodylocal_seg_min_vm: hakorune timed out (>${RUN_TIMEOUT_SECS}s)"
    exit 1
fi

OUTPUT_CLEAN=$(echo "$OUTPUT" | filter_noise)
EXPECTED_TAG="[plan/pattern2/promotion_hint:TrimSeg]"

if echo "$OUTPUT_CLEAN" | grep -q "^2$" || echo "$OUTPUT" | grep -q "^RC: 2$"; then
    if echo "$OUTPUT_CLEAN" | grep -qF "$EXPECTED_TAG"; then
        test_pass "phase29ab_pattern2_loopbodylocal_seg_min_vm: Pattern2 Trim promotion succeeded (output: 2)"
        exit 0
    fi
    echo "[FAIL] Missing promotion hint tag (expected: $EXPECTED_TAG)"
    echo "[INFO] Output (clean):"
    echo "$OUTPUT_CLEAN" | tail -n 20 || true
    test_fail "phase29ab_pattern2_loopbodylocal_seg_min_vm: Missing promotion hint tag"
    exit 1
else
    echo "[FAIL] Unexpected output (expected: 2)"
    echo "[INFO] Exit code: $EXIT_CODE"
    echo "[INFO] Output (clean):"
    echo "$OUTPUT_CLEAN" | tail -n 20 || true
    test_fail "phase29ab_pattern2_loopbodylocal_seg_min_vm: Unexpected output"
    exit 1
fi
