#!/bin/bash
# Remove ALL evolv-coder-kit and legacy claude-code-kit artifacts from ~/.claude/.
# Produces a clean, pristine environment as if neither package was ever installed.
# Usage: bash scripts/prerelease-cleanup.sh [--dry-run] [--yes]
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
NC='\033[0m'

DRY_RUN=false
SKIP_CONFIRM=false

for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=true ;;
    --yes) SKIP_CONFIRM=true ;;
    --help|-h)
      echo "Usage: bash scripts/prerelease-cleanup.sh [--dry-run] [--yes]"
      echo ""
      echo "Remove ALL evolv-coder-kit and legacy claude-code-kit artifacts."
      echo "Produces a pristine ~/.claude/ environment."
      echo ""
      echo "Options:"
      echo "  --dry-run  Show what would be removed without deleting"
      echo "  --yes      Skip confirmation prompt"
      exit 0
      ;;
    *) echo -e "${RED}Unknown flag: $arg${NC}"; exit 1 ;;
  esac
done

CLAUDE_DIR="$HOME/.claude"

echo -e "${CYAN}=== Pre-Release Cleanup ===${NC}"
if $DRY_RUN; then
  echo -e "${YELLOW}DRY RUN — no files will be removed${NC}"
fi
echo ""

if ! $SKIP_CONFIRM && ! $DRY_RUN; then
  echo "This will remove ALL evolv-coder-kit and claude-code-kit artifacts from ~/.claude/"
  echo "including registry, preferences, settings entries, hooks, skills, and standards."
  echo ""
  read -rp "Continue? [y/N] " confirm
  if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 0
  fi
  echo ""
fi

step=0

remove_dir() {
  local target="$1"
  local label="${2:-$target}"
  if [ -d "$target" ]; then
    if $DRY_RUN; then
      echo -e "    ${YELLOW}Would remove: $target${NC}"
    else
      rm -rf "$target"
    fi
    echo -e "    ${GREEN}Removed $label${NC}"
    return 0
  else
    echo -e "    Not found — skipping"
    return 1
  fi
}

remove_glob() {
  local dir="$1"
  shift
  local patterns=("$@")
  local found=0
  if [ ! -d "$dir" ]; then
    echo -e "    Not found — skipping"
    return
  fi
  for pattern in "${patterns[@]}"; do
    for f in $dir/$pattern; do
      [ -e "$f" ] || continue
      found=$((found + 1))
      if $DRY_RUN; then
        echo -e "    ${YELLOW}Would remove: $f${NC}"
      else
        rm -rf "$f"
      fi
    done
  done
  if [ "$found" -eq 0 ]; then
    echo -e "    None found — skipping"
  else
    echo -e "    ${GREEN}Removed $found item(s)${NC}"
  fi
}

# --- Step 1: Uninstall npm packages ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Uninstalling npm packages...${NC}"
if $DRY_RUN; then
  echo -e "    ${YELLOW}Would run: npm uninstall -g @evolvconsulting/claude-code-kit${NC}"
  echo -e "    ${YELLOW}Would run: npm uninstall -g @evolvconsulting/evolv-coder-kit${NC}"
else
  npm uninstall -g @evolvconsulting/claude-code-kit 2>/dev/null || true
  npm uninstall -g @evolvconsulting/evolv-coder-kit 2>/dev/null || true
fi
echo -e "    ${GREEN}DONE${NC}"

# --- Step 2: Remove scaffold directories ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Removing scaffold directories...${NC}"
remove_dir "$CLAUDE_DIR/claude-code-kit" "claude-code-kit (legacy)" || true
remove_dir "$CLAUDE_DIR/evolv-coder-kit" "evolv-coder-kit" || true
remove_dir "$CLAUDE_DIR/evolv-coder-standards" "evolv-coder-standards" || true

# --- Step 3: Remove managed skills ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Removing managed skills...${NC}"
remove_glob "$CLAUDE_DIR/skills" "eck-*" "evolv-*" "claude-code-kit-*"

# --- Step 4: Remove managed hooks ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Removing managed hooks...${NC}"
remove_glob "$CLAUDE_DIR/hooks" "evolv-*" "claude-code-kit*"

# --- Step 5: Remove managed output modes ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Removing managed output modes...${NC}"
remove_glob "$CLAUDE_DIR/output-modes" "evolv-*.md" "standard.md" "guided.md" "concise.md"

# --- Step 6: Remove managed agents ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Removing managed agents...${NC}"
remove_glob "$CLAUDE_DIR/agents" "evolv-*" "claude-code-kit*"

# --- Step 7: Clean settings.json entries ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Cleaning settings.json entries...${NC}"
settings="$CLAUDE_DIR/settings.json"
if [ -f "$settings" ] && command -v node &>/dev/null; then
  if $DRY_RUN; then
    echo -e "    ${YELLOW}Would clean evolv-*/claude-code-kit entries from settings.json${NC}"
  else
    node -e "
      const fs = require('fs');
      const p = '$settings';
      try {
        const s = JSON.parse(fs.readFileSync(p, 'utf-8'));
        let changed = false;

        // Remove statusLine if evolv- or claude-code-kit
        if (s.statusLine && s.statusLine.command &&
            (s.statusLine.command.includes('evolv-') || s.statusLine.command.includes('claude-code-kit'))) {
          delete s.statusLine; changed = true;
        }

        // Remove hook entries with evolv- or claude-code-kit
        if (s.hooks) {
          for (const event of Object.keys(s.hooks)) {
            if (!Array.isArray(s.hooks[event])) continue;
            const isEck = (cmd) => cmd && (cmd.includes('evolv-') || cmd.includes('claude-code-kit'));
            s.hooks[event] = s.hooks[event].filter(e => {
              if (Array.isArray(e.hooks)) {
                e.hooks = e.hooks.filter(h => !isEck(h.command));
                return e.hooks.length > 0;
              }
              return !isEck(e.command);
            });
            if (s.hooks[event].length === 0) delete s.hooks[event];
          }
          if (Object.keys(s.hooks).length === 0) delete s.hooks;
          changed = true;
        }

        // Remove ECK-owned keys
        for (const k of ['spinnerVerbs', 'companyAnnouncements', 'showTurnDuration', 'terminalProgressBarEnabled']) {
          if (s[k] !== undefined) { delete s[k]; changed = true; }
        }

        // Remove outputStyle if ECK-owned
        const eckStyles = ['standard', 'guided', 'concise', 'evolv-standard', 'evolv-guided', 'evolv-concise'];
        if (s.outputStyle && eckStyles.includes(s.outputStyle)) {
          delete s.outputStyle; changed = true;
        }

        if (changed) fs.writeFileSync(p, JSON.stringify(s, null, 2) + '\n');
        console.log('    Cleaned settings.json');
      } catch (e) { console.log('    settings.json parse error — skipping'); }
    " 2>/dev/null || true
  fi
  echo -e "    ${GREEN}DONE${NC}"
elif [ -f "$settings" ]; then
  echo -e "    ${YELLOW}Node.js not available — remove evolv-* entries from settings.json manually${NC}"
else
  echo -e "    settings.json not found — skipping"
fi

echo ""
if $DRY_RUN; then
  echo -e "${YELLOW}Dry run complete — no files were modified.${NC}"
else
  echo -e "${GREEN}Pre-release cleanup complete. Environment is pristine.${NC}"
  echo -e "To reinstall fresh: ${CYAN}npm install -g @evolvconsulting/evolv-coder-kit${NC}"
fi
