#!/bin/bash
set -e

# Hindsight CLI installer
# Usage: curl -fsSL https://hindsight.vectorize.io/get-cli | bash
# Or with specific version: HINDSIGHT_CLI_VERSION=0.4.3 curl -fsSL https://hindsight.vectorize.io/get-cli | bash

REPO_URL="https://github.com/vectorize-io/hindsight"
INSTALL_DIR="${HINDSIGHT_INSTALL_DIR:-$HOME/.local/bin}"
BINARY_NAME="hindsight"

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

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_banner() {
    echo ""
    # ANSI logo
    echo -e "  \033[38;2;9;127;184m▄\033[0m\033[48;2;8;130;178m\033[38;2;5;133;186m▄\033[0m       \033[48;2;10;143;160m\033[38;2;10;143;165m▄\033[0m\033[38;2;7;140;156m▄\033[0m  "
    echo -e " \033[38;2;8;125;192m▄\033[0m \033[38;2;3;132;191m▀\033[0m\033[38;2;2;133;192m▄\033[0m \033[38;2;3;132;180m▄\033[0m\033[38;2;1;137;184m▄\033[0m\033[38;2;3;133;174m▄\033[0m \033[38;2;3;142;176m▄\033[0m\033[38;2;4;142;169m▀\033[0m \033[38;2;10;144;164m▄\033[0m "
    echo -e "\033[38;2;6;121;195m▀\033[0m\033[38;2;5;128;203m▀\033[0m\033[48;2;5;124;195m\033[38;2;3;125;200m▄\033[0m\033[38;2;2;126;196m▄\033[0m\033[48;2;3;128;188m\033[38;2;1;131;196m▄\033[0m\033[48;2;0;152;219m\033[38;2;2;131;191m▄\033[0m\033[38;2;1;141;196m▀\033[0m\033[38;2;1;135;183m▀\033[0m\033[38;2;1;148;198m▀\033[0m\033[48;2;1;156;202m\033[38;2;2;135;180m▄\033[0m\033[48;2;4;134;169m\033[38;2;1;137;177m▄\033[0m\033[38;2;3;138;173m▄\033[0m\033[48;2;6;137;165m\033[38;2;2;140;170m▄\033[0m\033[38;2;7;144;169m▀\033[0m\033[38;2;7;139;158m▀\033[0m"
    echo -e "   \033[48;2;2;128;202m\033[38;2;2;124;201m▄\033[0m\033[48;2;1;130;201m\033[38;2;0;135;212m▄\033[0m\033[38;2;2;128;196m▄\033[0m \033[48;2;2;142;204m\033[38;2;7;138;199m▄\033[0m \033[38;2;1;135;186m▄\033[0m\033[48;2;1;142;186m\033[38;2;2;144;194m▄\033[0m\033[48;2;3;138;176m\033[38;2;2;134;176m▄\033[0m   "
    echo -e " \033[48;2;8;118;200m\033[38;2;8;121;209m▄\033[0m\033[38;2;3;121;203m▀\033[0m \033[38;2;3;122;192m▀\033[0m\033[38;2;1;138;216m▀\033[0m\033[48;2;0;138;210m\033[38;2;3;128;198m▄\033[0m\033[48;2;0;126;188m\033[38;2;2;131;198m▄\033[0m\033[48;2;0;142;205m\033[38;2;3;132;193m▄\033[0m\033[38;2;1;140;196m▀\033[0m  \033[38;2;4;134;175m▀\033[0m\033[48;2;13;135;167m\033[38;2;8;136;174m▄\033[0m "
    echo ""
    echo -e "  ${BLUE}HINDSIGHT CLI INSTALLER${NC}"
    echo ""
}

# Detect platform
detect_platform() {
    local os=$(uname -s)
    local arch=$(uname -m)

    case "$os" in
        Darwin)
            if [[ "$arch" == "arm64" ]] || [[ "$arch" == "aarch64" ]]; then
                echo "darwin-arm64"
            elif [[ "$arch" == "x86_64" ]]; then
                echo "darwin-amd64"
            else
                print_error "Unsupported macOS architecture: $arch"
                exit 1
            fi
            ;;
        Linux)
            if [[ "$arch" == "x86_64" ]]; then
                echo "linux-amd64"
            elif [[ "$arch" == "aarch64" ]] || [[ "$arch" == "arm64" ]]; then
                echo "linux-arm64"
            else
                print_error "Unsupported Linux architecture: $arch"
                exit 1
            fi
            ;;
        *)
            print_error "Unsupported operating system: $os"
            exit 1
            ;;
    esac
}

# Get latest version from GitHub API
get_latest_version() {
    local api_url="https://api.github.com/repos/vectorize-io/hindsight/releases/latest"
    local version=""

    if command -v curl > /dev/null 2>&1; then
        version=$(curl -fsSL "$api_url" | grep '"tag_name":' | sed -E 's/.*"tag_name": *"([^"]+)".*/\1/')
    elif command -v wget > /dev/null 2>&1; then
        version=$(wget -qO- "$api_url" | grep '"tag_name":' | sed -E 's/.*"tag_name": *"([^"]+)".*/\1/')
    fi

    if [[ -z "$version" ]]; then
        print_error "Failed to get latest version from GitHub" >&2
        exit 1
    fi

    echo "$version"
}

# Download binary
download_binary() {
    local platform=$1
    local version=$2
    local download_url="${REPO_URL}/releases/download/${version}/hindsight-${platform}"
    local tmp_file="/tmp/hindsight-$$"

    print_info "Downloading Hindsight CLI ${version} for $platform..." >&2

    if command -v curl > /dev/null 2>&1; then
        # GitHub returns 302 redirect to Azure blob storage
        # curl -L sometimes fails with 503, so manually handle redirect
        local redirect_url=$(curl -sI "$download_url" 2>/dev/null | grep -i "^location:" | sed 's/location: //i' | tr -d '\r\n')
        if [[ -n "$redirect_url" ]]; then
            curl -fsSL "$redirect_url" -o "$tmp_file"
        else
            # Fallback to direct download if no redirect
            curl -fsSL "$download_url" -o "$tmp_file"
        fi
    elif command -v wget > /dev/null 2>&1; then
        wget -q "$download_url" -O "$tmp_file"
    else
        print_error "Neither curl nor wget found. Please install one of them." >&2
        exit 1
    fi

    echo "$tmp_file"
}

# Install binary
install_binary() {
    local tmp_file=$1

    # Create install directory if it doesn't exist
    mkdir -p "$INSTALL_DIR"

    # Move binary to install directory
    mv "$tmp_file" "$INSTALL_DIR/$BINARY_NAME"
    chmod +x "$INSTALL_DIR/$BINARY_NAME"

    print_success "Installed to: $INSTALL_DIR/$BINARY_NAME"
}

# Check if directory is in PATH
check_path() {
    if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
        print_warning "$INSTALL_DIR is not in your PATH"
        echo ""
        echo "Add it to your PATH by adding this line to your shell profile:"
        echo ""

        # Detect shell
        if [[ -n "$BASH_VERSION" ]]; then
            echo "  echo 'export PATH=\"$INSTALL_DIR:\$PATH\"' >> ~/.bashrc"
            echo "  source ~/.bashrc"
        elif [[ -n "$ZSH_VERSION" ]]; then
            echo "  echo 'export PATH=\"$INSTALL_DIR:\$PATH\"' >> ~/.zshrc"
            echo "  source ~/.zshrc"
        else
            echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
        fi
        echo ""
    fi
}

# Main installation flow
main() {
    print_banner

    # Detect platform
    platform=$(detect_platform)
    print_info "Detected platform: $platform"

    # Get version (from env var or latest)
    if [[ -n "$HINDSIGHT_CLI_VERSION" ]]; then
        version="$HINDSIGHT_CLI_VERSION"
        # Add 'v' prefix if not present (GitHub releases use v-prefix)
        if [[ ! "$version" =~ ^v ]]; then
            version="v${version}"
        fi
        print_info "Using specified version: $version"
    else
        version=$(get_latest_version)
        print_info "Latest version: $version"
    fi

    # Download binary
    tmp_file=$(download_binary "$platform" "$version")

    # Install binary
    install_binary "$tmp_file"

    # Check PATH
    check_path

    print_success "Installation complete!"
    echo ""
    print_info "Try it out: $BINARY_NAME --help"
    echo ""
    print_info "Configure the API URL:"
    echo "  export HINDSIGHT_API_URL=http://localhost:8888"
    echo ""
}

# Run installation
main
