#!/usr/bin/env bash

set -euo pipefail

if [[ $# -lt 2 || $# -gt 3 ]]; then
  echo "usage: $0 <input-swagger-json> <output-swagger-json> [path-prefix]" >&2
  exit 1
fi

input_file="$1"
output_file="$2"
path_prefix="${3:-/api/v2025/cloud}"

if ! command -v jq >/dev/null 2>&1; then
  echo "error: jq is required to generate UI swagger" >&2
  exit 1
fi

if [[ ! -f "$input_file" ]]; then
  echo "error: input swagger file not found: $input_file" >&2
  exit 1
fi

tmp_file="$(mktemp)"

jq --arg prefix "$path_prefix" '
  .paths |= with_entries(
    .key |= (if startswith($prefix) then . else $prefix + . end)
  )
' "$input_file" > "$tmp_file"

mv "$tmp_file" "$output_file"
