#!/bin/bash

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BOLD='\033[1m'
END='\033[0m'
NC='\033[0m' # No Color

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

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

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

check_node_version() {
    if command -v node >/dev/null 2>&1; then
        local node_version
        node_version=$(node -v | sed 's/v//')
        local major_version
        major_version=$(echo $node_version | cut -d. -f1)

        if [ "$major_version" -ge 22 ]; then
            print_status "Node.js $node_version is already installed and meets requirements (>=22)"
            return 0
        else
            print_warning "Node.js $node_version is installed but version 22 or greater is required"
            return 1
        fi
    else
        print_warning "Node.js is not installed"
        return 1
    fi
}

install_node() {
    print_status "Installing Node.js via NVM..."

    # Check if nvm is already installed
    if [ -s "$HOME/.nvm/nvm.sh" ]; then
        print_status "NVM is already installed"
        \. "$HOME/.nvm/nvm.sh"
    else
        print_status "Downloading and installing NVM..."
        curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash

        # Load nvm
        \. "$HOME/.nvm/nvm.sh"
    fi

    print_status "Installing Node.js LTS 24..."
    nvm install 24
    nvm use 24
    nvm alias default 24

    print_status "Verifying installation..."
    node_version=$(node -v)
    npm_version=$(npm -v)
    nvm_current=$(nvm current)

    print_status "Node.js version: $node_version"
    print_status "npm version: $npm_version"
    print_status "NVM current: $nvm_current"

    if [[ "$node_version" == v24.* ]]; then
        print_status "Node.js installation successful!"
    else
        print_error "Node.js installation may have failed. Expected v24.x.x, got $node_version"
        exit 1
    fi
}

install_cli() {
    print_status "Installing @silogy/viv globally..."

    # Ensure we have access to npm/node if they were just installed via NVM
    if [ -s "$HOME/.nvm/nvm.sh" ]; then
        \. "$HOME/.nvm/nvm.sh"
    fi

    npm install -g @silogy/viv

    if command -v viv >/dev/null 2>&1; then
        print_status "viv installed successfully!"
    else
        print_error "viv installation failed or is not in PATH"

        # Check if viv exists in NVM paths
        local nvm_bin_path
        if nvm_bin_path=$(get_nvm_bin_path) && [ -f "$nvm_bin_path/viv" ]; then
            return 0
        fi

        exit 1
    fi
}

_which() {
    # `which` is not always available
    IFS=:
    for x in $PATH; do
        if [ -x "$x/$1" ]; then
            echo "$x/$1"
            return 0
        fi
    done
    echo "$1 not found in \$PATH"
    return 1
}

get_nvm_bin_path() {
    # Get the NVM bin path for the current or latest installed Node version
    if [ -s "$HOME/.nvm/nvm.sh" ]; then
        \. "$HOME/.nvm/nvm.sh" >/dev/null 2>&1
        local node_version
        if type nvm >/dev/null 2>&1; then
            node_version=$(nvm current 2>/dev/null || echo "none")
        else
            node_version="none"
        fi
        if [ "$node_version" = "none" ] || [ -z "$node_version" ]; then
            # Fallback: find the latest installed version
            if [ -d "$HOME/.nvm/versions/node/" ]; then
                node_version=$(ls "$HOME/.nvm/versions/node/" 2>/dev/null | grep -E '^v[0-9]+' | sort -V | tail -n1)
            fi
        fi
        if [ -n "$node_version" ] && [ "$node_version" != "none" ]; then
            echo "$HOME/.nvm/versions/node/$node_version/bin"
            return 0
        fi
    fi
    return 1
}


main() {
    print_status "Starting Viv CLI installation..."
    
    # Flag to track if we installed Node.js via NVM (and thus need PATH setup)
    local node_installed_via_nvm=false

    # Check operating system
    case "$(uname -s)" in
        Linux*)     OS=Linux;;
        Darwin*)    OS=Mac;;
        *)          print_error "Unsupported operating system: $(uname -s)"; exit 1;;
    esac

    print_status "Detected operating system: $OS"

    # Check Node.js version
    if ! check_node_version; then
        echo
        echo "Node.js 22 or greater is required but not found."
        echo "This installer can automatically install Node.js LTS 24 using NVM."
        echo
        echo -n "Would you like to install Node.js now? (y/N): "
        read -r REPLY < /dev/tty

        if [[ $REPLY =~ ^[Yy]$ ]]; then
            install_node
            node_installed_via_nvm=true
        else
            print_error "Node.js 22+ is required. Please install it manually and run this script again."
            exit 1
        fi
    fi

    # Install viv
    install_cli

    # Success message
    echo
    print_status "✅ Viv CLI installation completed successfully!"
    echo

    # We used to clone the Ibex repo here, but it's not necessary anymore.

    # Final setup instructions and PATH check
    local setup_needed=1  # Default: no setup needed
    local path_to_add=""
    
    # If we installed Node.js via NVM during this session, show PATH instructions
    if [ "$node_installed_via_nvm" = true ]; then
        setup_needed=0  # Setup is needed
        # Get the NVM path for the instructions
        path_to_add=$(get_nvm_bin_path)
    fi
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🎉 Installation Complete!"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    if [ $setup_needed -eq 0 ]; then
        echo
        echo "⚠️  IMPORTANT: PATH Setup Required"
        echo
        echo "   The 'viv' command is not currently in your PATH. If you're seeing \"viv: command not found\", you need to:"
        echo
        echo -e "   1. Add this line to your shell profile (~/.bashrc, ~/.zshrc, etc.):"
        echo
        echo -e "      ${BOLD}export PATH=\"$path_to_add:\$PATH\"${END}"
        echo
        echo -e "   2. For immediate use in this session, also run:"
        echo
        echo -e "      ${BOLD}source ~/.bashrc${END}   (or ${BOLD}source ~/.zshrc${END} if using zsh)"
        echo
        echo -e "   After setting up your PATH, try: ${BOLD}viv --help${END}"
    else
        echo
        echo -e "   ✅ All set! Try running: ${BOLD}viv --help${END}"
    fi
    
    echo
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo
}

main "$@"