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

command -v databuilder >/dev/null 2>&1 || { echo "ERROR: databuilder CLI not found."; exit 1; }

CATALOG="${CATALOG:-catalog_op}"
SCHEMA="${SCHEMA:-default}"
OP_NAME="${OP_NAME:-triple_op}"
VER_NAME="${VER_NAME:-v5}"
WORK_DIR="${WORK_DIR:-/tmp/operator_cli_test}"
mkdir -p "${WORK_DIR}"

if [[ ! -f "${WORK_DIR}/create_version.json" ]]; then
  if [[ ! -f "${WORK_DIR}/storage_location.txt" ]]; then
    echo "ERROR: missing ${WORK_DIR}/create_version.json"
    echo "Run 04_operator_file_upload.sh first."
    exit 1
  fi
  STORAGE_LOCATION="$(cat "${WORK_DIR}/storage_location.txt")"
  cat > "${WORK_DIR}/create_version.json" <<JSON
{
  "versionName": "${VER_NAME}",
  "comment": "first version created by sdk test",
  "language": "Python",
  "category": "TRANSFORM",
  "storageLocation": "${STORAGE_LOCATION}",
  "properties": {"className": "TripleOp"},
  "input": [],
  "output": [],
  "execParams": [],
  "defaultParams": [],
  "engineType": ["RAY"],
  "resourceType": "CPU"
}
JSON
fi

set +e
output="$(databuilder operator-version create \
  --catalog-name "${CATALOG}" \
  --schema-name "${SCHEMA}" \
  --operator-name "${OP_NAME}" \
  --use-official-image \
  --body-file "${WORK_DIR}/create_version.json" 2>&1)"
status=$?
set -e
printf "%s\n" "${output}"

if [[ ${status} -ne 0 ]]; then
  if [[ "${output}" == *'"code":"AlreadyExists"'* || "${output}" == *"AlreadyExists"* ]]; then
    echo "[info] operator version already exists, continue."
  else
    exit "${status}"
  fi
fi
