#!/usr/bin/env bash
# ==============================================================================
# Automated Asset Downloader for ComfyUI Lab Recipe
# Recipe: Civitai #133005: Seoul Candid Street & Cafe Lookbook (10 Poses) - Juggernaut XL v9
# Origin: https://decomfy.com/civitai-juggernaut-korean-candid-lookbook
# ==============================================================================
set -euo pipefail

# 1. ComfyUI directory location (Defaults to current working directory)
COMFY_DIR="${1:-.}"

# 2. Civitai API key (Optional: Set export CIVITAI_TOKEN="your_key" if gated)
CIVITAI_TOKEN="${CIVITAI_TOKEN:-}"

echo "===================================================================="
echo "ComfyUI Lab: Downloading assets for: civitai-juggernaut-korean-candid-lookbook"
echo "Target ComfyUI root: ${COMFY_DIR}"
echo "===================================================================="

# Create required directories
echo "==> Ensuring model directories exist..."
mkdir -p "${COMFY_DIR}/user/default/workflows"
mkdir -p "${COMFY_DIR}/models/checkpoints"

# Download Workflow JSON
echo "==> Fetching Workflow Canvas JSON..."
curl -sSL "https://decomfy.com/api/workflows/civitai-juggernaut-korean-candid-lookbook.json" -o "${COMFY_DIR}/user/default/workflows/civitai-juggernaut-korean-candid-lookbook.json"
echo "[OK] Saved workflow to ${COMFY_DIR}/user/default/workflows/civitai-juggernaut-korean-candid-lookbook.json"

echo "==> Downloading required models and weights..."
  # Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors (6.62 GB) -> models/checkpoints/
  if [ ! -f "${COMFY_DIR}/models/checkpoints/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors" ]; then
    echo "[+] Downloading Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors (6.62 GB)..."
    URL="https://civitai.com/api/download/models/348913"
    if [ -n "$CIVITAI_TOKEN" ]; then
      if [[ "$URL" == *"?"* ]]; then
        URL="${URL}&token=${CIVITAI_TOKEN}"
      else
        URL="${URL}?token=${CIVITAI_TOKEN}"
      fi
    fi
    curl -C - -L -f --retry 3 --progress-bar "$URL" -o "${COMFY_DIR}/models/checkpoints/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors"
  else
    echo "[OK] Found ${COMFY_DIR}/models/checkpoints/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors"
  fi

echo ""
echo "===================================================================="
echo "[SUCCESS] All recipe models and workflow have been synced!"
echo "Open ComfyUI, press 'Load' and select 'civitai-juggernaut-korean-candid-lookbook.json' to run."
echo "===================================================================="
