#!/bin/bash
#
# Vigthoria CLI Installer
# Usage: curl -fsSL https://cli.vigthoria.io/install.sh | bash
#
# Supports: Linux, macOS (Intel and Apple Silicon)
#

set -e

# Colors (with fallback for non-color terminals)
if [ -t 1 ] && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    CYAN='\033[0;36m'
    WHITE='\033[1;37m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    CYAN=''
    WHITE=''
    NC=''
fi

# Configuration
CLI_VERSION="1.4.4"
INSTALL_DIR="$HOME/.vigthoria"
REPO_URL="https://market.vigthoria.io/vigthoria/vigthoria-cli"

# Detect platform and set appropriate bin directory
detect_platform() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"
    
    case "$OS" in
        Darwin)
            PLATFORM="macos"
            # macOS: Check if /usr/local/bin is writable, otherwise use ~/.local/bin
            if [ -w "/usr/local/bin" ]; then
                BIN_DIR="/usr/local/bin"
            else
                BIN_DIR="$HOME/.local/bin"
                mkdir -p "$BIN_DIR"
            fi
            ;;
        Linux)
            PLATFORM="linux"
            # Linux: Prefer ~/.local/bin for user installs
            if [ -w "/usr/local/bin" ]; then
                BIN_DIR="/usr/local/bin"
            else
                BIN_DIR="$HOME/.local/bin"
                mkdir -p "$BIN_DIR"
            fi
            ;;
        *)
            echo -e "${RED}Unsupported operating system: $OS${NC}"
            echo "Please use the npm install method: npm install -g vigthoria-cli"
            exit 1
            ;;
    esac
    
    echo -e "${CYAN}Detected: $PLATFORM ($ARCH)${NC}"
}

echo -e "${CYAN}"
echo "╔═══════════════════════════════════════════════════════════╗"
echo "║                                                           ║"
echo "║         VIGTHORIA CLI INSTALLER v${CLI_VERSION}                  ║"
echo "║         AI-Powered Terminal Coding Assistant              ║"
echo "║                                                           ║"
echo "╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Check requirements
check_requirements() {
    echo -e "${CYAN}Checking requirements...${NC}"
    
    detect_platform
    
    # Check Node.js
    if ! command -v node &> /dev/null; then
        echo -e "${RED}✗ Node.js is not installed${NC}"
        echo ""
        echo "  Please install Node.js 18 or later:"
        if [ "$PLATFORM" = "macos" ]; then
            echo "    brew install node"
            echo "    or download from: https://nodejs.org/"
        else
            echo "    # Ubuntu/Debian:"
            echo "    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -"
            echo "    sudo apt-get install -y nodejs"
            echo ""
            echo "    # Or download from: https://nodejs.org/"
        fi
        exit 1
    fi
    
    NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_VERSION" -lt 18 ]; then
        echo -e "${RED}✗ Node.js version must be 18 or higher (found: v$NODE_VERSION)${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Node.js v$(node -v | cut -d'v' -f2)${NC}"
    
    # Check npm
    if ! command -v npm &> /dev/null; then
        echo -e "${RED}✗ npm is not installed${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ npm v$(npm -v)${NC}"
    
    # Check git (optional)
    if command -v git &> /dev/null; then
        echo -e "${GREEN}✓ git v$(git --version | cut -d' ' -f3)${NC}"
    else
        echo -e "${YELLOW}⚠ git not found (optional, for project context)${NC}"
    fi
    
    echo ""
}

# Install CLI
install_cli() {
    echo -e "${CYAN}Installing Vigthoria CLI...${NC}"
    
    # Create install directory
    mkdir -p "$INSTALL_DIR"
    
    # Option 1: Install from npm (production)
    if npm view vigthoria-cli version &> /dev/null; then
        echo "Installing from npm registry..."
        npm install -g vigthoria-cli
    else
        # Option 2: Install from local or git
        echo "Installing from source..."
        
        # Check if we're in the CLI directory
        if [ -f "package.json" ] && grep -q '"name": "vigthoria-cli"' package.json; then
            echo "Installing from current directory..."
            npm install
            npm run build
            npm link
        else
            # Clone from repo
            echo "Cloning from repository..."
            git clone "$REPO_URL" "$INSTALL_DIR/cli" 2>/dev/null || {
                echo -e "${YELLOW}Repository not available, using local install${NC}"
                # Copy local files for development
                SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
                if [ -d "$SCRIPT_DIR/../src" ]; then
                    cp -r "$SCRIPT_DIR/.." "$INSTALL_DIR/cli"
                fi
            }
            
            if [ -d "$INSTALL_DIR/cli" ]; then
                cd "$INSTALL_DIR/cli"
                npm install
                npm run build
                npm link
            fi
        fi
    fi
    
    echo -e "${GREEN}✓ Installation complete${NC}"
    echo ""
}

# Create symlinks
create_symlinks() {
    echo -e "${CYAN}Creating command shortcuts...${NC}"
    
    # Check if vigthoria command exists
    if command -v vigthoria &> /dev/null; then
        echo -e "${GREEN}✓ 'vigthoria' command available${NC}"
    fi
    
    # Create 'vig' alias if not exists
    if ! command -v vig &> /dev/null; then
        if [ -w "$BIN_DIR" ]; then
            ln -sf "$(which vigthoria)" "$BIN_DIR/vig" 2>/dev/null || true
        fi
    fi
    
    if command -v vig &> /dev/null; then
        echo -e "${GREEN}✓ 'vig' shortcut available${NC}"
    fi
    
    echo ""
}

# Setup shell completion
setup_completion() {
    echo -e "${CYAN}Setting up shell completion...${NC}"
    
    # Detect shell
    SHELL_NAME=$(basename "$SHELL")
    
    case "$SHELL_NAME" in
        bash)
            COMPLETION_FILE="$HOME/.bash_completion.d/vigthoria"
            mkdir -p "$HOME/.bash_completion.d"
            cat > "$COMPLETION_FILE" << 'EOF'
_vigthoria_completions() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local commands="chat edit generate explain fix review login logout status config init"
    COMPREPLY=($(compgen -W "$commands" -- "$cur"))
}
complete -F _vigthoria_completions vigthoria
complete -F _vigthoria_completions vig
EOF
            echo -e "${GREEN}✓ Bash completion installed${NC}"
            echo "  Run: source ~/.bash_completion.d/vigthoria"
            ;;
        zsh)
            COMPLETION_FILE="$HOME/.zsh/completion/_vigthoria"
            mkdir -p "$HOME/.zsh/completion"
            cat > "$COMPLETION_FILE" << 'EOF'
#compdef vigthoria vig

_vigthoria() {
    local -a commands
    commands=(
        'chat:Start interactive chat with AI'
        'edit:Edit a file with AI assistance'
        'generate:Generate code from description'
        'explain:Explain code in a file'
        'fix:Fix issues in a file'
        'review:Review code quality'
        'login:Login to Vigthoria'
        'logout:Logout from Vigthoria'
        'status:Show account status'
        'config:Configure settings'
        'init:Initialize project'
    )
    _describe 'command' commands
}

_vigthoria "$@"
EOF
            echo -e "${GREEN}✓ Zsh completion installed${NC}"
            echo "  Add to ~/.zshrc: fpath=(~/.zsh/completion \$fpath)"
            ;;
        *)
            echo -e "${YELLOW}⚠ Shell completion not available for $SHELL_NAME${NC}"
            ;;
    esac
    
    echo ""
}

# Print success message
print_success() {
    echo -e "${GREEN}"
    echo "╔═══════════════════════════════════════════════════════════╗"
    echo "║                                                           ║"
    echo "║         ✓ VIGTHORIA CLI INSTALLED SUCCESSFULLY!           ║"
    echo "║                                                           ║"
    echo "╚═══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    echo -e "${CYAN}Quick Start:${NC}"
    echo ""
    echo "  1. Login to your account:"
    echo -e "     ${WHITE}vigthoria login${NC}"
    echo ""
    echo "  2. Start coding with AI:"
    echo -e "     ${WHITE}vigthoria chat${NC}"
    echo ""
    echo "  3. Edit a file:"
    echo -e "     ${WHITE}vigthoria edit myfile.ts${NC}"
    echo ""
    echo "  4. Generate code:"
    echo -e "     ${WHITE}vigthoria generate \"REST API endpoint\"${NC}"
    echo ""
    echo -e "${CYAN}Commands:${NC}"
    echo "  vigthoria chat      - Interactive AI chat"
    echo "  vigthoria edit      - Edit files with AI"
    echo "  vigthoria generate  - Generate code"
    echo "  vigthoria explain   - Explain code"
    echo "  vigthoria fix       - Fix code issues"
    echo "  vigthoria review    - Code review"
    echo "  vigthoria --help    - Show all commands"
    echo ""
    echo -e "${CYAN}Shortcuts:${NC}"
    echo "  vig c  = vigthoria chat"
    echo "  vig e  = vigthoria edit"
    echo "  vig g  = vigthoria generate"
    echo ""
    echo -e "Documentation: ${CYAN}https://docs.vigthoria.io/cli${NC}"
    echo ""
}

# Main installation flow
main() {
    check_requirements
    install_cli
    create_symlinks
    setup_completion
    print_success
}

# Run main
main "$@"
