#!/bin/bash
# Benchmark script for health-bridge-go vs Python health-bridge

set -e

PYTHON_PORT=3007
GO_PORT=18007

echo "=== Health Bridge Benchmark ==="
echo "Python port: $PYTHON_PORT"
echo "Go port: $GO_PORT"
echo ""

# Check if servers are running
check_server() {
    local port=$1
    local name=$2
    if curl -s --max-time 2 "http://localhost:$port/health" > /dev/null 2>&1; then
        echo "✓ $name is running on port $port"
        return 0
    else
        echo "✗ $name is NOT running on port $port"
        return 1
    fi
}

echo "Checking servers..."
check_server $PYTHON_PORT "Python server" || true
check_server $GO_PORT "Go server" || true
echo ""

# Test payload
PAYLOAD='{
  "records": [
    {"type": "steps", "count": 1000, "source": "health_connect", "local_date": "2026-06-02", "time": "2026-06-02T10:00:00Z"},
    {"type": "calories", "kcal": 250, "source": "health_connect", "local_date": "2026-06-02", "time": "2026-06-02T10:00:00Z"}
  ],
  "subject": "chicho"
}'

# Generate signed headers for ingest_signed endpoint
generate_signature() {
    local secret=$1
    local device=$2
    local timestamp=$3
    local nonce=$4
    local body=$5
    
    body_hash=$(echo -n "$body" | sha256sum | cut -d' ' -f1)
    payload="${device}
${timestamp}
${nonce}
${body_hash}"
    
    signature=$(echo -n "$payload" | openssl dgst -sha256 -hmac "$secret" | cut -d' ' -f2)
    echo "$signature"
}

# Get values from environment or use defaults
SIGNED_SECRET=${HEALTH_BRIDGE_SIGNED_INGEST_SECRET:-""}
DEVICE=${HEALTH_BRIDGE_SIGNED_INGEST_DEVICE:-"pixel9a-chicho"}

if [ -z "$SIGNED_SECRET" ]; then
    echo "Note: HEALTH_BRIDGE_SIGNED_INGEST_SECRET not set, testing /health only"
    SIGNED=false
else
    SIGNED=true
fi

benchmark_endpoint() {
    local name=$1
    local url=$2
    local method=${3:-GET}
    local headers=$4
    local body=$5
    local runs=${6:-20}
    
    echo "--- $name ---"
    echo "URL: $url"
    echo "Method: $method"
    echo "Runs: $runs"
    
    local total=0
    local min=999999
    local max=0
    
    for i in $(seq 1 $runs); do
        start=$(date +%s%N)
        
        if [ -n "$body" ]; then
            curl -s -X "$method" -H "Content-Type: application/json" $headers -d "$body" "$url" > /dev/null
        else
            curl -s "$url" > /dev/null
        fi
        
        end=$(date +%s%N)
        elapsed=$(( (end - start) / 1000000 ))
        
        total=$(( total + elapsed ))
        if [ $elapsed -lt $min ]; then min=$elapsed; fi
        if [ $elapsed -gt $max ]; then max=$elapsed; fi
    done
    
    avg=$(( total / runs ))
    
    echo "Avg latency: ${avg}ms"
    echo "Min latency: ${min}ms"
    echo "Max latency: ${max}ms"
    echo ""
}

echo "=========================================="
echo "BENCHMARK: /health endpoint"
echo "=========================================="
echo ""

benchmark_endpoint "Python /health" "http://localhost:$PYTHON_PORT/health" "GET" "" "" 50
benchmark_endpoint "Go /health" "http://localhost:$GO_PORT/health" "GET" "" "" 50

if [ "$SIGNED" = true ]; then
    echo "=========================================="
    echo "BENCHMARK: /ingest_signed endpoint"
    echo "=========================================="
    echo ""
    
    timestamp=$(date +%s)
    nonce="bench-$(date +%s%N)"
    signature=$(generate_signature "$SIGNED_SECRET" "$DEVICE" "$timestamp" "$nonce" "$PAYLOAD")
    
    python_headers="-H X-HB-Device:$DEVICE -H X-HB-Nonce:$nonce -H X-HB-Timestamp:$timestamp -H X-HB-Signature:$signature"
    go_headers="-H X-HB-Device:$DEVICE -H X-HB-Nonce:$nonce -H X-HB-Timestamp:$timestamp -H X-HB-Signature:$signature"
    
    # Warmup
    curl -s -X POST -H "Content-Type: application/json" $python_headers -d "$PAYLOAD" "http://localhost:$PYTHON_PORT/ingest_signed" > /dev/null 2>&1 || true
    curl -s -X POST -H "Content-Type: application/json" $go_headers -d "$PAYLOAD" "http://localhost:$GO_PORT/ingest_signed" > /dev/null 2>&1 || true
    
    # Wait a bit for any async processing
    sleep 0.5
    
    benchmark_endpoint "Python /ingest_signed" "http://localhost:$PYTHON_PORT/ingest_signed" "POST" "$python_headers" "$PAYLOAD" 50
    benchmark_endpoint "Go /ingest_signed" "http://localhost:$GO_PORT/ingest_signed" "POST" "$go_headers" "$PAYLOAD" 50
fi

echo "=========================================="
echo "BENCHMARK COMPLETE"
echo "=========================================="
echo ""
echo "To run the servers:"
echo "  Python: cd /home/ubuntu/health-bridge && python server.py"
echo "  Go: cd /home/ubuntu/health-bridge-go && ./health-bridge-go"