#!/usr/bin/env bash
# runpod-ltx-install.sh  —  Fase 1: ComfyUI + custom nodes + túnel Cloudflare
# server-audit / Pod RunPod RTX 4090 (LTX-2.3 FFLF Seed Hunter)
#
# Se corre en la terminal de Jupyter Lab del Pod:
#   curl -s https://dl.ramsesvii.com/runpod-ltx-install.sh | bash
#
# Idempotente: se puede re-correr. Todo va a /workspace (Network Volume, persiste).
# ComfyUI y el túnel quedan corriendo en tmux (sobreviven si se cierra Jupyter).
set +e
COMFY="/workspace/ComfyUI"
LOG="/workspace/ltx-install.log"
exec > >(tee -a "$LOG") 2>&1
echo "############ FASE 1 — $(date -u) ############"

log(){ echo -e "\n\033[1;36m>> $*\033[0m"; }

# ----- 0) utilidades -----
log "0/5  Herramientas base"
export DEBIAN_FRONTEND=noninteractive
command -v cloudflared >/dev/null 2>&1 || {
  echo "  bajando cloudflared..."
  curl -fsSL https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 \
       -o /usr/local/bin/cloudflared && chmod +x /usr/local/bin/cloudflared
}
pip install -q --upgrade "huggingface_hub[hf_transfer]" 2>/dev/null
export HF_HUB_ENABLE_HF_TRANSFER=1

# ----- 1) ComfyUI -----
log "1/5  ComfyUI (a /workspace, persiste en el volume)"
if [ ! -d "$COMFY/.git" ]; then
  git clone --depth 1 https://github.com/comfyanonymous/ComfyUI "$COMFY"
else
  echo "  ya existe, git pull"; git -C "$COMFY" pull --ff-only
fi
echo "  instalando requirements de ComfyUI (no toco torch: ya es 2.8 cu128)..."
pip install -q -r "$COMFY/requirements.txt"

# ----- 2) ComfyUI-Manager (para Fase 2: detecta modelos/nodos faltantes) -----
log "2/5  ComfyUI-Manager"
MGR="$COMFY/custom_nodes/ComfyUI-Manager"
[ -d "$MGR/.git" ] || git clone --depth 1 https://github.com/ltdrdata/ComfyUI-Manager "$MGR"
[ -f "$MGR/requirements.txt" ] && pip install -q -r "$MGR/requirements.txt"

# ----- 3) Custom nodes del manual -----
log "3/5  Custom nodes (mxToolkit, LTXVideo, VideoHelperSuite, KJNodes, pysssss)"
clone_node(){ # url  nombre
  local url="$1" name="$2" d="$COMFY/custom_nodes/$2"
  if [ -d "$d/.git" ]; then git -C "$d" pull --ff-only >/dev/null 2>&1
  else echo "  clonando $name"; git clone --depth 1 "$url" "$d"; fi
  [ -f "$d/requirements.txt" ] && pip install -q -r "$d/requirements.txt"
}
clone_node https://github.com/Smirnov75/ComfyUI-mxToolkit          ComfyUI-mxToolkit
clone_node https://github.com/Lightricks/ComfyUI-LTXVideo          ComfyUI-LTXVideo
clone_node https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite ComfyUI-VideoHelperSuite
clone_node https://github.com/kijai/ComfyUI-KJNodes                ComfyUI-KJNodes
clone_node https://github.com/pythongosssss/ComfyUI-Custom-Scripts ComfyUI-Custom-Scripts

# ----- 4) Lanzar ComfyUI en tmux -----
log "4/5  Levantando ComfyUI en tmux (sesión 'comfy', puerto 8188)"
tmux kill-session -t comfy 2>/dev/null
tmux new-session -d -s comfy "cd $COMFY && python main.py --listen 0.0.0.0 --port 8188 2>&1 | tee /workspace/comfyui.log"
echo "  esperando a que ComfyUI levante..."
for i in $(seq 1 60); do
  curl -s -o /dev/null http://127.0.0.1:8188 && { echo "  ComfyUI ARRIBA"; break; }
  sleep 3
done

# ----- 5) Túnel Cloudflare -> 8188 -----
log "5/5  Túnel Cloudflare (URL pública temporal hacia ComfyUI)"
tmux kill-session -t cf 2>/dev/null
: > /workspace/cloudflared.log
tmux new-session -d -s cf "cloudflared tunnel --no-autoupdate --url http://localhost:8188 2>&1 | tee /workspace/cloudflared.log"
echo "  esperando URL del túnel..."
URL=""
for i in $(seq 1 30); do
  URL=$(grep -oE "https://[a-z0-9-]+\.trycloudflare\.com" /workspace/cloudflared.log | head -1)
  [ -n "$URL" ] && break
  sleep 2
done

echo
echo "=================================================================="
if [ -n "$URL" ]; then
  echo "  ✅ ComfyUI accesible en:   $URL"
else
  echo "  ⚠️  No salió la URL del túnel todavía. Mirá: cat /workspace/cloudflared.log"
fi
echo "  Logs:   ComfyUI -> /workspace/comfyui.log   |   install -> $LOG"
echo "  tmux:   'tmux attach -t comfy'  (ComfyUI)   |   'tmux attach -t cf' (túnel)"
echo "=================================================================="
echo ">> Copiá este bloque final y pegáselo a Claude (sobre todo la URL)."
