#!/bin/bash

# Claude Code Subagents Orchestrator - Installation Script
# Cross-platform installation for macOS and Linux (including WSL2)

set -e

# Configuration
PACKAGE_NAME="claude-code-subagents-orchestrator"
PACKAGE_VERSION="latest"
REPO_URL="https://github.com/anthropic/claude-code-subagents-orchestrator"
MIN_NODE_VERSION="18.0.0"

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

# Logging 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"
}

# Utility functions
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

version_gte() {
    printf '%s\n%s\n' "$2" "$1" | sort -V -C
}

# Platform detection
detect_platform() {
    local platform
    case "$(uname -s)" in
        Darwin*) platform="macOS" ;;
        Linux*)
            if [[ -n "$WSL_DISTRO_NAME" || -n "$WSL_INTEROP" ]]; then
                platform="WSL2"
            else
                platform="Linux"
            fi
            ;;
        CYGWIN*|MINGW*|MSYS*) platform="Windows" ;;
        *) platform="Unknown" ;;
    esac
    echo "$platform"
}

# Check system requirements
check_requirements() {
    log_info "Checking system requirements..."
    
    # Check Node.js
    if ! command_exists node; then
        log_error "Node.js is not installed. Please install Node.js $MIN_NODE_VERSION or higher."
        log_info "Visit: https://nodejs.org/en/download/"
        exit 1
    fi
    
    local node_version=$(node --version | sed 's/v//')
    if ! version_gte "$node_version" "$MIN_NODE_VERSION"; then
        log_error "Node.js version $node_version is too old. Please upgrade to $MIN_NODE_VERSION or higher."
        exit 1
    fi
    
    log_success "Node.js $node_version found"
    
    # Check npm
    if ! command_exists npm; then
        log_error "npm is not installed. Please install npm."
        exit 1
    fi
    
    local npm_version=$(npm --version)
    log_success "npm $npm_version found"
    
    # Check Claude Code (optional but recommended)
    check_claude_code
}

check_claude_code() {
    local platform=$(detect_platform)
    local claude_config_dir
    
    case "$platform" in
        "macOS")
            claude_config_dir="$HOME/Library/Application Support/Claude"
            ;;
        "Linux"|"WSL2")
            claude_config_dir="$HOME/.config/claude"
            ;;
        *)
            log_warning "Unable to detect Claude Code installation on this platform"
            return
            ;;
    esac
    
    if [[ -d "$claude_config_dir" ]]; then
        log_success "Claude Code configuration directory found"
    else
        log_warning "Claude Code not found. Install it at: https://claude.ai/code"
        log_warning "You can still install the orchestrator, but MCP integration won't work until Claude Code is installed."
    fi
}

# Installation methods
install_via_npm() {
    log_info "Installing $PACKAGE_NAME via npm..."
    
    if [[ "$PACKAGE_VERSION" == "latest" ]]; then
        npm install -g "$PACKAGE_NAME"
    else
        npm install -g "$PACKAGE_NAME@$PACKAGE_VERSION"
    fi
    
    log_success "Package installed successfully"
}

install_via_git() {
    log_info "Installing from source..."
    
    local temp_dir=$(mktemp -d)
    log_info "Cloning repository to $temp_dir"
    
    git clone "$REPO_URL" "$temp_dir"
    cd "$temp_dir"
    
    log_info "Installing dependencies..."
    npm ci
    
    log_info "Building project..."
    npm run build
    
    log_info "Installing globally..."
    npm install -g .
    
    cd - > /dev/null
    rm -rf "$temp_dir"
    
    log_success "Installation from source completed"
}

# Post-installation setup
post_install_setup() {
    log_info "Running post-installation setup..."
    
    # Verify installation
    if ! command_exists claude-orchestrator; then
        log_error "Installation verification failed. claude-orchestrator command not found."
        exit 1
    fi
    
    log_success "Installation verified"
    
    # Initialize MCP configuration
    log_info "Initializing MCP configuration..."
    if claude-orchestrator init --auto; then
        log_success "MCP configuration initialized"
    else
        log_warning "MCP configuration failed. You may need to run 'claude-orchestrator init' manually."
    fi
    
    # Set up completions (optional)
    setup_completions
}

setup_completions() {
    local shell_name=$(basename "$SHELL")
    
    case "$shell_name" in
        "bash")
            if [[ -f "$HOME/.bashrc" ]]; then
                echo 'eval "$(claude-orchestrator completion bash)"' >> "$HOME/.bashrc"
                log_info "Bash completions added to ~/.bashrc"
            fi
            ;;
        "zsh")
            if [[ -f "$HOME/.zshrc" ]]; then
                echo 'eval "$(claude-orchestrator completion zsh)"' >> "$HOME/.zshrc"
                log_info "Zsh completions added to ~/.zshrc"
            fi
            ;;
        "fish")
            local fish_config_dir="$HOME/.config/fish"
            if [[ -d "$fish_config_dir" ]]; then
                mkdir -p "$fish_config_dir/completions"
                claude-orchestrator completion fish > "$fish_config_dir/completions/claude-orchestrator.fish"
                log_info "Fish completions installed"
            fi
            ;;
    esac
}

# Health check
run_health_check() {
    log_info "Running health check..."
    
    if claude-orchestrator health-check; then
        log_success "Health check passed"
    else
        log_warning "Health check failed. Some features may not work correctly."
        log_info "Run 'claude-orchestrator health-check --verbose' for detailed diagnostics."
    fi
}

# Uninstallation
uninstall() {
    log_info "Uninstalling $PACKAGE_NAME..."
    
    if command_exists claude-orchestrator; then
        # Run cleanup
        claude-orchestrator cleanup --all 2>/dev/null || true
    fi
    
    # Remove global package
    npm uninstall -g "$PACKAGE_NAME" 2>/dev/null || true
    
    # Remove completions
    local shell_name=$(basename "$SHELL")
    case "$shell_name" in
        "bash")
            if [[ -f "$HOME/.bashrc" ]]; then
                sed -i '/claude-orchestrator completion bash/d' "$HOME/.bashrc"
            fi
            ;;
        "zsh")
            if [[ -f "$HOME/.zshrc" ]]; then
                sed -i '/claude-orchestrator completion zsh/d' "$HOME/.zshrc"
            fi
            ;;
        "fish")
            rm -f "$HOME/.config/fish/completions/claude-orchestrator.fish"
            ;;
    esac
    
    log_success "Uninstallation completed"
}

# Update function
update() {
    log_info "Updating $PACKAGE_NAME..."
    
    local current_version
    if command_exists claude-orchestrator; then
        current_version=$(claude-orchestrator --version 2>/dev/null | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "unknown")
        log_info "Current version: $current_version"
    fi
    
    npm update -g "$PACKAGE_NAME"
    
    local new_version
    if command_exists claude-orchestrator; then
        new_version=$(claude-orchestrator --version 2>/dev/null | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "unknown")
        log_success "Updated to version: $new_version"
    fi
    
    # Run health check after update
    run_health_check
}

# Main installation function
main() {
    local action="${1:-install}"
    local install_method="${2:-npm}"
    
    echo "================================================"
    echo "Claude Code Subagents Orchestrator Installation"
    echo "Platform: $(detect_platform)"
    echo "Action: $action"
    echo "================================================"
    echo
    
    case "$action" in
        "install")
            check_requirements
            
            case "$install_method" in
                "npm")
                    install_via_npm
                    ;;
                "git"|"source")
                    if ! command_exists git; then
                        log_error "Git is required for source installation"
                        exit 1
                    fi
                    install_via_git
                    ;;
                *)
                    log_error "Unknown installation method: $install_method"
                    exit 1
                    ;;
            esac
            
            post_install_setup
            run_health_check
            
            echo
            log_success "Installation completed successfully!"
            echo
            echo "Next steps:"
            echo "1. Restart your terminal or run: source ~/.bashrc (or ~/.zshrc)"
            echo "2. Run: claude-orchestrator --help"
            echo "3. Initialize your project: claude-orchestrator init"
            echo
            ;;
        "uninstall")
            uninstall
            ;;
        "update")
            update
            ;;
        "health-check"|"check")
            if command_exists claude-orchestrator; then
                run_health_check
            else
                log_error "$PACKAGE_NAME is not installed"
                exit 1
            fi
            ;;
        *)
            echo "Usage: $0 [install|uninstall|update|health-check] [npm|git]"
            echo
            echo "Actions:"
            echo "  install      Install the orchestrator (default)"
            echo "  uninstall    Remove the orchestrator"
            echo "  update       Update to the latest version"
            echo "  health-check Check installation health"
            echo
            echo "Install methods:"
            echo "  npm          Install from npm registry (default)"
            echo "  git          Install from source"
            echo
            echo "Examples:"
            echo "  $0                           # Install via npm"
            echo "  $0 install git              # Install from source"
            echo "  $0 update                   # Update to latest"
            echo "  $0 uninstall                # Remove installation"
            exit 1
            ;;
    esac
}

# Handle interruption
trap 'echo; log_error "Installation interrupted"; exit 1' INT TERM

# Run main function with all arguments
main "$@"