#!/usr/bin/env bash
# Remove Omnish Cursor bundle entries from ~/.cursor (keeps unrelated hooks).
set -euo pipefail

CURSOR_DIR="${CURSOR_DIR:-$HOME/.cursor}"
HOOKS_JSON="$CURSOR_DIR/hooks.json"

REMOVE_HOOKS=1
REMOVE_SKILL=1
REMOVE_CONFIG=0

usage() {
  cat <<EOF
Usage: $(basename "$0") [options]

Remove Omnish Cursor integration installed by install.sh.

Options:
  --hooks-only     Remove hooks + rule + hooks.json entries only
  --skill-only     Remove ~/.cursor/skills/omnish only
  --with-config    Also delete ~/.cursor/omnish-notify.json
  -h, --help       Show this help
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --hooks-only)
      REMOVE_HOOKS=1
      REMOVE_SKILL=0
      shift
      ;;
    --skill-only)
      REMOVE_HOOKS=0
      REMOVE_SKILL=1
      shift
      ;;
    --with-config)
      REMOVE_CONFIG=1
      shift
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      echo "error: unknown option: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

OMNISH_COMMANDS=(
  "./hooks/omnish-session-start.sh"
  "./hooks/omnish-notify.sh"
)

if [[ "$REMOVE_HOOKS" -eq 1 && -f "$HOOKS_JSON" ]]; then
  python3 - "$HOOKS_JSON" "${OMNISH_COMMANDS[@]}" <<'PY'
import json
import sys
from pathlib import Path

hooks_path = Path(sys.argv[1])
remove_cmds = set(sys.argv[2:])
data = json.loads(hooks_path.read_text(encoding="utf-8"))
hooks = data.get("hooks") or {}
changed = False
for event, entries in list(hooks.items()):
    if not isinstance(entries, list):
        continue
    filtered = [
        e for e in entries
        if not (isinstance(e, dict) and e.get("command") in remove_cmds)
    ]
    if len(filtered) != len(entries):
        changed = True
        hooks[event] = filtered
if changed:
    hooks_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
    print(f"updated {hooks_path} (removed omnish hook entries)")
else
    print(f"no omnish hook entries in {hooks_path}")
PY
fi

if [[ "$REMOVE_HOOKS" -eq 1 ]]; then
  rm -f \
    "$CURSOR_DIR/hooks/omnish-notify.sh" \
    "$CURSOR_DIR/hooks/omnish-notify.py" \
    "$CURSOR_DIR/hooks/omnish-session-start.sh" \
    "$CURSOR_DIR/rules/omnish-notify.mdc"
  echo "removed hook scripts and omnish-notify rule"
fi

if [[ "$REMOVE_SKILL" -eq 1 ]]; then
  rm -rf "$CURSOR_DIR/skills/omnish"
  echo "removed $CURSOR_DIR/skills/omnish"
fi

if [[ "$REMOVE_CONFIG" -eq 1 ]]; then
  rm -f "$CURSOR_DIR/omnish-notify.json"
  echo "removed $CURSOR_DIR/omnish-notify.json"
fi

echo "Done. Restart Cursor if hooks were removed."
