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

SHUFFLE_BASE_URL="${SHUFFLE_BASE_URL:-http://localhost:5001}"
SHUFFLE_API_KEY="${SHUFFLE_API_KEY:-}"
WORKFLOW_ID="${1:-0b2c5b48-0e02-49a3-8e12-2bc892ac15f9}"
TEMPLATE_FILE="${2:-shuffle-workflows/sample-webhook-soc-integrator-iris-workflow.json}"

if [[ -z "${SHUFFLE_API_KEY}" ]]; then
  echo "error: SHUFFLE_API_KEY is required"
  echo "example: SHUFFLE_API_KEY=xxxx scripts/update-shuffle-workflow-from-template.sh"
  exit 1
fi

if [[ ! -f "${TEMPLATE_FILE}" ]]; then
  echo "error: template file not found: ${TEMPLATE_FILE}"
  exit 1
fi

tmp_payload="$(mktemp)"
trap 'rm -f "${tmp_payload}"' EXIT

python3 - "${TEMPLATE_FILE}" "${WORKFLOW_ID}" > "${tmp_payload}" <<'PY'
import json
import sys

template_file = sys.argv[1]
workflow_id = sys.argv[2]

with open(template_file, "r", encoding="utf-8") as fh:
    wf = json.load(fh)

wf["id"] = workflow_id

for field in ("created", "edited", "last_runtime", "owner", "updated_by"):
    wf.pop(field, None)

print(json.dumps(wf))
PY

curl -sS -o /tmp/shuffle_workflow_update_resp.json -w "%{http_code}" \
  -X PUT "${SHUFFLE_BASE_URL}/api/v1/workflows/${WORKFLOW_ID}" \
  -H "Authorization: Bearer ${SHUFFLE_API_KEY}" \
  -H "Content-Type: application/json" \
  --data-binary "@${tmp_payload}" >/tmp/shuffle_workflow_update_status.txt

http_status="$(cat /tmp/shuffle_workflow_update_status.txt)"
response="$(cat /tmp/shuffle_workflow_update_resp.json)"

if [[ "${http_status}" != "200" ]]; then
  echo "error: workflow update failed (HTTP ${http_status})"
  echo "${response}"
  exit 1
fi

WORKFLOW_UPDATE_RESPONSE="${response}" python3 - <<'PY'
import json
import os
import sys

raw = os.environ.get("WORKFLOW_UPDATE_RESPONSE", "")
try:
    data = json.loads(raw)
except Exception:
    print("updated, but response is not valid JSON:")
    print(raw[:600])
    sys.exit(0)

if isinstance(data, dict) and data.get("success") is False:
    print("error: API returned success=false")
    print(raw)
    sys.exit(1)

workflow_id = data.get("id") if isinstance(data, dict) else None
name = data.get("name") if isinstance(data, dict) else None
print(f"updated: {name or '<unknown>'} id={workflow_id or '<unknown>'}")
PY
