#!/bin/bash
# Uninstall evolv-coder-kit and remove all artifacts from ~/.claude/.
# Produces a clean, pristine environment as if the package was never installed.
# Usage: bash scripts/uninstall-package.sh [--dry-run]
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
for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=true ;;
    --help|-h)
      echo "Usage: bash scripts/uninstall-package.sh [--dry-run]"
      echo ""
      echo "Completely remove evolv-coder-kit and all managed artifacts."
      echo "Leaves ~/.claude/ itself intact (Claude Code's own directory)."
      exit 0
      ;;
    *) echo -e "${RED}Unknown flag: $arg${NC}"; exit 1 ;;
  esac
done

echo -e "${CYAN}=== evolv-coder-kit Uninstall ===${NC}"
if $DRY_RUN; then
  echo -e "${YELLOW}DRY RUN — no files will be removed${NC}"
fi
echo ""

CLAUDE_DIR="$HOME/.claude"
step=0

# --- Step 1: Use the JS uninstaller if available (most thorough) ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Running JS uninstaller (--uninstall)...${NC}"
if command -v evolv-coder-kit &>/dev/null; then
  if $DRY_RUN; then
    evolv-coder-kit --uninstall --dry-run 2>/dev/null || true
  else
    evolv-coder-kit --uninstall 2>/dev/null || true
  fi
  echo -e "    ${GREEN}DONE${NC}"
else
  echo -e "    ${YELLOW}Binary not found — falling back to manual cleanup${NC}"
fi

# --- Step 2: Remove any remaining artifacts the JS uninstaller might miss ---
step=$((step + 1))
echo -e "${CYAN}Step $step: Removing remaining artifacts...${NC}"

# ~/.claude/evolv-coder-kit/ (scaffold, prefs, registry, migrations, state)
target="$CLAUDE_DIR/evolv-coder-kit"
if [ -d "$target" ]; then
  if $DRY_RUN; then
    echo -e "    ${YELLOW}Would remove: $target${NC}"
  else
    rm -rf "$target"
  fi
  echo -e "    ${GREEN}Removed $target${NC}"
fi

# ~/.claude/evolv-coder-standards/ (cloned standards repo)
target="$CLAUDE_DIR/evolv-coder-standards"
if [ -d "$target" ]; then
  if $DRY_RUN; then
    echo -e "    ${YELLOW}Would remove: $target${NC}"
  else
    rm -rf "$target"
  fi
  echo -e "    ${GREEN}Removed $target${NC}"
fi

# ~/.claude/skills/eck-* (global skills)
if [ -d "$CLAUDE_DIR/skills" ]; then
  found=0
  for d in "$CLAUDE_DIR/skills"/eck-*; do
    [ -e "$d" ] || continue
    found=$((found + 1))
    if $DRY_RUN; then
      echo -e "    ${YELLOW}Would remove: $d${NC}"
    else
      rm -rf "$d"
    fi
  done
  if [ "$found" -gt 0 ]; then
    echo -e "    ${GREEN}Removed $found skill(s)${NC}"
  fi
fi

# ~/.claude/hooks/evolv-* (compiled hooks)
if [ -d "$CLAUDE_DIR/hooks" ]; then
  found=0
  for f in "$CLAUDE_DIR/hooks"/evolv-*; do
    [ -e "$f" ] || continue
    found=$((found + 1))
    if $DRY_RUN; then
      echo -e "    ${YELLOW}Would remove: $f${NC}"
    else
      rm -rf "$f"
    fi
  done
  if [ "$found" -gt 0 ]; then
    echo -e "    ${GREEN}Removed $found hook file(s)${NC}"
  fi
fi

# ~/.claude/output-modes/evolv-*.md and standard ECK style files
if [ -d "$CLAUDE_DIR/output-modes" ]; then
  found=0
  for f in "$CLAUDE_DIR/output-modes"/evolv-*.md \
           "$CLAUDE_DIR/output-modes/standard.md" \
           "$CLAUDE_DIR/output-modes/guided.md" \
           "$CLAUDE_DIR/output-modes/concise.md"; do
    [ -e "$f" ] || continue
    found=$((found + 1))
    if $DRY_RUN; then
      echo -e "    ${YELLOW}Would remove: $f${NC}"
    else
      rm -f "$f"
    fi
  done
  if [ "$found" -gt 0 ]; then
    echo -e "    ${GREEN}Removed $found output mode file(s)${NC}"
  fi
fi

echo -e "    ${GREEN}DONE${NC}"

# --- Step 3: Clean settings.json evolv-* 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-* 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-
        if (s.statusLine && s.statusLine.command && s.statusLine.command.includes('evolv-')) {
          delete s.statusLine; changed = true;
        }

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

        // 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');
      } catch (e) { /* ignore parse errors */ }
    " 2>/dev/null || true
  fi
  echo -e "    ${GREEN}DONE${NC}"
else
  echo -e "    ${YELLOW}settings.json not found or node not available — skipping${NC}"
fi

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

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