#!/bin/bash
# Queue a prompt to ComfyUI via API
# This uses the API format, not the workflow format

PROMPT='{
  "1": {
    "class_type": "CLIPLoaderGGUF",
    "inputs": {
      "clip_name": "Qwen_3_4b-Q8_0.gguf",
      "type": "lumina2"
    }
  },
  "2": {
    "class_type": "CLIPTextEncode",
    "inputs": {
      "text": "a beautiful mountain landscape at sunset, golden hour, dramatic clouds, 8k photography",
      "clip": ["1", 0]
    }
  },
  "3": {
    "class_type": "CLIPTextEncode",
    "inputs": {
      "text": "",
      "clip": ["1", 0]
    }
  },
  "4": {
    "class_type": "UnetLoaderGGUF",
    "inputs": {
      "unet_name": "z_image_turbo-Q5_K_S.gguf"
    }
  },
  "5": {
    "class_type": "EmptyLatentImage",
    "inputs": {
      "width": 512,
      "height": 512,
      "batch_size": 1
    }
  },
  "6": {
    "class_type": "KSampler",
    "inputs": {
      "model": ["4", 0],
      "positive": ["2", 0],
      "negative": ["3", 0],
      "latent_image": ["5", 0],
      "seed": 42,
      "steps": 4,
      "cfg": 1.0,
      "sampler_name": "euler",
      "scheduler": "normal",
      "denoise": 1.0
    }
  },
  "7": {
    "class_type": "VAELoader",
    "inputs": {
      "vae_name": "ae.safetensors"
    }
  },
  "8": {
    "class_type": "VAEDecode",
    "inputs": {
      "samples": ["6", 0],
      "vae": ["7", 0]
    }
  },
  "9": {
    "class_type": "SaveImage",
    "inputs": {
      "images": ["8", 0],
      "filename_prefix": "BC250_test"
    }
  }
}'

echo "Queueing prompt..."
RESULT=$(curl -s -X POST http://localhost:8188/prompt \
  -H "Content-Type: application/json" \
  -d "{\"prompt\": $PROMPT}")
echo "Result: $RESULT"
PROMPT_ID=$(echo "$RESULT" | python3 -c "import json,sys; print(json.load(sys.stdin).get('prompt_id','FAILED'))" 2>/dev/null)
echo "Prompt ID: $PROMPT_ID"

# Monitor progress
echo "Monitoring..."
for i in $(seq 1 120); do
  sleep 5
  STATUS=$(curl -s http://localhost:8188/queue)
  RUNNING=$(echo "$STATUS" | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d.get('queue_running',[])))" 2>/dev/null)
  PENDING=$(echo "$STATUS" | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d.get('queue_pending',[])))" 2>/dev/null)
  echo "t+$((i*5))s: running=$RUNNING pending=$PENDING"
  
  if [ "$RUNNING" = "0" ] && [ "$PENDING" = "0" ]; then
    echo "DONE! Queue empty."
    # Check if image was saved
    ls -la /home/fabian/ComfyUI/output/BC250_test* 2>/dev/null | tail -5
    break
  fi
done
