#!/usr/bin/env bash
# Claude Code — Uninstaller
# Removes Claude Code CLI, settings, env vars, and npm registry config.
#
# Usage: sudo bash uclaude_uninstall.sh
set -euo pipefail

GREEN="\033[92m"
CYAN="\033[96m"
YELLOW="\033[93m"
BOLD="\033[1m"
RESET="\033[0m"

log()  { echo -e "${GREEN}[+]${RESET} $*"; }
warn() { echo -e "${YELLOW}[~]${RESET} $*"; }
info() { echo -e "${CYAN}[i]${RESET} $*"; }

echo -e "${BOLD}"
echo "  +--------------------------------------+"
echo "  |    Claude Code — Uninstaller         |"
echo "  +--------------------------------------+"
echo -e "${RESET}"

# ---- Uninstall npm package ----

if npm list -g @anthropic-ai/claude-code &>/dev/null 2>&1; then
    info "Removing @anthropic-ai/claude-code..."
    npm uninstall -g @anthropic-ai/claude-code 2>/dev/null || true
    log "npm package removed"
else
    warn "Claude Code not found in npm global packages"
fi

# ---- Remove settings ----

for user_home in /root /home/*; do
    CLAUDE_DIR="$user_home/.claude"
    if [ -d "$CLAUDE_DIR" ]; then
        info "Removing $CLAUDE_DIR..."
        rm -rf "$CLAUDE_DIR"
        log "Removed $CLAUDE_DIR"
    fi
    CLAUDE_JSON="$user_home/.claude.json"
    if [ -f "$CLAUDE_JSON" ]; then
        rm -f "$CLAUDE_JSON"
        log "Removed $CLAUDE_JSON"
    fi
done

# ---- Remove env vars from shell rc files ----

for user_home in /root /home/*; do
    for rc_file in "$user_home/.bashrc" "$user_home/.zshrc"; do
        if [ -f "$rc_file" ] && grep -q 'ANTHROPIC_API_KEY\|CLAUDE_CODE\|Claude Code\|ANTHROPIC_BASE_URL' "$rc_file" 2>/dev/null; then
            info "Cleaning env vars from $rc_file..."
            sed -i '/# Claude Code/d' "$rc_file"
            sed -i '/# UnlimitedCoding.*[Cc]laude/d' "$rc_file"
            sed -i '/ANTHROPIC_API_KEY/d' "$rc_file"
            sed -i '/ANTHROPIC_BASE_URL/d' "$rc_file"
            sed -i '/CLAUDE_CODE/d' "$rc_file"
            log "Cleaned $rc_file"
        fi
    done
done

# ---- Remove /etc/profile.d script ----

for f in /etc/profile.d/claude-code.sh /etc/profile.d/claude_code.sh; do
    if [ -f "$f" ]; then
        rm -f "$f"
        log "Removed $f"
    fi
done

# ---- Remove env vars from /etc/environment ----

if [ -f "/etc/environment" ] && grep -q 'ANTHROPIC_API_KEY\|ANTHROPIC_BASE_URL\|CLAUDE_CODE' /etc/environment 2>/dev/null; then
    info "Cleaning /etc/environment..."
    sed -i '/ANTHROPIC_API_KEY/d' /etc/environment
    sed -i '/ANTHROPIC_BASE_URL/d' /etc/environment
    sed -i '/CLAUDE_CODE/d' /etc/environment
    log "Cleaned /etc/environment"
fi

# ---- Remove npm registry config ----

info "Removing npm registry config..."
npm config delete @anthropic-ai:registry 2>/dev/null || true
log "npm registry config removed"

echo ""
echo -e "${GREEN}${BOLD}  Claude Code fully uninstalled!${RESET}"
echo ""
