#!/bin/bash

set -e  

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

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

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

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

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


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


validate_url() {
    local url="$1"
    if [[ $url =~ ^https?:// ]]; then
        return 0
    else
        return 1
    fi
}


show_usage() {
    echo "Usage: $0 SERVER_URL"
    echo
    echo "Arguments:"
    echo "  SERVER_URL    Required. The MCP server URL to configure"
    echo
    echo "Environment Variables:"
    echo "  MCP_SERVER_URL    The MCP server URL to configure"
    echo
    echo "Examples:"
    echo "  $0 https://my-server.example.com/stream"
    echo "  MCP_SERVER_URL=https://my-server.example.com/stream $0"
    echo
    echo "Options:"
    echo "  -h, --help    Show this help message"
}


parse_arguments() {
    # Check for help flag
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        show_usage
        exit 0
    fi
    
    if [[ -n "$1" ]]; then
        SERVER_URL="$1"
    elif [[ -n "$MCP_SERVER_URL" ]]; then
        SERVER_URL="$MCP_SERVER_URL"
    else
        print_error "Server URL is required"
        print_error "Provide it as an argument or set MCP_SERVER_URL environment variable"
        echo
        show_usage
        exit 1
    fi
    

    if ! validate_url "$SERVER_URL"; then
        print_error "Invalid URL format: $SERVER_URL"
        print_error "URL must start with http:// or https://"
        exit 1
    fi
    
    print_status "Using server URL: $SERVER_URL"
}


install_homebrew() {
    print_status "Checking for Homebrew installation..."
    
    if command_exists brew; then
        print_success "Homebrew is already installed"
        return 0
    fi
    
    print_status "Installing Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
    if [[ $(uname -m) == "arm64" ]]; then
        echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
        eval "$(/opt/homebrew/bin/brew shellenv)"
    fi
    
    print_success "Homebrew installed successfully"
}

install_node_npm() {
    print_status "Checking for Node.js and npm installation..."
    
    if command_exists node && command_exists npm; then
        print_success "Node.js and npm are already installed"
        node_version=$(node --version)
        npm_version=$(npm --version)
        print_status "Node.js version: $node_version"
        print_status "npm version: $npm_version"
        return 0
    fi
    
    print_status "Installing Node.js and npm via Homebrew..."
    brew install node
    
    print_success "Node.js and npm installed successfully"
    node_version=$(node --version)
    npm_version=$(npm --version)
    print_status "Node.js version: $node_version"
    print_status "npm version: $npm_version"
}

install_jq() {
    print_status "Checking for jq installation..."
    
    if command_exists jq; then
        print_success "jq is already installed"
        return 0
    fi
    
    print_status "Installing jq..."
    brew install jq
    print_success "jq installed successfully"
}

create_mcp_config() {
    print_status "Updating Claude Desktop configuration..."
    
    local config_dir
    local config_file
    if [[ "$OSTYPE" == "darwin"* ]]; then
        config_dir="$HOME/Library/Application Support/Claude"
        config_file="$config_dir/claude_desktop_config.json"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        config_dir="$HOME/.config/claude"
        config_file="$config_dir/claude_desktop_config.json"
    else
        print_error "Unsupported operating system: $OSTYPE"
        exit 1
    fi
    
    if [[ "$OSTYPE" == "darwin"* ]]; then
        if [[ ! -d "/Applications/Claude.app" && ! -d "$HOME/Applications/Claude.app" ]]; then
            print_warning "Claude Desktop not found in /Applications or ~/Applications. Config will be written, but install/launch Claude to use it."
        fi
    fi
    
    mkdir -p "$config_dir"
    
    if [[ ! -f "$config_file" ]]; then
        echo '{"mcpServers":{}}' > "$config_file"
        print_status "Created initial config file"
    fi
    
    if [[ -f "$config_file" ]]; then
        cp "$config_file" "$config_file.bak.$(date +%Y%m%d%H%M%S)"
        print_status "Created backup of existing config"
    fi
    
    local tmp_file=$(mktemp)
    local server_key="blotout-athena-api-mcp-service-remote-mcp"
    local server_url="$SERVER_URL"
    
    jq --arg key "$server_key" \
       --arg cmd "npx" \
       --arg url "$server_url" \
       '(.mcpServers //= {})
        | (.mcpServers[$key] //= {})
        | .mcpServers[$key].command = $cmd
        | .mcpServers[$key].args = ["mcp-remote", $url]
        | .mcpServers[$key].name = $key' \
       "$config_file" > "$tmp_file"
    
    mv "$tmp_file" "$config_file"
    
    print_success "Claude config updated: $config_file (key: $server_key)"
    print_status "Configuration content:"
    cat "$config_file"
}

install_mcp_remote() {
    print_status "Installing mcp-remote package..."
    
    if npm list -g mcp-remote >/dev/null 2>&1; then
        print_success "mcp-remote is already installed globally"
    else
        print_status "Installing mcp-remote globally..."
        npm install -g mcp-remote
        print_success "mcp-remote installed successfully"
    fi
}

show_next_steps() {
    print_success "Installation completed successfully!"
    echo
    print_status "Next steps:"
    echo "1. Restart Claude Desktop application"
    echo "2. The MCP server should now be available in Claude"
    echo "3. You can verify the configuration by checking the config file at:"
    if [[ "$OSTYPE" == "darwin"* ]]; then
        echo "   ~/Library/Application Support/Claude/claude_desktop_config.json"
    else
        echo "   ~/.config/claude/claude_desktop_config.json"
    fi
    echo
    print_warning "If you encounter any issues, please check that:"
    echo "- Claude Desktop is properly installed"
    echo "- The claude_desktop_config.json file was created correctly"
    echo "- You have restarted Claude Desktop after the installation"
}

main() {
    parse_arguments "$@"
    
    echo "=========================================="
    echo "    MCP Installer for Claude Desktop"
    echo "=========================================="
    echo
    
    if [[ "$OSTYPE" != "darwin"* ]] && [[ "$OSTYPE" != "linux-gnu"* ]]; then
        print_error "This script only supports macOS and Linux"
        exit 1
    fi
    
    install_homebrew
    
    install_node_npm
    
    install_jq
    
    install_mcp_remote
    
    create_mcp_config
    
    show_next_steps
}

main "$@"