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

GREEN="\033[92m"
RED="\033[91m"
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 "  |    Qwen Code — Uninstaller           |"
echo "  +--------------------------------------+"
echo -e "${RESET}"

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

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

# ---- Remove settings ----

for user_home in /root /home/*; do
    QWEN_DIR="$user_home/.qwen"
    if [ -d "$QWEN_DIR" ]; then
        info "Removing $QWEN_DIR..."
        rm -rf "$QWEN_DIR"
        log "Removed $QWEN_DIR"
    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 'QWEN_API_KEY\|QWEN_BASE_URL\|Qwen Code' "$rc_file" 2>/dev/null; then
            info "Cleaning env vars from $rc_file..."
            sed -i '/# Qwen Code/d' "$rc_file"
            sed -i '/QWEN_API_KEY/d' "$rc_file"
            sed -i '/QWEN_BASE_URL/d' "$rc_file"
            log "Cleaned $rc_file"
        fi
    done
done

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

if [ -f "/etc/profile.d/qwen-code.sh" ]; then
    info "Removing /etc/profile.d/qwen-code.sh..."
    rm -f "/etc/profile.d/qwen-code.sh"
    log "Removed /etc/profile.d/qwen-code.sh"
fi

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

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

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

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

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