#!/bin/sh
set -eu
PROJECT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
YAZA_TEST_CLI=${YAZA_TEST_CLI:-"$PROJECT_ROOT/dist/yaza"}
export YAZA_STDLIB_DIR="$PROJECT_ROOT"
TEMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/yaza-defer-check.XXXXXX")
trap 'rm -rf "$TEMP_DIR"' EXIT HUP INT TERM
cd "$PROJECT_ROOT"
"$YAZA_TEST_CLI" build tests/defer.test.yz -o "$TEMP_DIR/defer"
"$TEMP_DIR/defer" > "$TEMP_DIR/actual"
printf '%s\n' 'Deferred cleanup semantics passed.' 'Main scope cleanup passed.' > "$TEMP_DIR/expected"
cmp "$TEMP_DIR/expected" "$TEMP_DIR/actual"
cat > "$TEMP_DIR/bad-call.yz" <<'YAZA'
start:
    defer 1 + 2
YAZA
cat > "$TEMP_DIR/bad-result.yz" <<'YAZA'
fn cleanup() -> Result[Number, Text]:
    return err("must be handled")
start:
    defer cleanup()
YAZA
cat > "$TEMP_DIR/bad-type.yz" <<'YAZA'
fn cleanup(value: Number) -> Number:
    return value
start:
    defer cleanup("wrong type")
YAZA
cat > "$TEMP_DIR/bad-trailing.yz" <<'YAZA'
fn cleanup() -> Number:
    return 0
start:
    defer cleanup() + 1
YAZA
cat > "$TEMP_DIR/bad-unknown.yz" <<'YAZA'
start:
    defer missing_cleanup()
YAZA
for fixture in "$TEMP_DIR"/bad-*.yz; do
    if "$YAZA_TEST_CLI" check "$fixture" > "$TEMP_DIR/diagnostic" 2>&1; then
        printf 'FAIL compiler accepted %s\n' "$fixture" >&2
        exit 1
    fi
    grep -F 'native compiler:' "$TEMP_DIR/diagnostic" > /dev/null
done
printf '%s\n' 'Deferred cleanup conformance passed (scope exits, captures, and rejected programs).'
