#!/bin/bash
# BlackRoad Stats Push — runs on Pi cron, fetches stats from local proxy and pushes to Worker KV

PROXY_URL="http://localhost:7890/stats"
WORKER_URL="https://portfolio-stats-api.amundsonalexa.workers.dev/push"

# Load secret from env file if not already set
if [ -z "$PUSH_SECRET" ] && [ -f /opt/blackroad/stats-push.env ]; then
    export $(grep -v '^#' /opt/blackroad/stats-push.env | xargs)
fi

if [ -z "$PUSH_SECRET" ]; then
    echo "ERROR: PUSH_SECRET not set"
    exit 1
fi

# Fetch stats from local proxy
STATS=$(curl -s --connect-timeout 10 --max-time 60 "$PROXY_URL" 2>/dev/null)

if [ -z "$STATS" ] || ! echo "$STATS" | python3 -c "import sys,json; json.load(sys.stdin)" 2>/dev/null; then
    echo "ERROR: Failed to get stats from local proxy"
    exit 1
fi

# Push to Worker
RESPONSE=$(curl -s --connect-timeout 10 --max-time 15 \
    -X POST "$WORKER_URL" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $PUSH_SECRET" \
    -d "$STATS" 2>/dev/null)

echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $(hostname): $RESPONSE"
