#!/usr/bin/env bash
# reflection's wake entry point with auto-rollback escape hatch.
#
# This shim is deliberately small and lives outside the Python runtime so it
# survives runtime corruption. If the agent's self-modifications break
# `agent/runtime/`, this shim detects the failure (via an import smoke test)
# and rolls `agent/runtime/` back to the `reflect/last-known-good` ref before
# launching the wake.
#
# Off-limits to the agent — modifying this shim defeats the rollback path.
set -euo pipefail

# Cron's PATH is minimal (/usr/bin:/bin) and doesn't include uv's home
# (~/.local/bin). Prepend the paths the runtime needs so cron-fired wakes find
# uv, scry, etc. — same effect as running from an interactive shell.
export PATH="$HOME/.local/bin:/usr/local/bin:$PATH"

PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$PROJECT_ROOT"

SMOKE_LOG="$(mktemp -t reflect-smoke.XXXXXX.log)"
trap 'rm -f "$SMOKE_LOG"' EXIT

run_smoke() {
    uv run python -c "from agent.runtime.wake import main" >"$SMOKE_LOG" 2>&1
}

attempt_rollback() {
    if ! git rev-parse --verify reflect/last-known-good >/dev/null 2>&1; then
        echo "❌ no reflect/last-known-good ref — cannot auto-rollback" >&2
        return 1
    fi
    echo "⚠️  reflect runtime smoke failed; rolling back agent/runtime/ to reflect/last-known-good" >&2
    git checkout reflect/last-known-good -- agent/runtime/
    return 0
}

if ! run_smoke; then
    echo "❌ reflect runtime failed import smoke test:" >&2
    cat "$SMOKE_LOG" >&2
    if attempt_rollback; then
        if ! run_smoke; then
            echo "❌ post-rollback smoke still failing — manual intervention needed" >&2
            cat "$SMOKE_LOG" >&2
            exit 1
        fi
        echo "✓ rollback successful; runtime restored to last known good" >&2
    else
        exit 1
    fi
fi

# Extract --track <name> from args and export as REFLECT_TRACK env var.
# Falls back to "main" (already the Python default) if --track is absent.
# Dispatcher path (bin/reflect-dispatch → agent/lib/tick.py) sets REFLECT_TRACK
# directly via os.environ; this branch handles manual `bin/reflect-wake --track foo`.
REFLECT_TRACK="${REFLECT_TRACK:-main}"
args=()
while [[ $# -gt 0 ]]; do
    case "$1" in
        --track)
            REFLECT_TRACK="${2:-main}"
            shift 2
            ;;
        *)
            args+=("$1")
            shift
            ;;
    esac
done
export REFLECT_TRACK
exec uv run reflect-wake "${args[@]}"
