#!/bin/bash
#
# ComfyUI Startup Script
# Starts ComfyUI server on port 8188
#

WORKSPACE_DIR="${WORKSPACE_DIR:-/workspace}"
COMFYUI_DIR="${WORKSPACE_DIR}/ComfyUI"
HF_CACHE="${WORKSPACE_DIR}/huggingface_cache"

# Set environment variables
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
export HF_HOME="${HF_CACHE}"
export TQDM_DISABLE=1

# Navigate to ComfyUI directory
cd "${COMFYUI_DIR}" || exit 1

# Determine which Python to use
if [ -f "venv/bin/python" ]; then
  PYTHON_BIN="venv/bin/python"
  echo "Using ComfyUI virtual environment Python..."
else
  PYTHON_BIN="python3"
  echo "WARNING: venv not found, using system Python"
fi

echo "Starting ComfyUI on port 8188..."
echo "Access at: http://localhost:8188"
echo "Using HuggingFace cache: ${HF_CACHE}"
echo "Python: ${PYTHON_BIN}"

# Start ComfyUI with GPU support
exec "${PYTHON_BIN}" main.py \
  --listen 0.0.0.0 \
  --port 8188 \
  --enable-cors-header \
  --preview-method auto

echo "ComfyUI stopped"
