#!/usr/bin/env python3
"""Download Z-Image-Turbo GGUF models on BC-250 using wget."""
import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.178.150', username='fabian', key_filename=r'C:\Users\fabia\.ssh\id_ed25519')

def run(cmd, timeout=7200, desc=""):
    if desc:
        print(f"\n{'='*60}")
        print(f"  {desc}")
        print(f"{'='*60}")
    print(f"$ {cmd}")
    _, stdout, stderr = ssh.exec_command(cmd, timeout=timeout)
    out = stdout.read().decode()
    err = stderr.read().decode()
    rc = stdout.channel.recv_exit_status()
    if out.strip():
        lines = out.strip().split('\n')
        if len(lines) > 30:
            print(f"  ... ({len(lines)} lines, showing last 30)")
            print('\n'.join(lines[-30:]))
        else:
            print(out.strip())
    if err.strip():
        lines = err.strip().split('\n')
        show = lines[-15:] if len(lines) > 15 else lines
        print(f"STDERR: {chr(10).join(show)}")
    print(f"  Exit code: {rc}")
    return rc, out, err

dl_script = r'''#!/bin/bash
set -euo pipefail

LOG="/home/fabian/model_download.log"
exec > >(tee -a "$LOG") 2>&1

COMFY="$HOME/ComfyUI"

echo "=========================================="
echo " Downloading Z-Image-Turbo GGUF Models"
echo " Started: $(date)"
echo "=========================================="

# 1. Diffusion model (5.19 GB)
echo ""
echo "[1/3] Downloading z_image_turbo-Q5_K_S.gguf (5.19 GB)..."
DEST1="$COMFY/models/diffusion_models/z_image_turbo-Q5_K_S.gguf"
if [ -f "$DEST1" ]; then
    echo "  Already exists ($(du -h "$DEST1" | cut -f1)), skipping."
else
    wget -c -q --show-progress \
        "https://huggingface.co/jayn7/Z-Image-Turbo-GGUF/resolve/main/z_image_turbo-Q5_K_S.gguf" \
        -O "$DEST1.tmp"
    mv "$DEST1.tmp" "$DEST1"
    echo "  Done: $(du -h "$DEST1" | cut -f1)"
fi

# 2. Text encoder Qwen3-4B (2.82 GB)
echo ""
echo "[2/3] Downloading Qwen3-4B.i1-Q5_K_S.gguf (2.82 GB)..."
DEST2="$COMFY/models/text_encoders/Qwen3-4B.i1-Q5_K_S.gguf"
if [ -f "$DEST2" ]; then
    echo "  Already exists ($(du -h "$DEST2" | cut -f1)), skipping."
else
    wget -c -q --show-progress \
        "https://huggingface.co/mradermacher/Qwen3-4B-i1-GGUF/resolve/main/Qwen3-4B.i1-Q5_K_S.gguf" \
        -O "$DEST2.tmp"
    mv "$DEST2.tmp" "$DEST2"
    echo "  Done: $(du -h "$DEST2" | cut -f1)"
fi

# 3. VAE (335 MB)
echo ""
echo "[3/3] Downloading ae.safetensors (VAE, 335 MB)..."
DEST3="$COMFY/models/vae/ae.safetensors"
if [ -f "$DEST3" ]; then
    echo "  Already exists ($(du -h "$DEST3" | cut -f1)), skipping."
else
    wget -c -q --show-progress \
        "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/vae/ae.safetensors" \
        -O "$DEST3.tmp"
    mv "$DEST3.tmp" "$DEST3"
    echo "  Done: $(du -h "$DEST3" | cut -f1)"
fi

echo ""
echo "=========================================="
echo " Model Download Summary"
echo "=========================================="
echo "Diffusion model:"
ls -lh "$COMFY/models/diffusion_models/"*.gguf 2>/dev/null || echo "  NOT FOUND"
echo "Text encoder:"
ls -lh "$COMFY/models/text_encoders/"*.gguf 2>/dev/null || echo "  NOT FOUND"
echo "VAE:"
ls -lh "$COMFY/models/vae/"*.safetensors 2>/dev/null || echo "  NOT FOUND"
echo ""
echo "Total model size:"
du -sh "$COMFY/models/"
echo ""
echo "DOWNLOAD_COMPLETE"
echo "Finished: $(date)"
'''

# Upload download script
sftp = ssh.open_sftp()
with sftp.open('/home/fabian/download_models.sh', 'w') as f:
    f.write(dl_script)
sftp.close()

run("chmod +x /home/fabian/download_models.sh", desc="Make script executable")
run("rm -f /home/fabian/model_download.log", desc="Clean old log")
run("bash -c 'which wget'", desc="Verify wget exists")

# Start download in background via nohup
run("bash -c 'nohup bash /home/fabian/download_models.sh </dev/null >/dev/null 2>&1 & echo PID=$!'",
    desc="Start model download in background")

time.sleep(15)
run("tail -20 /home/fabian/model_download.log 2>/dev/null || echo 'Waiting for log...'",
    desc="Initial download progress")

# Monitor download progress - check every 60s for up to 30 minutes
for i in range(30):
    time.sleep(60)
    rc, out, _ = run(f"tail -5 /home/fabian/model_download.log 2>/dev/null; echo '---'; "
                     f"ls -lh ~/ComfyUI/models/diffusion_models/ ~/ComfyUI/models/text_encoders/ ~/ComfyUI/models/vae/ 2>/dev/null",
        desc=f"Progress check {i+1}/30 ({(i+1)}min)")
    if 'DOWNLOAD_COMPLETE' in out:
        print("\n  ALL DOWNLOADS COMPLETE!")
        break
    # Check if background process still running
    _, pout, _ = run("bash -c 'pgrep -f download_models.sh || echo NOPROCESS'")
    if 'NOPROCESS' in pout and 'DOWNLOAD_COMPLETE' not in out:
        print("\n  WARNING: Download process exited without completion!")
        run("cat /home/fabian/model_download.log", desc="Full download log")
        break

# Final verification
run("tail -25 /home/fabian/model_download.log 2>/dev/null", desc="Final download status")
run("du -sh ~/ComfyUI/models/diffusion_models/ ~/ComfyUI/models/text_encoders/ ~/ComfyUI/models/vae/",
    desc="Model directory sizes")

ssh.close()
print("\nDone.")
