#!/bin/bash
# setup.sh — One-line install of Claude Style
#
# Usage: npx claude-style
#    or: ./scripts/setup.sh
#
# This script:
# 1. Verifies prerequisites (Qwen Code, jq)
# 2. Installs the extension in ~/.qwen/extensions/
# 3. Copies hooks and prompts into extension directory
# 4. Configures hooks in ~/.qwen/settings.json
# 5. Verifies installation

set -e

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

# Detect project directory (works both locally and via npx)
SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

EXTENSION_NAME="claude-style"
EXTENSION_DIR="$HOME/.qwen/extensions/$EXTENSION_NAME"
SETTINGS_FILE="$HOME/.qwen/settings.json"

echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║        Claude Style — Installer         ║${NC}"
echo -e "${BLUE}║   Qwen Code with Claude's flavor 🎨     ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# Step 1: Verify prerequisites
echo -e "${YELLOW}[1/5] Checking prerequisites...${NC}"

if ! command -v qwen &> /dev/null; then
    echo -e "${RED}✗ Qwen Code not found${NC}"
    echo "  Install: https://github.com/QwenLM/qwen-code"
    exit 1
fi
echo -e "${GREEN}✓ Qwen Code found${NC}"

if ! command -v jq &> /dev/null; then
    echo -e "${YELLOW}⚠ jq not found — hooks will work but context injection may fail${NC}"
else
    echo -e "${GREEN}✓ jq found${NC}"
fi

# Step 2: Install extension
echo ""
echo -e "${YELLOW}[2/5] Installing extension...${NC}"

if [ -d "$EXTENSION_DIR" ]; then
    echo -e "${YELLOW}⚠ Extension already exists at $EXTENSION_DIR${NC}"
    echo "  Updating in place..."
    # Validate path before deletion (prevent symlink attacks)
    case "$EXTENSION_DIR" in
        "$HOME/.qwen/extensions/"*)
            ;;
        *)
            echo -e "${RED}✗ Invalid extension path: $EXTENSION_DIR${NC}"
            exit 1
            ;;
    esac
    # Use -P to not follow symlinks, delete contents only
    find -P "$EXTENSION_DIR" -mindepth 1 -delete 2>/dev/null || true
else
    mkdir -p "$EXTENSION_DIR"
fi

# Copy extension files (with nullglob to handle empty dirs safely)
shopt -s nullglob
ext_files=("$PROJECT_DIR/extension/"*)
if [ ${#ext_files[@]} -gt 0 ]; then
    cp -r "${ext_files[@]}" "$EXTENSION_DIR/"
fi

# Copy hooks into extension directory
mkdir -p "$EXTENSION_DIR/hooks"
hook_files=("$PROJECT_DIR/hooks/"*)
if [ ${#hook_files[@]} -gt 0 ]; then
    cp "${hook_files[@]}" "$EXTENSION_DIR/hooks/"
    chmod +x "$EXTENSION_DIR/hooks/"*.sh 2>/dev/null || true
fi

# Copy prompts into extension directory
mkdir -p "$EXTENSION_DIR/prompts"
prompt_files=("$PROJECT_DIR/prompts/"*)
if [ ${#prompt_files[@]} -gt 0 ]; then
    cp -r "${prompt_files[@]}" "$EXTENSION_DIR/prompts/"
fi
shopt -u nullglob

echo -e "${GREEN}✓ Extension installed at $EXTENSION_DIR${NC}"

# Step 3: Configure hooks
echo ""
echo -e "${YELLOW}[3/5] Configuring hooks...${NC}"

# Ensure ~/.qwen/ directory exists
mkdir -p "$(dirname "$SETTINGS_FILE")"

# Create settings.json if it doesn't exist
if [ ! -f "$SETTINGS_FILE" ]; then
    echo '{}' > "$SETTINGS_FILE"
fi

# Build hooks config using jq (proper JSON escaping for paths)
HOOKS_DIR="$EXTENSION_DIR/hooks"

HOOKS_CONFIG=$(jq -n \
    --arg ss "$HOOKS_DIR/session-start.sh" \
    --arg tg "$HOOKS_DIR/tool-guard.sh" \
    --arg ac "$HOOKS_DIR/agent-context.sh" \
    '{
  "SessionStart": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": $ss,
          "name": "claude-style-session",
          "timeout": 5000
        }
      ]
    }
  ],
  "PreToolUse": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": $tg,
          "name": "claude-style-tools",
          "timeout": 5000
        }
      ]
    }
  ],
  "SubagentStart": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": $ac,
          "name": "claude-style-agents",
          "timeout": 5000
        }
      ]
    }
  ]
}')

# Merge hooks into existing settings
if command -v jq &> /dev/null; then
    # Backup existing settings
    if [ -f "$SETTINGS_FILE" ]; then
        cp "$SETTINGS_FILE" "${SETTINGS_FILE}.claude-style.bak"
    fi

    MERGED=$(jq --argjson hooks "$HOOKS_CONFIG" '.hooks = (.hooks * $hooks)' "$SETTINGS_FILE" 2>/tmp/claude-style-jq.err) || MERGED=""

    if [ -n "$MERGED" ]; then
        echo "$MERGED" > "$SETTINGS_FILE"
        echo -e "${GREEN}✓ Hooks configured in $SETTINGS_FILE${NC}"
        if [ -f "${SETTINGS_FILE}.claude-style.bak" ]; then
            echo -e "${YELLOW}  Backup saved at ${SETTINGS_FILE}.claude-style.bak${NC}"
        fi
    else
        JQ_ERR=""
        if [ -f /tmp/claude-style-jq.err ]; then
            JQ_ERR=$(cat /tmp/claude-style-jq.err)
            rm -f /tmp/claude-style-jq.err
        fi
        echo -e "${RED}✗ Failed to merge hooks${NC}"
        if [ -n "$JQ_ERR" ]; then
            echo -e "${RED}  $JQ_ERR${NC}"
        fi
        if [ -f "${SETTINGS_FILE}.claude-style.bak" ]; then
            cp "${SETTINGS_FILE}.claude-style.bak" "$SETTINGS_FILE"
            echo -e "${YELLOW}  Settings restored from backup${NC}"
        fi
    fi
else
    echo -e "${RED}✗ jq not available — hooks not configured${NC}"
    echo "  Please install jq and re-run: npm install -g jq"
fi

# Step 4: Sync extension version with package.json
echo ""
echo -e "${YELLOW}[4/5] Syncing versions...${NC}"
if [ -f "$EXTENSION_DIR/qwen-extension.json" ] && command -v jq &> /dev/null; then
    PKG_VERSION=$(jq -r '.version' "$PROJECT_DIR/package.json")
    jq --arg v "$PKG_VERSION" '.version = $v' "$EXTENSION_DIR/qwen-extension.json" > "${EXTENSION_DIR}/qwen-extension.json.tmp" && \
        mv "${EXTENSION_DIR}/qwen-extension.json.tmp" "$EXTENSION_DIR/qwen-extension.json"
    echo -e "${GREEN}✓ Extension version synced to $PKG_VERSION${NC}"
fi

# Step 5: Verify
echo ""
echo -e "${YELLOW}[5/5] Verifying installation...${NC}"

if [ -d "$EXTENSION_DIR" ] && [ -f "$EXTENSION_DIR/qwen-extension.json" ]; then
    echo -e "${GREEN}✓ Extension files found${NC}"
else
    echo -e "${RED}✗ Extension files not found${NC}"
    exit 1
fi

if [ -d "$EXTENSION_DIR/prompts" ]; then
    PROMPT_COUNT=$(find "$EXTENSION_DIR/prompts" -name "*.md" | wc -l)
    echo -e "${GREEN}✓ $PROMPT_COUNT prompt files installed${NC}"
fi

if [ -d "$EXTENSION_DIR/hooks" ]; then
    HOOK_COUNT=$(find "$EXTENSION_DIR/hooks" -name "*.sh" | wc -l)
    echo -e "${GREEN}✓ $HOOK_COUNT hooks installed${NC}"
fi

# Summary
echo ""
echo -e "${BLUE}────────────────────────────────────────────${NC}"
echo -e "${GREEN}✓ Installation complete!${NC}"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo ""
echo "1. Start Qwen Code: ${BLUE}qwen${NC}"
echo "2. Load core prompts: ${BLUE}> /load-core-prompts${NC}"
echo "3. Verify: ${BLUE}> /memory show${NC}"
echo ""
echo -e "${YELLOW}Available commands:${NC}"
echo "  /load-core-prompts    Load Claude behavioral rules"
echo "  /claude-review        Review code"
echo "  /claude-refactor      Refactor code"
echo "  /claude-debug         Debug systematically"
echo "  /claude-plan          Plan features"
echo "  /claude-explore       Explore codebase"
echo "  /claude-security      Security review"
echo "  /claude-commit        Create commits"
echo ""
echo -e "${BLUE}────────────────────────────────────────────${NC}"
