"""Just start ComfyUI and submit workflow. All patches applied."""
import paramiko, time, json

k = paramiko.Ed25519Key.from_private_key_file(r'C:\Users\fabia\.ssh\id_ed25519')
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('192.168.178.150', username='fabian', pkey=k, timeout=10)
sftp = c.open_sftp()

def sh(cmd, t=30):
    ch = c.get_transport().open_session()
    ch.settimeout(t)
    ch.exec_command('/bin/bash -l -c ' + "'" + cmd.replace("'", "'\\''") + "'")
    o = b""
    while True:
        try:
            d = ch.recv(65536)
            if not d: break
            o += d
        except: break
    ch.close()
    return o.decode(errors='replace').strip()

# Kill any leftover, clean logs
sh('pkill -9 -f "python3.*main.py" 2>/dev/null; sleep 1')
sh('rm -f /tmp/comfyui.log; rm -f ~/ComfyUI/output/ZImageTurbo_GPU*.png')

# Start
sh('nohup /tmp/run_comfyui.sh > /tmp/comfyui.log 2>&1 &')
time.sleep(5)
pid = sh('pgrep -f "python3.*main.py"')
print(f"Started PID: {pid}")

# Wait for HTTP
for i in range(60):
    r = sh('curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8188/ 2>/dev/null', t=5)
    if '200' in r:
        print(f"HTTP ready ({i*2}s)")
        break
    time.sleep(2)

# Confirm SHARED
log = ''
try:
    with sftp.open('/tmp/comfyui.log', 'r') as f:
        log = f.read().decode(errors='replace')
except: pass
for l in log.split('\n'):
    s = l.strip()
    if any(x in s for x in ['vram state', 'SHARED', 'Device:']): print(f"  {s}")

# Submit
wf = {"prompt": {
    "1": {"class_type": "UnetLoaderGGUF", "inputs": {"unet_name": "z_image_turbo-Q5_K_S.gguf"}},
    "2": {"class_type": "CLIPLoaderGGUF", "inputs": {"clip_name": "Qwen3-4B.i1-Q5_K_S.gguf", "type": "qwen_image"}},
    "3": {"class_type": "VAELoader", "inputs": {"vae_name": "ae.safetensors"}},
    "4": {"class_type": "CLIPTextEncode", "inputs": {"text": "A red fox in a snowy forest, photorealistic", "clip": ["2", 0]}},
    "5": {"class_type": "EmptyLatentImage", "inputs": {"width": 512, "height": 512, "batch_size": 1}},
    "6": {"class_type": "KSampler", "inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["4", 0],
        "latent_image": ["5", 0], "seed": 99999, "steps": 8, "cfg": 1.0,
        "sampler_name": "euler", "scheduler": "simple", "denoise": 1.0}},
    "7": {"class_type": "VAEDecode", "inputs": {"samples": ["6", 0], "vae": ["3", 0]}},
    "8": {"class_type": "SaveImage", "inputs": {"images": ["7", 0], "filename_prefix": "ZImageTurbo_GPU"}}
}}
with sftp.open('/tmp/wf.json', 'w') as f:
    f.write(json.dumps(wf))
print("Submitting...")
resp = sh('curl -s -X POST http://127.0.0.1:8188/prompt -H "Content-Type: application/json" -d @/tmp/wf.json')
print(f"  {resp[:120]}")

# Monitor
t0 = time.time()
shown = set()
for i in range(150):
    el = int(time.time() - t0)
    try:
        with sftp.open('/tmp/comfyui.log', 'r') as f:
            log = f.read().decode(errors='replace')
    except: log = ''

    for l in log.split('\n'):
        s = l.strip()
        if s and s not in shown and any(x in s for x in ['/8', 'loaded', 'load device', 'offload device',
                'Requested', 'VAE', 'Prompt executed', 'Error', 'OOM', 'CUDA']):
            if 'FETCH' not in s and 'audio_vae' not in s and 'split attention' not in s:
                gpu = sh('cat /sys/class/drm/card0/device/gpu_busy_percent 2>/dev/null', t=3)
                print(f"  [{el:>3}s] GPU:{gpu}% {s[-110:]}")
                shown.add(s)

    imgs = sh('ls ~/ComfyUI/output/ZImageTurbo_GPU*.png 2>/dev/null', t=5)
    if imgs:
        print(f"\n*** DONE in {el}s! ***")
        for l in log.split('\n'):
            s = l.strip()
            if 'Prompt executed' in s: print(f"  {s}")
        break

    if sh('pgrep -f "python3.*main.py" >/dev/null && echo Y || echo N', t=5) == 'N':
        print(f"\nCRASHED at {el}s!")
        for l in log.split('\n')[-15:]:
            if l.strip(): print(f"  {l.strip()}")
        break

    time.sleep(4)

sftp.close()
c.close()
