#!/bin/bash
set -e

# MCP Gateway CLI Installer
# Usage: curl -fsSL https://get.mcpgw.io | sh

VERSION="${MCPGW_VERSION:-latest}"
INSTALL_DIR="${MCPGW_INSTALL_DIR:-$HOME/.local/bin}"

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

# Detect OS and architecture
detect_platform() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"
    
    case "$OS" in
        Linux*)     PLATFORM="linux";;
        Darwin*)    PLATFORM="macos";;
        *)          
            echo -e "${RED}✗ Unsupported OS: $OS${NC}"
            exit 1
            ;;
    esac
    
    case "$ARCH" in
        x86_64)     ARCH="amd64";;
        arm64|aarch64) ARCH="arm64";;
        *)          
            echo -e "${RED}✗ Unsupported architecture: $ARCH${NC}"
            exit 1
            ;;
    esac
}

# Check if Python is available
check_python() {
    if ! command -v python3 &> /dev/null; then
        echo -e "${RED}✗ Python 3 is required but not installed${NC}"
        echo -e "  Install Python 3.9+ and try again"
        exit 1
    fi
    
    PYTHON_VERSION=$(python3 --version | cut -d' ' -f2 | cut -d'.' -f1,2)
    PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d'.' -f1)
    PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d'.' -f2)
    
    if [ "$PYTHON_MAJOR" -lt 3 ] || ([ "$PYTHON_MAJOR" -eq 3 ] && [ "$PYTHON_MINOR" -lt 9 ]); then
        echo -e "${RED}✗ Python 3.9+ required (found $PYTHON_VERSION)${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✓${NC} Python $PYTHON_VERSION found"
}

# Install via pip
install_pip() {
    echo -e "${BLUE}Installing mcpgw via pip...${NC}"
    
    # Try pip3 first, fall back to pip
    if command -v pip3 &> /dev/null; then
        PIP_CMD="pip3"
    elif command -v pip &> /dev/null; then
        PIP_CMD="pip"
    else
        echo -e "${RED}✗ pip not found${NC}"
        exit 1
    fi
    
    # Install to user directory
    $PIP_CMD install --user mcpgw
    
    echo -e "${GREEN}✓${NC} mcpgw installed"
}

# Setup shell aliases
setup_aliases() {
    SHELL_RC=""
    
    # Detect shell
    if [ -n "$ZSH_VERSION" ]; then
        SHELL_RC="$HOME/.zshrc"
    elif [ -n "$BASH_VERSION" ]; then
        if [ -f "$HOME/.bashrc" ]; then
            SHELL_RC="$HOME/.bashrc"
        else
            SHELL_RC="$HOME/.bash_profile"
        fi
    fi
    
    if [ -n "$SHELL_RC" ]; then
        # Check if aliases already exist
        if ! grep -q "alias mg=" "$SHELL_RC" 2>/dev/null; then
            echo "" >> "$SHELL_RC"
            echo "# MCP Gateway CLI aliases" >> "$SHELL_RC"
            echo "alias mg='mcpgw'" >> "$SHELL_RC"
            echo -e "${GREEN}✓${NC} Shell alias 'mg' added to $SHELL_RC"
            RELOAD_SHELL=true
        fi
    fi
}

# Verify installation
verify_install() {
    # Check if mcpgw is in PATH
    if command -v mcpgw &> /dev/null; then
        VERSION=$(mcpgw --version 2>/dev/null | head -1 || echo "unknown")
        echo -e "${GREEN}✓${NC} mcpgw is accessible: $VERSION"
        return 0
    else
        # Add common Python user bin directories to PATH suggestions
        USER_BIN_DIRS=(
            "$HOME/.local/bin"
            "$HOME/Library/Python/3.*/bin"
        )
        
        echo -e "${YELLOW}⚠${NC}  mcpgw installed but not in PATH"
        echo -e "  Add this to your shell config:"
        echo -e "  ${BLUE}export PATH=\"\$HOME/.local/bin:\$PATH\"${NC}"
        return 1
    fi
}

# Print success message
print_success() {
    cat << 'EOF'

╔══════════════════════════════════════════════╗
║                                              ║
║      ✅ MCP Gateway CLI Installed!          ║
║                                              ║
╚══════════════════════════════════════════════╝

EOF
    
    echo -e "${GREEN}Commands available:${NC}"
    echo -e "  ${BLUE}mcpgw${NC}      - Full command"
    echo -e "  ${BLUE}mg${NC}         - Short alias (same as mcpgw)"
    echo ""
    echo -e "${GREEN}Quick Start:${NC}"
    echo -e "  ${BLUE}mcpgw auth login${NC}     - Login to your account"
    echo -e "  ${BLUE}mcpgw quickstart${NC}     - Interactive setup wizard"
    echo -e "  ${BLUE}mcpgw add github${NC}     - Add GitHub MCP server"
    echo -e "  ${BLUE}mcpgw generate${NC}       - Generate Claude config"
    echo ""
    echo -e "${GREEN}Documentation:${NC}"
    echo -e "  https://docs.mcpgw.io"
    echo ""
    
    if [ "$RELOAD_SHELL" = true ]; then
        echo -e "${YELLOW}Note:${NC} Reload your shell or run: ${BLUE}source $SHELL_RC${NC}"
        echo ""
    fi
}

# Main installation flow
main() {
    echo ""
    echo -e "${BLUE}╔═══════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║  MCP Gateway CLI Installer           ║${NC}"
    echo -e "${BLUE}╚═══════════════════════════════════════╝${NC}"
    echo ""
    
    detect_platform
    echo -e "${GREEN}✓${NC} Platform: $PLATFORM ($ARCH)"
    
    check_python
    install_pip
    setup_aliases
    
    echo ""
    
    if verify_install; then
        print_success
    else
        echo -e "${YELLOW}Installation complete but PATH setup needed${NC}"
        echo -e "Run: ${BLUE}export PATH=\"\$HOME/.local/bin:\$PATH\"${NC}"
        echo -e "Then: ${BLUE}mcpgw --version${NC}"
    fi
}

main "$@"
