#!/bin/bash
set -e

# SummonAI Kit CLI Installer
# Usage: curl -fsSL https://cli.summonaikit.com/install.sh | bash

RELEASES_URL="${SUMMONAIKIT_RELEASES_URL:-https://cli.summonaikit.com}"
INSTALL_DIR="${SUMMONAIKIT_INSTALL_DIR:-$HOME/.summonaikit/bin}"

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

print_banner() {
    echo ""
    echo -e "${GREEN}╔═══════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}     ${BLUE}SummonAI Kit CLI Installer${NC}        ${GREEN}║${NC}"
    echo -e "${GREEN}╚═══════════════════════════════════════╝${NC}"
    echo ""
}

info() {
    echo -e "${BLUE}→${NC} $1"
}

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

warn() {
    echo -e "${YELLOW}!${NC} $1"
}

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

detect_platform() {
    local os arch binary

    os="$(uname -s)"
    arch="$(uname -m)"

    case "$os" in
        Darwin)
            case "$arch" in
                arm64|aarch64) binary="summonaikit-darwin-arm64" ;;
                x86_64) binary="summonaikit-darwin-x64" ;;
                *) error "Unsupported architecture: $arch" ;;
            esac
            ;;
        Linux)
            # Check for musl (Alpine)
            if [ -f /etc/alpine-release ] || ldd --version 2>&1 | grep -q musl; then
                case "$arch" in
                    aarch64|arm64) binary="summonaikit-linux-arm64-musl" ;;
                    x86_64) binary="summonaikit-linux-x64-musl-baseline" ;;
                    *) error "Unsupported architecture: $arch" ;;
                esac
            else
                case "$arch" in
                    aarch64|arm64) binary="summonaikit-linux-arm64" ;;
                    x86_64) binary="summonaikit-linux-x64-baseline" ;;
                    *) error "Unsupported architecture: $arch" ;;
                esac
            fi
            ;;
        *)
            error "Unsupported operating system: $os"
            ;;
    esac

    echo "$binary"
}

download_binary() {
    local binary="$1"
    local dest="$2"
    local url="${RELEASES_URL}/cli/latest/${binary}"

    info "Downloading ${binary}..."

    if command -v curl &> /dev/null; then
        curl -fsSL "$url" -o "$dest"
    elif command -v wget &> /dev/null; then
        wget -q "$url" -O "$dest"
    else
        error "Neither curl nor wget found. Please install one of them."
    fi
}

setup_path() {
    local shell_profile=""
    local shell_name="${SHELL##*/}"
    local os="$(uname -s)"

    case "$shell_name" in
        bash)
            # On Linux, prefer .bashrc (interactive non-login shells)
            # On macOS, prefer .bash_profile (login shells)
            if [ "$os" = "Linux" ]; then
                shell_profile="$HOME/.bashrc"
            elif [ -f "$HOME/.bash_profile" ]; then
                shell_profile="$HOME/.bash_profile"
            else
                shell_profile="$HOME/.bashrc"
            fi
            ;;
        zsh)
            shell_profile="$HOME/.zshrc"
            ;;
        fish)
            shell_profile="$HOME/.config/fish/config.fish"
            ;;
        *)
            shell_profile="$HOME/.profile"
            ;;
    esac

    # Check if already in PATH
    if echo "$PATH" | tr ':' '\n' | grep -q "^${INSTALL_DIR}$"; then
        return 0
    fi

    # Create profile file if it doesn't exist
    if [ -n "$shell_profile" ]; then
        if [ ! -f "$shell_profile" ]; then
            mkdir -p "$(dirname "$shell_profile")"
            touch "$shell_profile"
        fi

        if ! grep -q "SUMMONAIKIT" "$shell_profile" 2>/dev/null; then
            echo "" >> "$shell_profile"
            echo "# SummonAI Kit CLI" >> "$shell_profile"
            if [ "$shell_name" = "fish" ]; then
                echo "set -gx PATH \$PATH ${INSTALL_DIR}" >> "$shell_profile"
            else
                echo "export PATH=\"\$PATH:${INSTALL_DIR}\"" >> "$shell_profile"
            fi
            success "Added ${INSTALL_DIR} to PATH in ${shell_profile}"
        fi
    fi

    # Update PATH for current session immediately
    export PATH="$PATH:${INSTALL_DIR}"

    return 1  # Signal that shell restart is recommended for new terminals
}

main() {
    print_banner

    # Detect platform
    info "Detecting platform..."
    BINARY=$(detect_platform)
    success "Platform detected: ${BINARY}"

    # Create install directory
    info "Creating install directory: ${INSTALL_DIR}"
    mkdir -p "$INSTALL_DIR"

    # Download binary
    DEST="${INSTALL_DIR}/summonaikit"
    download_binary "$BINARY" "$DEST"
    success "Downloaded successfully"

    # Make executable
    chmod +x "$DEST"
    success "Made executable"

    # Setup PATH
    info "Setting up PATH..."
    local shell_name="${SHELL##*/}"
    if setup_path; then
        success "PATH already configured"
    else
        success "PATH updated for this session"
        warn "For new terminals, restart your shell or run: source ~/.${shell_name}rc"
    fi

    echo ""
    echo -e "${GREEN}╔═══════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}    ${BLUE}Installation complete!${NC}              ${GREEN}║${NC}"
    echo -e "${GREEN}╚═══════════════════════════════════════╝${NC}"
    echo ""
    echo "  Binary installed to: ${DEST}"
    echo ""
    echo "  Get started:"
    echo "    summonaikit          # Start the CLI"
    echo "    summonaikit help     # Show help"
    echo "    summonaikit update   # Update to latest"
    echo ""

    # Check if we can run it
    if [ -x "$DEST" ]; then
        if "$DEST" --version &> /dev/null; then
            VERSION=$("$DEST" --version 2>&1)
            success "Installed: ${VERSION}"
        fi
    fi
}

main "$@"
