#!/usr/bin/env bash
set -euo pipefail

# Redirect Windows users to PowerShell script (except MINGW64/Git Bash)
platform=$(uname -ms)
if [[ ${OS:-} = Windows_NT ]]; then
    if [[ $platform != MINGW64* ]]; then
        powershell -c "irm cli.hetge.com/hetge-cli/install.ps1|iex"
        exit $?
    fi
fi

# ============================================================================
# hetge-cli install script for macOS and Linux
#
# Usage:
#   /bin/bash -c "$(curl -fsSL https://cli.hetge.com/hetge-cli/install.sh)"
#
# This script will:
#   1. Install Homebrew (if not present)
#   2. Install Node.js (if not present)
#   3. Install gh, op, env2op CLI tools
#   4. Authenticate with GitHub (opens browser)
#   5. Configure npm for @hetge packages
#   6. Install @hetge/cli globally
# ============================================================================

# Colors (only if stdout is a terminal)
if [[ -t 1 ]]; then
    Red='\033[0;31m'
    Green='\033[0;32m'
    Yellow='\033[0;33m'
    Blue='\033[0;34m'
    Bold='\033[1m'
    Dim='\033[2m'
    Reset='\033[0m'
    # True color for banner
    Teal='\033[38;2;23;178;159m'
    White='\033[97m'
    BrightBlue='\033[38;2;59;130;246m'
else
    Red=''
    Green=''
    Yellow=''
    Blue=''
    Bold=''
    Dim=''
    Reset=''
    Teal=''
    White=''
    BrightBlue=''
fi

# Output functions
info() {
    echo -e "${Blue}::${Reset} $*"
}

success() {
    echo -e "${Green}✓${Reset} $*"
}

warn() {
    echo -e "${Yellow}!${Reset} $*"
}

error() {
    echo -e "${Red}error${Reset}: $*" >&2
    exit 1
}

# Check if command exists
command_exists() {
    command -v "$1" &>/dev/null
}

# Platform detection
is_macos() {
    [[ "$(uname -s)" == "Darwin" ]]
}

is_linux() {
    [[ "$(uname -s)" == "Linux" ]]
}

has_homebrew() {
    command_exists brew
}

has_apt() {
    command_exists apt-get
}

# Print banner
print_banner() {
    echo ""
    echo -e "${Teal}█████                █████      █████████  ██████████${White}                     ${BrightBlue}████   ███ ${Reset}"
    echo -e "${Teal}░░███                ░░███      ███░░░░░███░░███░░░░░█${White}                    ${BrightBlue}░░███  ░░░  ${Reset}"
    echo -e "${Teal} ░███████    ██████  ███████   ███     ░░░  ░███  █ ░ ${White}             ${BrightBlue}██████  ░███  ████ ${Reset}"
    echo -e "${Teal} ░███░░███  ███░░███░░░███░   ░███          ░██████   ${White} ██████████ ${BrightBlue}███░░███ ░███ ░░███ ${Reset}"
    echo -e "${Teal} ░███ ░███ ░███████   ░███    ░███    █████ ░███░░█   ${White}░░░░░░░░░░ ${BrightBlue}░███ ░░░  ░███  ░███ ${Reset}"
    echo -e "${Teal} ░███ ░███ ░███░░░    ░███ ███░░███  ░░███  ░███ ░   █${White}           ${BrightBlue}░███  ███ ░███  ░███ ${Reset}"
    echo -e "${Teal} ████ █████░░██████   ░░█████  ░░█████████  ██████████${White}           ${BrightBlue}░░██████  █████ █████${Reset}"
    echo -e "${Teal}░░░░ ░░░░░  ░░░░░░     ░░░░░    ░░░░░░░░░  ░░░░░░░░░░ ${White}            ${BrightBlue}░░░░░░  ░░░░░ ░░░░░ ${Reset}"
    echo ""
    echo -e " ${Dim}Installation Script${Reset}"
    echo ""
}

# Install system dependencies (for minimal systems like Docker)
install_system_deps() {
    # Only run on apt-based systems (Debian, Ubuntu)
    if ! has_apt; then
        return 0
    fi

    local packages=()

    # Check for git (required by Homebrew)
    if ! command_exists git; then
        packages+=(git)
    fi

    # Check for build-essential (required by Homebrew)
    if ! command_exists gcc; then
        packages+=(build-essential)
    fi

    if [[ ${#packages[@]} -eq 0 ]]; then
        return 0
    fi

    info "Installing system dependencies: ${packages[*]}..."

    # Use sudo if not root
    local sudo=""
    if [[ $EUID -ne 0 ]]; then
        sudo="sudo"
    fi

    $sudo apt-get update -qq
    $sudo apt-get install -y -qq "${packages[@]}"

    success "System dependencies installed"
}

# Check prerequisites
check_prerequisites() {
    info "[1/6] Checking prerequisites..."

    # Install system deps if needed (apt-based systems)
    install_system_deps

    success "Prerequisites satisfied"
}

# Install Homebrew if needed
install_homebrew() {
    if has_homebrew; then
        success "Homebrew already installed"
        return 0
    fi

    info "Installing Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

    # Add Homebrew to PATH for this session and persist to shell profile
    if is_linux; then
        local brew_path=""
        if [[ -f /home/linuxbrew/.linuxbrew/bin/brew ]]; then
            brew_path="/home/linuxbrew/.linuxbrew/bin/brew"
        elif [[ -f "$HOME/.linuxbrew/bin/brew" ]]; then
            brew_path="$HOME/.linuxbrew/bin/brew"
        fi

        if [[ -n "$brew_path" ]]; then
            # Add to current session
            eval "$("$brew_path" shellenv)"

            # Persist to shell profile
            local shellenv_cmd="eval \"\$($brew_path shellenv)\""
            local profile="$HOME/.bashrc"
            [[ -f "$HOME/.zshrc" ]] && profile="$HOME/.zshrc"

            if ! grep -q "linuxbrew" "$profile" 2>/dev/null; then
                echo "" >> "$profile"
                echo "# Homebrew" >> "$profile"
                echo "$shellenv_cmd" >> "$profile"
            fi
        fi
    fi

    success "Homebrew installed"
}

# Install dependencies
install_dependencies() {
    info "[2/6] Installing dependencies..."

    # Ensure Homebrew is available
    install_homebrew

    # Install Node.js if not present
    if command_exists node; then
        success "Node.js already installed"
    else
        info "Installing Node.js..."
        brew install node
        success "Node.js installed"
    fi

    # Install gh
    if command_exists gh; then
        success "gh already installed"
    else
        info "Installing GitHub CLI..."
        brew install gh
        success "GitHub CLI installed"
    fi

    # Install 1password-cli
    if command_exists op; then
        success "1Password CLI already installed"
    else
        info "Installing 1Password CLI..."
        brew install 1password-cli
        success "1Password CLI installed"
    fi

    # Install env2op-cli
    if command_exists env2op; then
        success "env2op already installed"
    else
        info "Installing env2op CLI..."
        brew install tolgamorf/tap/env2op-cli
        success "env2op CLI installed"
    fi
}

# Check if gh has required scopes
has_required_scopes() {
    local status
    status=$(gh auth status 2>&1 || true)
    echo "$status" | grep -q "write:packages"
}

# Setup GitHub authentication
setup_authentication() {
    info "[3/6] Setting up GitHub authentication..."

    # Check if already authenticated
    if gh auth status &>/dev/null; then
        if has_required_scopes; then
            local user
            user=$(gh auth status 2>&1 | grep "Logged in to github.com account" | sed 's/.*account //' | awk '{print $1}' || echo "unknown")
            success "Already authenticated as ${Bold}${user}${Reset} with required scopes"
            return 0
        else
            warn "Missing write:packages scope. Refreshing authentication..."
            gh auth refresh -s write:packages
            success "Authentication refreshed with write:packages scope"
            return 0
        fi
    fi

    # Not authenticated - run login
    echo ""
    info "A browser window will open for GitHub authentication."
    info "Please complete the authentication in your browser."
    echo ""

    gh auth login \
        --scopes write:packages \
        --hostname github.com \
        --git-protocol ssh \
        --web \
        --skip-ssh-key \
        --clipboard

    # Verify authentication succeeded
    if ! gh auth status &>/dev/null; then
        error "GitHub authentication failed. Please try again."
    fi

    local user
    user=$(gh auth status 2>&1 | grep "Logged in to github.com account" | sed 's/.*account //' | awk '{print $1}' || echo "unknown")
    success "Authenticated as ${Bold}${user}${Reset}"
}

# Cross-platform sed -i (macOS requires '' argument, Linux doesn't)
sed_inplace() {
    if is_macos; then
        sed -i '' "$@"
    else
        sed -i "$@"
    fi
}

# Configure npm registry
configure_npm() {
    info "[4/6] Configuring npm for @hetge packages..."

    # Get auth token
    local token
    token=$(gh auth token)
    if [[ -z "$token" ]]; then
        error "Could not get GitHub auth token"
    fi

    # Write directly to ~/.npmrc (more reliable than npm config set -g)
    local npmrc="$HOME/.npmrc"

    # Add or update @hetge registry
    if [[ -f "$npmrc" ]] && grep -q "@hetge:registry" "$npmrc"; then
        # Update existing
        sed_inplace 's|@hetge:registry=.*|@hetge:registry=https://npm.pkg.github.com|' "$npmrc"
    else
        echo "@hetge:registry=https://npm.pkg.github.com" >> "$npmrc"
    fi

    # Add or update auth token
    if grep -q "//npm.pkg.github.com/:_authToken" "$npmrc" 2>/dev/null; then
        # Update existing
        sed_inplace "s|//npm.pkg.github.com/:_authToken=.*|//npm.pkg.github.com/:_authToken=$token|" "$npmrc"
    else
        echo "//npm.pkg.github.com/:_authToken=$token" >> "$npmrc"
    fi

    # Verify npm auth works
    if npm whoami --registry=https://npm.pkg.github.com &>/dev/null; then
        success "npm registry configured and authenticated"
    else
        warn "npm registry configured, but authentication could not be verified"
        warn "You may need to re-run: gh auth refresh -s read:packages"
    fi
}

# Install hetge-cli
install_hetge_cli() {
    info "[5/6] Installing @hetge/cli..."

    # Ensure npm global bin is in PATH
    NPM_GLOBAL_BIN="$(npm prefix -g)/bin"
    if [[ ":$PATH:" != *":$NPM_GLOBAL_BIN:"* ]]; then
        export PATH="$NPM_GLOBAL_BIN:$PATH"
    fi

    npm install -g @hetge/cli

    success "@hetge/cli installed"
}

# Verify installation
verify_installation() {
    info "[6/6] Verifying installation..."

    local errors=0

    # Check tools
    for tool in gh op env2op hetge; do
        if command_exists "$tool"; then
            local version
            version=$("$tool" --version 2>/dev/null | head -1 || echo "installed")
            success "  ${tool}: ${Dim}${version}${Reset}"
        else
            echo -e "  ${Red}✗${Reset} ${tool}: NOT FOUND"
            ((errors++)) || true
        fi
    done

    # Check gh auth
    if gh auth status &>/dev/null; then
        local user
        user=$(gh auth status 2>&1 | grep "Logged in to github.com account" | sed 's/.*account //' | awk '{print $1}' || echo "unknown")
        success "  gh auth: logged in as ${user}"
    else
        echo -e "  ${Red}✗${Reset} gh auth: NOT AUTHENTICATED"
        ((errors++)) || true
    fi

    # Check npm config
    local registry
    registry=$(npm config get @hetge:registry 2>/dev/null || echo "")
    if [[ "$registry" == "https://npm.pkg.github.com" ]]; then
        success "  npm registry: configured"
    else
        echo -e "  ${Red}✗${Reset} npm registry: NOT CONFIGURED"
        ((errors++)) || true
    fi

    if [[ $errors -gt 0 ]]; then
        error "Installation incomplete. Please fix the errors above."
    fi
}

# Install shell completions
install_shell_completions() {
    local detected_shell
    detected_shell="$(basename "$SHELL")"

    # Check if shell is supported
    case "$detected_shell" in
        bash|zsh|fish)
            ;;
        *)
            info "Shell completions not auto-installed for '$detected_shell'"
            info "Run 'hetge completion' to set up manually"
            return 0
            ;;
    esac

    info "Installing shell completions for $detected_shell..."

    local npm_bin
    npm_bin="$(npm prefix -g)/bin"

    if "$npm_bin/hetge" completion "$detected_shell" --install > /dev/null 2>&1; then
        success "Shell completions installed for $detected_shell"
    else
        warn "Could not install shell completions automatically"
        info "Run 'hetge completion' to set up manually"
    fi
}

# Print success message
print_success() {
    echo ""
    echo -e "${Green}================================================${Reset}"
    echo -e "${Green} Installation Complete!${Reset}"
    echo -e "${Green}================================================${Reset}"
    echo ""
    echo " You can now use hetge-cli in your projects:"
    echo ""
    echo -e "   ${Dim}# Run globally${Reset}"
    echo "   hetge"
    echo ""
    echo -e "   ${Dim}# Or add to a project${Reset}"
    echo "   npm install -D @hetge/cli"
    echo ""
    echo -e " ${Yellow}Note:${Reset} Open a new terminal or run 'source ~/.bashrc' to use the tools."
    echo -e "       Shell completions have been installed automatically."
    echo ""
}

# Main
main() {
    print_banner
    check_prerequisites
    install_dependencies
    setup_authentication
    configure_npm
    install_hetge_cli
    install_shell_completions
    verify_installation
    print_success
}

main "$@"
