#!/usr/bin/env bash
################################################################################
# Claude Code Customizations Installer
# This script automates the setup of custom agents, MCP tools, and plugins
# for Claude Code on a new machine.
################################################################################

set -e  # Exit on error

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

# Configuration
CLAUDE_DIR="$HOME/.claude"
AGENTS_DIR="$CLAUDE_DIR/agents"
PLUGINS_DIR="$CLAUDE_DIR/plugins"
BACKUP_DIR="$HOME/.claude-backup-$(date +%Y%m%d_%H%M%S)"

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

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

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

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 is not installed. Please install it first."
        exit 1
    fi
}

backup_file() {
    local file="$1"
    if [ -f "$file" ]; then
        mkdir -p "$BACKUP_DIR"
        cp "$file" "$BACKUP_DIR/"
        log_info "Backed up $file to $BACKUP_DIR"
    fi
}

################################################################################
# Prerequisites Check
################################################################################

check_prerequisites() {
    log_info "Checking prerequisites..."

    check_command "node"
    check_command "npm"
    check_command "python3"
    check_command "curl"

    # Check Node.js version (need 14+)
    NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_VERSION" -lt 14 ]; then
        log_error "Node.js version 14 or higher required. Current: $(node -v)"
        exit 1
    fi

    log_success "Prerequisites check passed"
}

################################################################################
# Directory Structure Setup
################################################################################

setup_directories() {
    log_info "Setting up directory structure..."

    mkdir -p "$AGENTS_DIR"/{engineering,marketing,product,studio-operations,project-management,testing,design,bonus}

    mkdir -p "$PLUGINS_DIR"/{cache,marketplaces}
    mkdir -p "$CLAUDE_DIR"/{hooks,debug,file-history,paste-cache,projects,session-env,shell-snapshots,todos}

    log_success "Directory structure created"
}

################################################################################
# Settings Configuration
################################################################################

setup_settings() {
    log_info "Configuring Claude Code settings..."

    local settings_file="$CLAUDE_DIR/settings.json"

    backup_file "$settings_file"

    # Prompt for API credentials
    read -p "Enter your ANTHROPIC_AUTH_TOKEN (or press Enter to skip): " API_TOKEN
    read -p "Enter your ANTHROPIC_BASE_URL (default: https://api.anthropic.com): " API_BASE
    API_BASE=${API_BASE:-https://api.anthropic.com}

    # Create settings.json
    cat > "$settings_file" << EOF
{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "${API_TOKEN}",
    "ANTHROPIC_BASE_URL": "${API_BASE}",
    "API_TIMEOUT_MS": "3000000",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
  },
  "enabledPlugins": {
    "glm-plan-bug@zai-coding-plugins": true,
    "glm-plan-usage@zai-coding-plugins": true
  }
}
EOF

    # Create local settings for permissions
    local local_settings="$CLAUDE_DIR/settings.local.json"
    backup_file "$local_settings"

    cat > "$local_settings" << EOF
{
  "permissions": {
    "allow": [
      "Bash(npm install:*)",
      "Bash(npm run content:*)",
      "Bash(npm run build:*)",
      "Bash(grep:*)",
      "Bash(find:*)",
      "Bash(for:*)",
      "Bash(do sed:*)",
      "Bash(done)",
      "Bash(python3:*)",
      "Bash(while read f)",
      "Bash(do echo \\"\\$f%-* \\$f\\")",
      "Bash(ls:*)",
      "Bash(node:*)",
      "Bash(pm2 delete:*)",
      "Bash(pm2 start npm:*)",
      "Bash(pm2 save:*)"
    ]
  }
}
EOF

    log_success "Settings configured"
}

################################################################################
# MCP Services Installation
################################################################################

install_mcp_services() {
    log_info "Installing MCP services..."

    # Install @z_ai/mcp-server globally for vision tools
    log_info "Installing @z_ai/mcp-server (vision analysis tools)..."
    npm install -g @z_ai/mcp-server 2>/dev/null || {
        log_warning "Global install failed, trying with npx..."
        # It's okay if this fails, the tools will use npx
    }

    # Install @z_ai/coding-helper for MCP management
    log_info "Installing @z_ai/coding-helper..."
    npm install -g @z_ai/coding-helper 2>/dev/null || {
        log_warning "Global install failed, will use npx"
    }

    log_success "MCP services installation completed"
}

################################################################################
# Agent Definitions
################################################################################

install_agents() {
    log_info "Installing custom agents..."

    # Note: In a production setup, these would be downloaded from a repository
    # For now, we'll create placeholder agent definitions
    # The actual agent content should be copied from the source machine

    log_info "Agent directory structure created at $AGENTS_DIR"
    log_warning "NOTE: You need to copy the actual agent .md files from the source machine"
    log_info "Run: scp -r user@source:~/.claude/agents/* $AGENTS_DIR/"

    log_success "Agent structure ready"
}

################################################################################
# Plugins Installation
################################################################################

install_plugins() {
    log_info "Installing Claude Code plugins..."

    # Initialize plugin registry
    local installed_plugins="$PLUGINS_DIR/installed_plugins.json"
    local known_marketplaces="$PLUGINS_DIR/known_marketplaces.json"

    backup_file "$installed_plugins"
    backup_file "$known_marketplaces"

    cat > "$known_marketplaces" << EOF
{
  "marketplaces": {
    "https://github.com/anthropics/claude-plugins": {
      "displayName": "Official Claude Plugins",
      "contact": "support@anthropic.com"
    }
  }
}
EOF

    # Install GLM plugins via npx
    log_info "Installing GLM Coding Plan plugins..."

    # Create plugin cache structure
    mkdir -p "$PLUGINS_DIR/cache/zai-coding-plugins"/{glm-plan-bug,glm-plan-usage}

    # Note: Actual plugin installation happens via the @z_ai/coding-helper
    # which should already be installed

    cat > "$installed_plugins" << EOF
{
  "version": 2,
  "plugins": {
    "glm-plan-bug@zai-coding-plugins": [
      {
        "scope": "user",
        "installPath": "$PLUGINS_DIR/cache/zai-coding-plugins/glm-plan-bug/0.0.1",
        "version": "0.0.1",
        "installedAt": "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)",
        "lastUpdated": "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
      }
    ],
    "glm-plan-usage@zai-coding-plugins": [
      {
        "scope": "user",
        "installPath": "$PLUGINS_DIR/cache/zai-coding-plugins/glm-plan-usage/0.0.1",
        "version": "0.0.1",
        "installedAt": "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)",
        "lastUpdated": "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
      }
    ]
  }
}
EOF

    log_success "Plugins configured"
}

################################################################################
# Download Agents from Repository
################################################################################

download_agent_definitions() {
    log_info "Preparing to download agent definitions..."

    # Create a temporary script to download agents
    # In production, this would download from a git repository or CDN

    cat > /tmp/download_agents.sh << 'DOWNLOAD_SCRIPT'
#!/bin/bash
# This script would download agent definitions from a central repository
# For now, it creates a template structure

AGENT_CATEGORIES=("engineering" "marketing" "product" "studio-operations" "project-management" "testing" "design" "bonus")

for category in "${AGENT_CATEGORIES[@]}"; do
    echo "Category: $category"
    # Agents would be downloaded here
done
DOWNLOAD_SCRIPT

    chmod +x /tmp/download_agents.sh

    log_info "Agent download script created at /tmp/download_agents.sh"
    log_warning "You need to provide the actual agent definitions"
}

################################################################################
# Verification
################################################################################

verify_installation() {
    log_info "Verifying installation..."

    local errors=0

    # Check directories
    [ -d "$CLAUDE_DIR" ] || { log_error "Claude directory missing"; errors=$((errors+1)); }
    [ -d "$AGENTS_DIR" ] || { log_error "Agents directory missing"; errors=$((errors+1)); }
    [ -d "$PLUGINS_DIR" ] || { log_error "Plugins directory missing"; errors=$((errors+1)); }

    # Check files
    [ -f "$CLAUDE_DIR/settings.json" ] || { log_error "settings.json missing"; errors=$((errors+1)); }
    [ -f "$CLAUDE_DIR/settings.local.json" ] || { log_error "settings.local.json missing"; errors=$((errors+1)); }
    [ -f "$PLUGINS_DIR/installed_plugins.json" ] || { log_error "installed_plugins.json missing"; errors=$((errors+1)); }

    # Check MCP availability
    if command -v npx &> /dev/null; then
        log_success "npx available for MCP tools"
    else
        log_error "npx not available"
        errors=$((errors+1))
    fi

    if [ $errors -eq 0 ]; then
        log_success "Installation verification passed"
        return 0
    else
        log_error "Installation verification failed with $errors errors"
        return 1
    fi
}

################################################################################
# Main Installation Flow
################################################################################

main() {
    echo -e "${BLUE}╔════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║   Claude Code Customizations - Automated Installer        ║${NC}"
    echo -e "${BLUE}╚════════════════════════════════════════════════════════════╝${NC}"
    echo ""

    # Parse command line arguments
    SKIP_AGENTS_COPY=false
    while [[ $# -gt 0 ]]; do
        case $1 in
            --skip-agents)
                SKIP_AGENTS_COPY=true
                shift
                ;;
            --help)
                echo "Usage: $0 [OPTIONS]"
                echo ""
                echo "Options:"
                echo "  --skip-agents    Skip copying agent files (if already present)"
                echo "  --help           Show this help message"
                echo ""
                exit 0
                ;;
            *)
                log_error "Unknown option: $1"
                echo "Use --help for usage information"
                exit 1
                ;;
        esac
    done

    # Run installation steps
    check_prerequisites
    setup_directories
    setup_settings
    install_mcp_services
    install_agents
    install_plugins

    # Verify installation
    if verify_installation; then
        echo ""
        log_success "═══════════════════════════════════════════════════════════"
        log_success "Installation completed successfully!"
        log_success "═══════════════════════════════════════════════════════════"
        echo ""
        log_info "Next steps:"
        echo "  1. Copy agent definitions from source machine:"
        echo "     scp -r user@source:~/.claude/agents/* $AGENTS_DIR/"
        echo ""
        echo "  2. Restart Claude Code to load all customizations"
        echo ""
        echo "  3. Verify MCP tools are working by starting a new session"
        echo ""
        echo "Backup location: $BACKUP_DIR"
        echo ""
    else
        log_error "Installation failed. Please check the errors above."
        exit 1
    fi
}

# Run main function
main "$@"
