#!/bin/bash

# AITBC GPU Miner Startup Script
# Copy to start_gpu_miner.sh and adjust variables for your environment

set -e

# === CONFIGURE THESE ===
COORDINATOR_URL="http://YOUR_COORDINATOR_IP:18000"
MINER_API_KEY="your_miner_api_key"
OLLAMA_HOST="http://127.0.0.1:11434"
GPU_ID="gpu-0"

echo "🔧 Starting AITBC GPU Miner"
echo "Coordinator: $COORDINATOR_URL"
echo "Ollama: $OLLAMA_HOST"
echo ""

# Check Ollama is running
if ! curl -s "$OLLAMA_HOST/api/tags" > /dev/null 2>&1; then
    echo "❌ Ollama not running at $OLLAMA_HOST"
    echo "Start it with: ollama serve"
    exit 1
fi

echo "✅ Ollama is running"

# Check GPU
if command -v nvidia-smi &> /dev/null; then
    echo "GPU detected:"
    nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
else
    echo "⚠️  No NVIDIA GPU detected (CPU-only mode)"
fi

# Register miner
echo ""
echo "Registering miner with coordinator..."
curl -s -X POST "$COORDINATOR_URL/v1/miners/register" \
    -H "X-Api-Key: $MINER_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"gpu_id\": \"$GPU_ID\", \"ollama_url\": \"$OLLAMA_HOST\"}"

echo ""
echo "✅ Miner registered. Starting heartbeat loop..."

# Heartbeat + job polling loop
while true; do
    curl -s -X POST "$COORDINATOR_URL/v1/miners/heartbeat" \
        -H "X-Api-Key: $MINER_API_KEY" > /dev/null 2>&1
    sleep 10
done
