#!/usr/bin/env bash
set -euo pipefail

PLUGIN_NAME="rivermoon-comfy-api-nodes"
ZIP_URL="https://video.rivermoon7.com/v1/comfy/downloads/rivermoon-comfy-api-nodes.zip"
COMFYUI_PATH="${COMFYUI_PATH:-${1:-}}"
DRY_RUN="${DRY_RUN:-0}"

log() {
  printf '[RiverMoon] %s\n' "$1"
}

run() {
  log "$1"
  shift
  if [ "$DRY_RUN" = "1" ]; then
    printf '  dry-run: %s\n' "$*"
    return 0
  fi
  "$@"
}

resolve_comfy_path() {
  if [ -n "$COMFYUI_PATH" ] && [ -d "$COMFYUI_PATH" ]; then
    cd "$COMFYUI_PATH" && pwd
    return
  fi

  for path in "$HOME/ComfyUI" "$HOME/comfyui" "$PWD/ComfyUI" "$PWD"; do
    if [ -d "$path/custom_nodes" ] && { [ -f "$path/main.py" ] || [ -d "$path/ComfyUI" ]; }; then
      cd "$path" && pwd
      return
    fi
  done

  printf 'ComfyUI path not found. Re-run with COMFYUI_PATH=/path/to/ComfyUI %s\n' "$0" >&2
  exit 1
}

COMFY_ROOT="$(resolve_comfy_path)"
CUSTOM_NODES="$COMFY_ROOT/custom_nodes"
PLUGIN_DIR="$CUSTOM_NODES/$PLUGIN_NAME"
TMP_DIR="${TMPDIR:-/tmp}/rivermoon-comfy-install"
ZIP_PATH="$TMP_DIR/$PLUGIN_NAME.zip"

log "ComfyUI: $COMFY_ROOT"
log "Plugin target: $PLUGIN_DIR"
log "Mode: $([ "$DRY_RUN" = "1" ] && echo dry-run || echo install)"
log "This installer does not download models, install GPU runtimes, or change system directory permissions."

run "Prepare temp directory" mkdir -p "$TMP_DIR"

if command -v curl >/dev/null 2>&1; then
  run "Download RiverMoon plugin zip" curl -fsSL "$ZIP_URL" -o "$ZIP_PATH"
elif command -v wget >/dev/null 2>&1; then
  run "Download RiverMoon plugin zip" wget -q "$ZIP_URL" -O "$ZIP_PATH"
else
  printf 'curl or wget is required.\n' >&2
  exit 1
fi

run "Replace plugin directory" rm -rf "$PLUGIN_DIR"
run "Create plugin directory" mkdir -p "$PLUGIN_DIR"
run "Extract plugin zip" unzip -q "$ZIP_PATH" -d "$PLUGIN_DIR"

PYTHON_BIN="${PYTHON_BIN:-python3}"
if [ -x "$COMFY_ROOT/venv/bin/python" ]; then
  PYTHON_BIN="$COMFY_ROOT/venv/bin/python"
fi

run "Install Python dependencies into the ComfyUI Python environment" "$PYTHON_BIN" -m pip install -r "$PLUGIN_DIR/requirements.txt"

log "Done. Restart ComfyUI and find nodes under RiverMoon/API, RiverMoon/Image, and RiverMoon/Video."
