#!/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)
            if [ "$os" = "Linux" ]; then
                # Linux terminals normally start an interactive NON-login
                # shell, which reads .bashrc.
                shell_profile="$HOME/.bashrc"
            else
                # macOS Terminal (and iTerm2, by default) opens bash as a
                # LOGIN shell, which reads .bash_profile (or .bash_login, or
                # .profile) -- never .bashrc, unless .bash_profile happens to
                # source it. Writing to .bashrc here, which used to happen on
                # any machine that had not already created a .bash_profile,
                # left the PATH change invisible in every new terminal window
                # opened after this script ran, so `summonaikit` looked
                # installed but stayed unrunnable by name until someone found
                # this by hand. Created below if it does not exist yet.
                shell_profile="$HOME/.bash_profile"
            fi
            ;;
        zsh)
            shell_profile="$HOME/.zshrc"
            ;;
        fish)
            shell_profile="$HOME/.config/fish/config.fish"
            ;;
        *)
            shell_profile="$HOME/.profile"
            ;;
    esac

    # Exposed to the caller so the "restart or source X" message names the
    # file this function actually wrote, rather than a guess reconstructed
    # from the shell name after the fact (that guess used to say .bashrc even
    # on the macOS branch above, which writes .bash_profile instead).
    SUMMONAIKIT_SHELL_PROFILE="$shell_profile"

    # 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..."
    SUMMONAIKIT_SHELL_PROFILE=""
    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 ${SUMMONAIKIT_SHELL_PROFILE}"
    fi

    echo ""
    echo -e "${GREEN}╔═══════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}    ${BLUE}Installation complete!${NC}              ${GREEN}║${NC}"
    echo -e "${GREEN}╚═══════════════════════════════════════╝${NC}"
    echo ""
    # The absolute path, printed on its own line and repeated below: a
    # freshly opened shell (including one an assistant's own tool starts,
    # which never re-reads the profile file just written above) cannot find
    # `summonaikit` by name until a NEW terminal picks up the PATH change.
    # This exact path always works, in the meantime, with no PATH change
    # needed at all.
    echo "  Binary installed to: ${DEST}"
    echo ""
    echo "  Get started:"
    echo "    summonaikit          # Start the CLI (once a new terminal picks up the PATH change)"
    echo "    ${DEST}          # Same thing, right now, by its full path"
    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 "$@"
