#!/bin/bash
################################################################################
# SuperCharge Claude Code - Ultimate Installation Script
################################################################################
# This script transforms any Claude Code installation into a supercharged
# version with all customizations, skills, agents, plugins, and integrations.
#
# Features:
# - 30+ Custom Skills (cognitive, development, UI/UX, brainstorming)
# - RalphLoop autonomous agent integration
# - Multi-AI consultation (Qwen integration)
# - Agent management system with sync capabilities
# - Custom hooks for session management
# - MCP servers integration
# - Plugin marketplace setup
# - Optional Claude Code installation with Z.AI API support
#
# Usage: ./supercharge.sh [options]
#   --skip-deps    Skip dependency installation
#   --dev-mode     Development mode (verbose output)
#
# For Claude Code installation: ./install-claude-code.sh [options]
#   --auto         Automatic installation with API key prompt (default)
#   --manual       Show manual installation steps only
#   --skip-install Skip Claude Code installation, just configure API
################################################################################

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Claude config directory
CLAUDE_DIR="${HOME}/.claude"

# Backup directory
BACKUP_DIR="${HOME}/.claude-backup-$(date +%Y%m%d_%H%M%S)"

# Flags
SKIP_DEPS=false
DEV_MODE=false

################################################################################
# Helper Functions
################################################################################

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${CYAN}${BOLD}==>${NC} ${BOLD}$1${NC}"
}

print_banner() {
    echo -e "${CYAN}${BOLD}"
    cat << "EOF"
╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║   ███████╗██╗      █████╗  ██████╗                          ║
║   ██╔════╝██║     ██╔══██╗██╔════╝                          ║
║   ███████╗██║     ███████║██║  ███╗                         ║
║   ╚════██║██║     ██╔══██║██║   ██║                         ║
║   ███████║███████╗██║  ██║╚██████╔╝                         ║
║   ╚══════╝╚══════╝╚═╝  ╚═╝ ╚═════╝                          ║
║                                                               ║
║          ███████╗██╗  ██╗███████╗███╗   ██╗                  ║
║          ██╔════╝╚██╗██╔╝██╔════╝████╗  ██║                  ║
║          █████╗   ╚███╔╝ █████╗  ██╔██╗ ██║                  ║
║          ██╔══╝   ██╔██╗ ██╔══╝  ██║╚██╗██║                  ║
║          ███████╗██║██╗██║███████╗██║ ╚████║                  ║
║          ╚══════╝╚═╝╚═╝╚═╝╚══════╝╚═╝  ╚═══╝                  ║
║                                                               ║
║                   Ultimate Installation Script               ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
}

check_claude_code() {
    log_step "Checking for Claude Code installation..."

    if ! command -v claude &> /dev/null; then
        log_warn "Claude Code CLI not found!"
        echo ""
        echo -e "${YELLOW}Claude Code is required to use these customizations.${NC}"
        echo ""
        echo "Options:"
        echo "  1. Install Claude Code with Z.AI API support (recommended)"
        echo "  2. Install manually later"
        echo "  3. Exit to install first"
        echo ""
        read -p "Choose option [1/2/3]: " -n 1 -r choice
        echo ""

        case $choice in
            1)
                log_info "Running Claude Code installer..."
                bash "$SCRIPT_DIR/install-claude-code.sh" --auto
                if ! command -v claude &> /dev/null; then
                    log_error "Claude Code installation failed. Please install manually."
                    exit 1
                fi
                log_success "Claude Code installed successfully"
                ;;
            2)
                log_warn "Skipping Claude Code installation"
                log_info "You can install it later with: ./install-claude-code.sh"
                return 1
                ;;
            3)
                log_info "Please install Claude Code first:"
                echo "  npm install -g @anthropic-ai/claude-code"
                echo "  Or run: ./install-claude-code.sh"
                exit 1
                ;;
            *)
                log_error "Invalid choice"
                exit 1
                ;;
        esac
    fi

    log_success "Claude Code found: $(claude --version 2>/dev/null || echo 'installed')"
    return 0
}

backup_existing_config() {
    log_step "Backing up existing configuration..."

    if [ -d "$CLAUDE_DIR" ]; then
        mkdir -p "$BACKUP_DIR"
        cp -r "$CLAUDE_DIR" "$BACKUP_DIR/"
        log_success "Backup created at: $BACKUP_DIR"
    else
        log_info "No existing configuration to backup"
    fi
}

install_dependencies() {
    if [ "$SKIP_DEPS" = true ]; then
        log_warn "Skipping dependency installation"
        return
    fi

    log_step "Checking and installing dependencies..."

    # Check Python 3
    if ! command -v python3 &> /dev/null; then
        log_warn "Python 3 not found. Some features may not work."
    else
        log_success "Python 3 found: $(python3 --version)"
    fi

    # Check Node.js
    if ! command -v node &> /dev/null; then
        log_warn "Node.js not found. Some features may not work."
    else
        log_success "Node.js found: $(node --version)"
    fi

    # Check Git
    if ! command -v git &> /dev/null; then
        log_error "Git not found. Please install Git first."
        exit 1
    else
        log_success "Git found: $(git --version)"
    fi

    # Install Ralph Orchestrator (Python package for /ralph autonomous agent)
    RALPH_INSTALLED=false

    # Check if ralph command exists
    if command -v ralph &> /dev/null; then
        log_success "Ralph Orchestrator found: $(ralph --version 2>/dev/null || echo 'installed')"
        RALPH_INSTALLED=true
    fi

    # Check if Python package is installed
    if python3 -c "import ralph_orchestrator" 2>/dev/null; then
        if [ "$RALPH_INSTALLED" = false ]; then
            log_success "Ralph Orchestrator Python package found"
            RALPH_INSTALLED=true
        fi
    fi

    # Install if not found
    if [ "$RALPH_INSTALLED" = false ]; then
        log_info "Installing Ralph Orchestrator..."
        if command -v pip3 &> /dev/null; then
            # Try installing from requirements.txt if it exists in script dir
            if [ -f "$SCRIPT_DIR/requirements.txt" ]; then
                log_info "Installing from requirements.txt..."
                pip3 install -r "$SCRIPT_DIR/requirements.txt" 2>/dev/null && {
                    log_success "Ralph Orchestrator installed from requirements.txt"
                } || {
                    # Fallback to direct install
                    log_warn "requirements.txt install failed, trying direct install..."
                    pip3 install ralph-orchestrator pyyaml 2>/dev/null || {
                        log_error "Failed to install Ralph Orchestrator"
                        echo ""
                        echo -e "${YELLOW}Ralph Orchestrator is required for /ralph command${NC}"
                        echo "Install manually:"
                        echo "  pip3 install ralph-orchestrator"
                        echo ""
                        echo "The /ralph command will not work without it."
                    }
                }
            else
                # Direct install
                pip3 install ralph-orchestrator pyyaml 2>/dev/null && {
                    log_success "Ralph Orchestrator installed"
                } || {
                    log_warn "Failed to install Ralph Orchestrator"
                }
            fi
        else
            log_warn "pip3 not found. Skipping Ralph Orchestrator installation."
            echo ""
            echo -e "${YELLOW}Install pip3 first:${NC}"
            echo "  sudo apt-get install python3-pip"
            echo "  Then: pip3 install ralph-orchestrator"
        fi
    fi

    # Verify installation
    if command -v ralph &> /dev/null || python3 -c "import ralph_orchestrator" 2>/dev/null; then
        log_success "Ralph Orchestrator ready for /ralph command"
    else
        log_warn "Ralph Orchestrator not available - /ralph command will use fallback mode"
    fi
}

install_skills() {
    log_step "Installing custom skills..."

    mkdir -p "$CLAUDE_DIR/skills"

    # Copy all skills
    if [ -d "$SCRIPT_DIR/skills" ]; then
        cp -r "$SCRIPT_DIR/skills/"* "$CLAUDE_DIR/skills/" 2>/dev/null || true
        local skill_count=$(find "$SCRIPT_DIR/skills" -name "SKILL.md" | wc -l)
        log_success "Installed $skill_count custom skills"
    else
        log_warn "Skills directory not found"
    fi
}

install_agents() {
    log_step "Installing agent management system..."

    mkdir -p "$CLAUDE_DIR/agents"

    if [ -d "$SCRIPT_DIR/agents" ]; then
        cp -r "$SCRIPT_DIR/agents/"* "$CLAUDE_DIR/agents/" 2>/dev/null || true
        log_success "Agent management system installed"

        # Make scripts executable
        find "$CLAUDE_DIR/agents" -name "*.sh" -exec chmod +x {} \;
    else
        log_warn "Agents directory not found"
    fi
}

install_hooks() {
    log_step "Installing custom hooks..."

    mkdir -p "$CLAUDE_DIR/hooks"

    if [ -d "$SCRIPT_DIR/hooks" ]; then
        cp -r "$SCRIPT_DIR/hooks/"* "$CLAUDE_DIR/hooks/" 2>/dev/null || true

        # Make hook scripts executable
        find "$CLAUDE_DIR/hooks" -name "*.sh" -exec chmod +x {} \;

        log_success "Custom hooks installed"
    else
        log_warn "Hooks directory not found"
    fi

    # Install hooks.json if it doesn't exist
    if [ -f "$SCRIPT_DIR/templates/hooks.json" ] && [ ! -f "$CLAUDE_DIR/hooks.json" ]; then
        cp "$SCRIPT_DIR/templates/hooks.json" "$CLAUDE_DIR/hooks.json"
        log_success "Hooks configuration installed"
    fi
}

install_commands() {
    log_step "Installing custom commands..."

    mkdir -p "$CLAUDE_DIR/commands"

    if [ -d "$SCRIPT_DIR/commands" ]; then
        cp -r "$SCRIPT_DIR/commands/"* "$CLAUDE_DIR/commands/" 2>/dev/null || true
        local cmd_count=$(ls -1 "$SCRIPT_DIR/commands" 2>/dev/null | wc -l)
        log_success "Installed $cmd_count custom commands"
    else
        log_warn "Commands directory not found"
    fi
}

install_plugins() {
    log_step "Installing plugin references..."

    mkdir -p "$CLAUDE_DIR/plugins"

    if [ -d "$SCRIPT_DIR/plugins" ]; then
        cp -r "$SCRIPT_DIR/plugins/"* "$CLAUDE_DIR/plugins/" 2>/dev/null || true
        local plugin_count=$(find "$SCRIPT_DIR/plugins" -type d -mindepth 1 | wc -l)
        log_success "Installed $plugin_count plugin references"
    else
        log_warn "Plugins directory not found"
    fi
}

install_binaries() {
    log_step "Installing custom binaries..."

    mkdir -p "$HOME/.local/bin"

    if [ -f "$SCRIPT_DIR/bin/ralphloop" ]; then
        cp "$SCRIPT_DIR/bin/ralphloop" "$HOME/.local/bin/"
        chmod +x "$HOME/.local/bin/ralphloop"

        # Add to PATH if not already there
        if ! echo "$PATH" | grep -q "$HOME/.local/bin"; then
            echo "" >> "$HOME/.bashrc"
            echo "# SuperCharge Claude Code - Add local bin to PATH" >> "$HOME/.bashrc"
            echo "export PATH=\"\$HOME/.local/bin:\$PATH\"" >> "$HOME/.bashrc"
            log_info "Added ~/.local/bin to PATH in .bashrc"
        fi

        log_success "RalphLoop wrapper installed"
    else
        log_warn "RalphLoop binary not found"
    fi
}

install_scripts() {
    log_step "Installing utility scripts..."

    mkdir -p "$CLAUDE_DIR/scripts"

    if [ -d "$SCRIPT_DIR/scripts" ]; then
        cp -r "$SCRIPT_DIR/scripts/"* "$CLAUDE_DIR/scripts/" 2>/dev/null || true

        # Make scripts executable
        find "$CLAUDE_DIR/scripts" -name "*.sh" -exec chmod +x {} \;

        log_success "Utility scripts installed"
    else
        log_warn "Scripts directory not found"
    fi
}

install_config_templates() {
    log_step "Installing configuration templates..."

    if [ -d "$SCRIPT_DIR/templates" ]; then
        # Install config.json if not exists
        if [ -f "$SCRIPT_DIR/templates/config.json" ] && [ ! -f "$CLAUDE_DIR/config.json" ]; then
            cp "$SCRIPT_DIR/templates/config.json" "$CLAUDE_DIR/config.json"
            log_success "config.json installed"
        fi

        # Merge settings.json
        if [ -f "$SCRIPT_DIR/templates/settings.json" ]; then
            if [ -f "$CLAUDE_DIR/settings.json" ]; then
                # Merge existing settings with template
                local temp_file=$(mktemp)
                python3 -c "
import json
import sys

try:
    with open('$CLAUDE_DIR/settings.json', 'r') as f:
        existing = json.load(f)
except:
    existing = {}

try:
    with open('$SCRIPT_DIR/templates/settings.json', 'r') as f:
        template = json.load(f)
except:
    template = {}

# Merge: template values take precedence for keys that exist in template
for key in template:
    if key != 'permissions':  # Don't override permissions
        existing[key] = template[key]

with open('$temp_file', 'w') as f:
    json.dump(existing, f, indent=2)
" 2>/dev/null || cp "$SCRIPT_DIR/templates/settings.json" "$temp_file"
                mv "$temp_file" "$CLAUDE_DIR/settings.json"
            else
                cp "$SCRIPT_DIR/templates/settings.json" "$CLAUDE_DIR/settings.json"
            fi
            log_success "settings.json configured"
        fi

        # Install settings.local.json if not exists
        if [ -f "$SCRIPT_DIR/templates/settings.local.json" ] && [ ! -f "$CLAUDE_DIR/settings.local.json" ]; then
            cp "$SCRIPT_DIR/templates/settings.local.json" "$CLAUDE_DIR/settings.local.json"
            log_success "settings.local.json installed"
        fi
    fi
}

sync_agents() {
    log_step "Syncing agents from repository..."

    if [ -f "$CLAUDE_DIR/scripts/sync-agents.sh" ]; then
        bash "$CLAUDE_DIR/scripts/sync-agents.sh" 2>/dev/null || log_warn "Agent sync completed with warnings"
        log_success "Agent sync completed"
    else
        log_warn "sync-agents.sh not found"
    fi
}

print_summary() {
    echo ""
    echo -e "${GREEN}${BOLD}╔═══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}${BOLD}║                   INSTALLATION COMPLETE!                       ║${NC}"
    echo -e "${GREEN}${BOLD}╚═══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "${BOLD}Your Claude Code installation is now SUPERCHARGED!${NC}"
    echo ""
    echo -e "${CYAN}Installed Features:${NC}"
    echo -e "  ${GREEN}✓${NC} 30+ Custom Skills (cognitive, development, UI/UX)"
    echo -e "  ${GREEN}✓${NC} RalphLoop Autonomous Agent Integration"
    echo -e "  ${GREEN}✓${NC} Multi-AI Consultation (Qwen)"
    echo -e "  ${GREEN}✓${NC} Agent Management System"
    echo -e "  ${GREEN}✓${NC} Custom Hooks & Commands"
    echo -e "  ${GREEN}✓${NC} Plugin Marketplace Setup"
    echo ""
    echo -e "${CYAN}New Commands Available:${NC}"
    echo -e "  ${YELLOW}/ralph${NC}      - Autonomous \"Tackle Until Solved\" agent"
    echo -e "  ${YELLOW}/brainstorm${NC} - Multi-AI brainstorming session"
    echo -e "  ${YELLOW}/write-plan${NC} - Create implementation plans"
    echo -e "  ${YELLOW}/execute-plan${NC} - Execute written plans"
    echo ""
    echo -e "${CYAN}Quick Start:${NC}"
    echo -e "  1. Restart your terminal or run: ${YELLOW}source ~/.bashrc${NC}"
    echo -e "  2. Run Claude Code: ${YELLOW}claude${NC}"
    echo -e "  3. Try: ${YELLOW}/ralph \"Design a microservices architecture\"${NC}"
    echo ""
    echo -e "${CYAN}Configuration:${NC}"
    echo -e "  Config dir: ${YELLOW}$CLAUDE_DIR${NC}"
    echo -e "  Backup:     ${YELLOW}$BACKUP_DIR${NC}"
    echo ""
    echo -e "${CYAN}Optional Configuration:${NC}"
    echo -e "  ${YELLOW}export RALPH_AGENT=claude${NC}     # Set Ralph agent"
    echo -e "  ${YELLOW}export RALPH_MAX_ITERATIONS=100${NC} # Set max iterations"
    echo -e "  ${YELLOW}export QWEN_CONSULT_MODE=always${NC}  # Qwen consultation mode"
    echo ""
    echo -e "${GREEN}${BOLD}Enjoy your supercharged Claude Code experience!${NC}"
    echo ""
}

################################################################################
# Main Installation
################################################################################

main() {
    print_banner

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --skip-deps)
                SKIP_DEPS=true
                shift
                ;;
            --dev-mode)
                DEV_MODE=true
                set -x
                shift
                ;;
            -h|--help)
                echo "Usage: $0 [options]"
                echo "  --skip-deps    Skip dependency installation"
                echo "  --dev-mode     Development mode (verbose output)"
                exit 0
                ;;
            *)
                log_error "Unknown option: $1"
                exit 1
                ;;
        esac
    done

    # Run installation steps
    if ! check_claude_code; then
        log_info "Customizations installed. Install Claude Code to use them."
        echo ""
        echo -e "${CYAN}Install Claude Code:${NC}"
        echo "  npm install -g @anthropic-ai/claude-code"
        echo "  Or run: ./install-claude-code.sh"
        echo ""
        exit 0
    fi
    backup_existing_config
    install_dependencies
    install_skills
    install_agents
    install_hooks
    install_commands
    install_plugins
    install_binaries
    install_scripts
    install_config_templates
    sync_agents

    print_summary
}

# Run main function
main "$@"
