#!/usr/bin/env bash
# Downloads the OpenAPI spec from a running backend and regenerates Rust DTOs.
#
# Usage:
#   scripts/update-api-spec.sh [backend-url]
#
# Default backend URL: http://localhost:8083
#
# Mirrors the TypeScript SDK's scripts/update-api-spec.js. The fetched spec is
# written to api-spec/openapi.json; `cargo codegen` then regenerates
# src/api_spec/generated.rs via the xtask crate.

set -euo pipefail

BACKEND_URL="${1:-http://localhost:8083}"
SPEC_URL="${BACKEND_URL%/}/api-docs/openapi.json"

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SPEC_PATH="$REPO_ROOT/api-spec/openapi.json"

mkdir -p "$REPO_ROOT/api-spec"

echo "Fetching OpenAPI spec from $SPEC_URL..."
if ! curl --fail --silent --show-error --output "$SPEC_PATH" "$SPEC_URL"; then
    echo "Failed to fetch OpenAPI spec from $SPEC_URL" >&2
    exit 1
fi

SIZE_KB=$(($(wc -c < "$SPEC_PATH") / 1024))
echo "Saved OpenAPI spec to $SPEC_PATH (${SIZE_KB} KB)"

echo "Generating Rust types..."
cd "$REPO_ROOT"
cargo codegen
echo "Type generation complete."
