#!/usr/bin/env bash
set -e

echo "================================================="
echo "   🚀 Installing AXIOM Agent CLI (Terminal IDE)  "
echo "================================================="

# Detect OS and Arch
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

if [ "$ARCH" = "x86_64" ]; then
    ARCH="amd64"
elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
    ARCH="arm64"
fi

echo "Detected OS: $OS | Architecture: $ARCH"

DOWNLOAD_URL="https://agent.axiom.farm/downloads/agent/${OS}-${ARCH}/axiom-agent"
BIN_DIR="$HOME/.local/bin"
EXE="$BIN_DIR/axiom-agent"

mkdir -p "$BIN_DIR"

echo "Downloading AXIOM Agent from $DOWNLOAD_URL..."
curl -sSL --fail "$DOWNLOAD_URL" -o "$EXE" || {
    echo "❌ Pre-built binary not found for ${OS}-${ARCH}."
    echo "Falling back to installing from source via Cargo..."
    if command -v cargo &> /dev/null; then
        cargo install --git git@axiomcore:axiom.git axiom-agent-cli
        echo "✅ Installed via Cargo!"
        exit 0
    else
        echo "❌ Cargo not found. Please install Rust (rustup.rs) or contact support."
        exit 1
    fi
}

chmod +x "$EXE"

# Fix "zsh: killed" for ad-hoc signed binaries on Apple Silicon
if [ "$OS" = "darwin" ]; then
    xattr -d com.apple.quarantine "$EXE" 2>/dev/null || true
    echo "Applying local code signature to satisfy macOS Gatekeeper..."
    codesign --force --deep --sign - "$EXE" 2>/dev/null || true
fi

# Add to PATH if not already
if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
    echo "Adding $BIN_DIR to your PATH in ~/.bashrc and ~/.zshrc..."
    echo "export PATH=\"$BIN_DIR:\$PATH\"" >> "$HOME/.bashrc"
    echo "export PATH=\"$BIN_DIR:\$PATH\"" >> "$HOME/.zshrc"
    export PATH="$BIN_DIR:$PATH"
fi

echo ""
echo "✅ AXIOM Agent CLI installed successfully!"
echo "Run 'axiom-agent' to start the Terminal IDE."
echo "If command is not found, restart your terminal or run: source ~/.zshrc"
echo ""
echo "📖 Documentation: https://agent.axiom.farm"
echo "💬 Need help?     https://git.axiom.farm/AXIOMCore/axiom/issues"
