#!/bin/bash
# Test image generation via ComfyUI API
# Workflow: Z-Image Turbo GGUF + Gemma2 CLIP + AE VAE

API="http://127.0.0.1:8188"

echo "=== Checking ComfyUI API ==="
curl -s "$API/system_stats" | python3.11 -m json.tool 2>/dev/null | head -20
echo ""

echo "=== Listing available models ==="
curl -s "$API/models/unet" 2>/dev/null
echo ""
curl -s "$API/models/clip" 2>/dev/null  
echo ""
curl -s "$API/models/vae" 2>/dev/null
echo ""

echo "=== Queueing image generation ==="
WORKFLOW='{
  "prompt": {
    "1": {
      "class_type": "UNETLoader",
      "inputs": {
        "unet_name": "z_image_turbo-Q5_K_S.gguf",
        "weight_dtype": "default"
      }
    },
    "2": {
      "class_type": "DualCLIPLoader",
      "inputs": {
        "clip_name1": "gemma2_2b_lumina2.safetensors",
        "clip_name2": "gemma2_2b_lumina2.safetensors",
        "type": "lumina2"
      }
    },
    "3": {
      "class_type": "CLIPTextEncode",
      "inputs": {
        "text": "a beautiful mountain landscape at sunset, golden light, detailed, 4k",
        "clip": ["2", 0]
      }
    },
    "4": {
      "class_type": "CLIPTextEncode",
      "inputs": {
        "text": "blurry, ugly, distorted",
        "clip": ["2", 0]
      }
    },
    "5": {
      "class_type": "EmptyLatentImage",
      "inputs": {
        "width": 512,
        "height": 512,
        "batch_size": 1
      }
    },
    "6": {
      "class_type": "KSampler",
      "inputs": {
        "model": ["1", 0],
        "positive": ["3", 0],
        "negative": ["4", 0],
        "latent_image": ["5", 0],
        "seed": 42,
        "steps": 8,
        "cfg": 3.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"
      }
    }
  }
}'

RESPONSE=$(curl -s -X POST "$API/prompt" -H "Content-Type: application/json" -d "$WORKFLOW")
echo "Queue response: $RESPONSE"
PROMPT_ID=$(echo "$RESPONSE" | python3.11 -c "import sys,json; print(json.load(sys.stdin).get('prompt_id','NONE'))" 2>/dev/null)
echo "Prompt ID: $PROMPT_ID"

if [ "$PROMPT_ID" = "NONE" ] || [ -z "$PROMPT_ID" ]; then
    echo "ERROR: Failed to queue prompt!"
    exit 1
fi

echo ""
echo "=== Waiting for generation ==="
for i in $(seq 1 60); do
    sleep 5
    STATUS=$(curl -s "$API/history/$PROMPT_ID" 2>/dev/null)
    HAS_OUTPUT=$(echo "$STATUS" | python3.11 -c "
import sys, json
data = json.load(sys.stdin)
if '$PROMPT_ID' in data:
    outputs = data['$PROMPT_ID'].get('outputs', {})
    if '9' in outputs:
        images = outputs['9'].get('images', [])
        if images:
            print('DONE:' + images[0].get('filename', 'unknown'))
        else:
            print('PROCESSING')
    else:
        print('PROCESSING')
else:
    print('WAITING')
" 2>/dev/null)
    echo "[$((i*5))s] $HAS_OUTPUT"
    if [[ "$HAS_OUTPUT" == DONE:* ]]; then
        FILENAME=${HAS_OUTPUT#DONE:}
        echo ""
        echo "=== SUCCESS ==="
        echo "Image generated: $FILENAME"
        echo "File location: /home/fabian/ComfyUI/output/$FILENAME"
        ls -lh "/home/fabian/ComfyUI/output/$FILENAME" 2>/dev/null
        exit 0
    fi
done

echo "TIMEOUT: Generation did not complete in 5 minutes"
echo "=== Checking queue ==="
curl -s "$API/queue" | python3.11 -m json.tool 2>/dev/null | head -20
