#!/bin/bash
# uninstall.sh — Remove Claude Style from Qwen Code
#
# Usage: ./scripts/uninstall.sh
#
# Removes the extension and restores hooks from backup.
# Does NOT delete the project directory.

set -e

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

EXTENSION_DIR="$HOME/.qwen/extensions/claude-style"
SETTINGS_FILE="$HOME/.qwen/settings.json"
BACKUP_FILE="${SETTINGS_FILE}.claude-style.bak"

echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Claude Style — Uninstall             ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# Remove extension
if [ -d "$EXTENSION_DIR" ]; then
    echo -e "${YELLOW}Removing extension...${NC}"
    rm -rf "$EXTENSION_DIR"
    echo -e "${GREEN}✓ Extension removed from $EXTENSION_DIR${NC}"
else
    echo -e "${YELLOW}⚠ Extension not found at $EXTENSION_DIR${NC}"
fi

# Restore hooks from backup
if [ -f "$BACKUP_FILE" ]; then
    echo -e "${YELLOW}Restoring hooks from backup...${NC}"
    cp "$BACKUP_FILE" "$SETTINGS_FILE"
    rm -f "$BACKUP_FILE"
    echo -e "${GREEN}✓ Hooks restored from backup${NC}"
elif [ -f "$SETTINGS_FILE" ] && command -v jq &> /dev/null; then
    # Remove claude-style hooks by rebuilding the hooks structure
    echo -e "${YELLOW}Removing claude-style hooks from settings...${NC}"
    UPDATED=$(jq '
        if .hooks.SessionStart then .hooks.SessionStart = [.hooks.SessionStart[]? | .hooks = [.hooks[]? | select(.name | test("claude-style") | not)]] else . end |
        if .hooks.PreToolUse then .hooks.PreToolUse = [.hooks.PreToolUse[]? | .hooks = [.hooks[]? | select(.name | test("claude-style") | not)]] else . end |
        if .hooks.SubagentStart then .hooks.SubagentStart = [.hooks.SubagentStart[]? | .hooks = [.hooks[]? | select(.name | test("claude-style") | not)]] else . end
    ' "$SETTINGS_FILE" 2>&1) || UPDATED=""

    if [ -n "$UPDATED" ]; then
        echo "$UPDATED" > "$SETTINGS_FILE"
        echo -e "${GREEN}✓ Claude Style hooks removed from settings${NC}"
    else
        echo -e "${YELLOW}⚠ Could not remove hooks — remove manually from $SETTINGS_FILE${NC}"
    fi
fi

echo ""
echo -e "${BLUE}────────────────────────────────────────────${NC}"
echo -e "${GREEN}✓ Uninstall complete${NC}"
echo ""
echo -e "${YELLOW}Note: The project directory was not deleted.${NC}"
echo "  Delete it manually if desired: ${BLUE}rm -rf ~/projects/personal/claude-style${NC}"
