#!/usr/bin/env python3
"""Download Z-Image-Turbo GGUF model checkpoints on BC-250.

Files needed (GGUF format — memory-efficient for 14GB RAM):
1. z_image_turbo-Q5_K_S.gguf (5.19 GB) → diffusion_models/
2. Qwen3-4B.i1-Q5_K_S.gguf  (2.82 GB) → text_encoders/
3. ae.safetensors             (335 MB)  → vae/
Total: ~8.35 GB
"""
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=3600, 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

# Create download script for background execution
dl_script = '''#!/bin/bash
set -euo pipefail

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

source /home/fabian/comfyui-env/bin/activate

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)..."
if [ -f "$COMFY/models/diffusion_models/z_image_turbo-Q5_K_S.gguf" ]; then
    echo "  Already exists, skipping."
else
    HF_XET_HIGH_PERFORMANCE=1 huggingface-cli download \
        jayn7/Z-Image-Turbo-GGUF \
        z_image_turbo-Q5_K_S.gguf \
        --local-dir "$COMFY/models/diffusion_models/" \
        --local-dir-use-symlinks False
    echo "  Done."
fi

# 2. Text encoder Qwen3-4B (2.82 GB)
echo ""
echo "[2/3] Downloading Qwen3-4B.i1-Q5_K_S.gguf (2.82 GB)..."
if [ -f "$COMFY/models/text_encoders/Qwen3-4B.i1-Q5_K_S.gguf" ]; then
    echo "  Already exists, skipping."
else
    HF_XET_HIGH_PERFORMANCE=1 huggingface-cli download \
        mradermacher/Qwen3-4B-i1-GGUF \
        Qwen3-4B.i1-Q5_K_S.gguf \
        --local-dir "$COMFY/models/text_encoders/" \
        --local-dir-use-symlinks False
    echo "  Done."
fi

# 3. VAE (335 MB)
echo ""
echo "[3/3] Downloading ae.safetensors (VAE, 335 MB)..."
if [ -f "$COMFY/models/vae/ae.safetensors" ]; then
    echo "  Already exists, skipping."
else
    HF_XET_HIGH_PERFORMANCE=1 huggingface-cli download \
        Comfy-Org/z_image_turbo \
        split_files/vae/ae.safetensors \
        --local-dir "$COMFY/models/vae/" \
        --local-dir-use-symlinks False
    # Move from subdirectory if needed
    if [ -f "$COMFY/models/vae/split_files/vae/ae.safetensors" ]; then
        mv "$COMFY/models/vae/split_files/vae/ae.safetensors" "$COMFY/models/vae/ae.safetensors"
        rm -rf "$COMFY/models/vae/split_files"
    fi
    echo "  Done."
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 download script executable")
run("rm -f /home/fabian/model_download.log", desc="Clean old log")

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

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

# Keep checking
for i in range(6):
    time.sleep(30)
    rc, out, _ = run(f"tail -10 /home/fabian/model_download.log 2>/dev/null",
        desc=f"Download progress check {i+1}")
    if 'DOWNLOAD_COMPLETE' in out:
        print("\n  ALL DOWNLOADS COMPLETE!")
        break

# Final check
run("tail -20 /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/ 2>/dev/null",
    desc="Model directory sizes")

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