#!/bin/bash
# AgntSpace installer
# Usage: curl -fsSL https://www.agntspace.com/install.sh | bash
set -e

echo ""
echo "  AGNTSPACE — Your AI partner"
echo "  ============================="
echo ""

# Find Python 3.11+
PY=""
for cmd in python3 python; do
    if command -v "$cmd" &> /dev/null; then
        ver=$("$cmd" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
        major=$(echo "$ver" | cut -d. -f1)
        minor=$(echo "$ver" | cut -d. -f2)
        if [ "$major" -ge 3 ] && [ "$minor" -ge 11 ]; then
            PY="$cmd"
            break
        fi
    fi
done

if [ -z "$PY" ]; then
    echo "  Python 3.11+ is required."
    echo "  Download from: https://www.python.org/downloads/"
    echo ""
    exit 1
fi

echo "  $($PY --version) found"

# Ensure pip is available
$PY -m ensurepip --upgrade 2>/dev/null || true

# Install
echo "  Installing agntspace..."
if ! $PY -m pip install --upgrade --no-cache-dir agntspace 2>/dev/null; then
    echo ""
    echo "  pip install failed. Check your internet connection and that"
    echo "  pip is up to date: $PY -m pip install --upgrade pip"
    echo ""
    echo "  For help: https://agntspace.com"
    echo ""
    exit 1
fi

# Verify
if ! command -v agntspace &> /dev/null; then
    echo "  agntspace command not found. Try: $PY -m agntspace.cli --help"
    exit 1
fi

# Anonymous install ping (version + OS only, no IP/UA/cookies).
# Privacy: https://agntspace.com/privacy#install-ping
INSTALLED_VERSION=$("$PY" -c "from importlib.metadata import version; print(version('agntspace'))" 2>/dev/null) || INSTALLED_VERSION=""
INSTALL_PING_OS=$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')
case "$INSTALL_PING_OS" in
    darwin*) INSTALL_PING_OS="darwin" ;;
    *)       INSTALL_PING_OS="linux" ;;
esac
curl -sf -m 5 -X POST https://agntspace.com/api/install-ping \
    -H "Content-Type: application/json" \
    -d "{\"version\":\"$INSTALLED_VERSION\",\"os\":\"$INSTALL_PING_OS\"}" \
    >/dev/null 2>&1 || true

# Initialize
echo "  Initializing..."
agntspace init --minimal

echo ""
echo "  Done! Start your agent:"
echo ""
echo "    agntspace start"
echo ""
echo "  Then open http://localhost:8000"
echo ""
