#!/usr/bin/env bash
# ==============================================================================
# Project HiveMind@home & OpenRouter — 1-Command GPU Producer Onboarding Script
# Reciprocity Unit: HiveMind Points (HMT) • <1.5s Instant Game Preemption SLA
# ==============================================================================
set -euo pipefail

GATEWAY_URL="${HIVEMIND_GATEWAY_URL:-https://hivemind-at-home-ruche-cfhmhmvv5a-uc.a.run.app}"
echo "🐝 Welcome to Project HiveMind@home & La Ruche GPU Producer Onboarding!"
echo "🌐 Active Gateway: ${GATEWAY_URL}"
echo "🪙 Reciprocity Model: HiveMind Points (HMT) — Earn 85% Tullock GPU Payouts"
echo ""

# 1. Detect GPU VRAM if nvidia-smi is available
VRAM_GB=""
if command -v nvidia-smi >/dev/null 2>&1; then
  VRAM_MIB="$(nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits | head -n 1 | tr -d ' ')"
  if [ -n "${VRAM_MIB}" ]; then
    VRAM_GB="$(python3 -c "print(round(float('${VRAM_MIB}')/1024.0, 1))")"
    GPU_NAME="$(nvidia-smi --query-gpu=name --format=csv,noheader | head -n 1)"
    echo "✅ Detected NVIDIA GPU: ${GPU_NAME} (${VRAM_GB} GB VRAM)"
  fi
fi

# 2. Download standalone producer agent & Zero-Trust Producer Shield
echo "⬇️  Downloading standalone hivemind_producer_agent.py & hivemind_producer_shield.py..."
curl -fsSL "${GATEWAY_URL}/hivemind_producer_agent.py" -o hivemind_producer_agent.py
curl -fsSL "${GATEWAY_URL}/hivemind_producer_shield.py" -o hivemind_producer_shield.py
chmod +x hivemind_producer_agent.py hivemind_producer_shield.py

# 3. Ensure httpx, fastapi, uvicorn are installed for Agent + Shield
if ! python3 -c "import httpx, fastapi, uvicorn" >/dev/null 2>&1; then
  echo "📦 Installing lightweight HTTP & Shield dependencies (httpx, fastapi, uvicorn)..."
  pip install --user --quiet httpx fastapi uvicorn || pip install --quiet httpx fastapi uvicorn
fi

# 4. Recommend optimal capability tier for this GPU
echo ""
echo "🔍 Querying HiveMind Capability Catalog for your GPU..."
if [ -n "${VRAM_GB}" ]; then
  python3 hivemind_producer_agent.py --gateway "${GATEWAY_URL}" --suggest --vram-gb "${VRAM_GB}" || true
else
  python3 hivemind_producer_agent.py --gateway "${GATEWAY_URL}" --suggest --vram-gb 8 || true
fi

ENDPOINT_TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"
echo ""
echo "=============================================================================="
echo "🛡️ SAFE & EASY GPU PRODUCER ONBOARDING (T4 16GB / RTX 2070 8GB / ANY GPU):"
echo "=============================================================================="
echo "1. Pull & run your recommended Ollama model locally:"
echo "   • RTX 2070 (8 GB) / Consumer 8 GB:  ollama run qwen2.5-coder:7b"
echo "   • Tesla T4 (16 GB) / 12-16 GB GPU:  ollama run qwen2.5-coder:14b"
echo ""
echo "2. Start the Zero-Trust Producer Shield (protects your local Ollama on port 8787"
echo "   so ONLY the HiveMind Gateway with your secret token can query your GPU):"
echo "   export HIVEMIND_ENDPOINT_TOKEN="${ENDPOINT_TOKEN}""
echo "   python3 hivemind_producer_shield.py --upstream http://127.0.0.1:11434 --port 8787 --max-concurrent 2 &"
echo ""
echo "3. Export your hm-... key (from ${GATEWAY_URL}/openrouter) & start the Agent:"
echo "   export HIVEMIND_API_KEY=hm-YOUR_KEY"
echo "   python3 hivemind_producer_agent.py \\"
echo "     --gateway ${GATEWAY_URL} \\"
echo "     --endpoint https://YOUR_PUBLIC_TUNNEL_TO_PORT_8787 \\"
echo "     --preset coder --sync-remote-config"
echo "=============================================================================="
