#!/usr/bin/env bash
# BlackRoad Shell Interpreter
# Routes all input through BlackRoad OS fleet AI
set -eo pipefail

source "$HOME/.blackroad/config/nodes.sh" 2>/dev/null || true

QUERY="$*"
[[ -z "$QUERY" ]] && { echo "Usage: blackroad-shell \"query\""; exit 1; }

echo "╔═══════════════════════════════════════╗"
echo "║       DIG - BlackRoad AI Query        ║"
echo "╚═══════════════════════════════════════╝"
echo ""
echo "; <<>> DIG AI <<>> $QUERY"
echo ""

# Try fleet Ollama nodes via HTTP (safe JSON via jq)
for node in cecilia lucidia alice; do
  ip="${NODE_IP[$node]:-}"
  [[ -z "$ip" ]] && continue

  response=$(curl -sf --max-time 30 "http://${ip}:11434/api/generate" \
    -d "$(jq -n --arg p "$QUERY" '{model: "llama3.2", prompt: $p, stream: false}')" 2>/dev/null | \
    jq -r '.response // empty' 2>/dev/null)

  if [[ -n "$response" ]]; then
    echo "$response"
    exit 0
  fi
done

echo "BLACKROAD: all nodes offline"
