#!/usr/bin/env bash
# gpu.sh — the ONLY way pipeline agents touch GPU jobs on miri-desktop.
#
# Subcommands:
#   gpu.sh check                       — ComfyUI health (exit 1 if down; report, never restart)
#   gpu.sh comfy-gen <args...>         — image generation (z-image-turbo ~35s, flux3-klein-gguf ~6min)
#   gpu.sh ssh <command...>            — arbitrary command on miri-desktop (use sparingly)
#
# Tip: pass generous tool/shell timeouts (z-image 300s, flux3 900s+); calls block until done.
set -euo pipefail
HOST=miri-desktop
CMD="${1:-check}"; shift || true

case "$CMD" in
  check)
    if ssh -o ConnectTimeout=8 "$HOST" curl -s -m 5 http://127.0.0.1:8188/system_stats 2>/dev/null | grep -q "devices"; then
      echo "OK: ComfyUI reachable on $HOST"
      ssh "$HOST" curl -s -m 5 http://127.0.0.1:8188/system_stats 2>/dev/null | python3 -c "
import json, sys
d = json.load(sys.stdin)
for dev in d.get('devices', []):
    print(f\"  {dev.get('name','?')} — {dev.get('vram_total',0)//2**30}GB VRAM\")
" 2>/dev/null || true
    else
      echo "DOWN: ComfyUI not reachable on $HOST — report to the user; do not restart it (log: miri-desktop:~/comfyui/comfy.log)" >&2
      exit 1
    fi ;;
  comfy-gen)
    exec /usr/local/bin/comfy-gen "$@" ;;
  ssh)
    exec ssh "$HOST" "$@" ;;
  *)
    echo "usage: gpu.sh check | comfy-gen <args...> | ssh <cmd...>" >&2
    exit 2 ;;
esac
