#!/usr/bin/env bash
# Arm/disarm a fake plugin-update for Phase 18.4 handoff testing.
# Stages target/release/owl.exe + current skills under a sibling cache dir,
# then rewrites installed_plugins.json["spt@cplugs"][0] to point there.
# Disarm restores the manifest from backup. Cache dir is left on disk.
set -euo pipefail

CURRENT_VER_DIR="$HOME/.claude/plugins/cache/cplugs/spt/1.8.7"
FAKE_VER="1.8.8-test"
FAKE_DIR="$HOME/.claude/plugins/cache/cplugs/spt/$FAKE_VER"
MANIFEST="$HOME/.claude/plugins/installed_plugins.json"
BAK="$MANIFEST.handoff-test.bak"

REPO="$(cd "$(dirname "$0")/.." && pwd)"
NEW_BINARY="$REPO/target/release/owl.exe"

arm() {
    if [[ -f "$BAK" ]]; then
        echo "REFUSING: backup already exists at $BAK — disarm first" >&2
        exit 1
    fi
    if [[ ! -f "$NEW_BINARY" ]]; then
        echo "REFUSING: $NEW_BINARY missing — run cargo build --release first" >&2
        exit 1
    fi

    cp "$MANIFEST" "$BAK"

    mkdir -p "$FAKE_DIR"
    cp -r "$CURRENT_VER_DIR/." "$FAKE_DIR/"
    cp "$NEW_BINARY" "$FAKE_DIR/owl.exe"

    # Convert Unix-style FAKE_DIR to Windows form for installed_plugins.json.
    # Windows paths use backslashes and drive letter; manifest parser reads literal string.
    WIN_FAKE_DIR=$(cygpath -w "$FAKE_DIR")

    python - "$MANIFEST" "$WIN_FAKE_DIR" "$FAKE_VER" <<'PY'
import json, sys, pathlib
m_path, new_path, ver = sys.argv[1], sys.argv[2], sys.argv[3]
m = json.loads(pathlib.Path(m_path).read_text())
entry = m["plugins"]["spt@cplugs"][0]
entry["installPath"] = new_path
entry["version"] = ver
pathlib.Path(m_path).write_text(json.dumps(m, indent=2))
PY

    echo "ARMED"
    echo "  fake cache:  $FAKE_DIR"
    echo "  installPath: $WIN_FAKE_DIR"
    echo "  backup:      $BAK"
}

disarm() {
    if [[ ! -f "$BAK" ]]; then
        echo "NOT ARMED (no backup at $BAK)" >&2
        exit 1
    fi
    mv "$BAK" "$MANIFEST"
    echo "DISARMED (manifest restored from $BAK)"
}

status() {
    if [[ -f "$BAK" ]]; then
        echo "ARMED (backup exists at $BAK)"
        python - "$MANIFEST" <<'PY'
import json, sys, pathlib
m = json.loads(pathlib.Path(sys.argv[1]).read_text())
entry = m["plugins"]["spt@cplugs"][0]
print(f"  current installPath: {entry['installPath']}")
print(f"  current version:     {entry['version']}")
PY
    else
        echo "DISARMED"
    fi
}

case "${1:-}" in
    arm) arm ;;
    disarm) disarm ;;
    status) status ;;
    *)
        echo "usage: $0 {arm|disarm|status}" >&2
        exit 2
        ;;
esac
