#!/usr/bin/env bash
# Generate TypeScript types from the Rust schema, via `trace explain`.
#
# Why: the Rust types in crates/trace-core have `JsonSchema` derives. The CLI
# command `trace explain <type> --output jsonschema` prints the schema for
# `trace`, `reply`, or `state`. We pipe each into json-schema-to-typescript
# to produce frontend-consumable .d.ts modules. This keeps the frontend types
# in lockstep with the Rust source of truth — schema drift becomes a CI
# failure rather than a silent runtime bug.
#
# Triggered as `prebuild` in package.json so it runs on every production
# build. Idempotent: re-running produces identical output if the schema
# hasn't changed.

set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
FE_ROOT="$(cd "$HERE/.." && pwd)"
REPO_ROOT="$(cd "$FE_ROOT/.." && pwd)"
OUT_DIR="$FE_ROOT/src/generated"

# shellcheck disable=SC1091
source "$REPO_ROOT/scripts/_find_flowtrace_bin.sh"

mkdir -p "$OUT_DIR"

# Generate per root. Each output is a self-contained .ts module exporting the
# top-level type plus all reachable sub-types.
generate() {
  local root="$1"
  local out_name="$2"
  local banner="// DO NOT EDIT — generated by frontend/scripts/sync-types.sh from \`trace explain $root --output jsonschema\`.\n// Edit the Rust types in crates/trace-core and rerun \`npm run sync-types\` (or \`npm run build\`) to refresh.\n"
  local schema_tmp
  schema_tmp="$(mktemp)"
  echo "  $root → src/generated/$out_name"
  "$BIN" explain "$root" --output jsonschema > "$schema_tmp"
  printf '%b' "$banner" > "$OUT_DIR/$out_name"
  # Pipe via a tempfile — bash variable expansion through `echo "$var" |` was
  # losing the definitions section in some shells, leaving $ref pointers to
  # resolve against an empty schema.
  npx --silent json-schema-to-typescript \
      --no-additionalProperties \
      --bannerComment "" \
      < "$schema_tmp" \
      >> "$OUT_DIR/$out_name"
  rm -f "$schema_tmp"
}

echo "sync-types: generating TS from Rust schema..."
generate "trace"     "trace.ts"      &
generate "reply"      "reply.ts"       &
generate "state"      "state.ts"       &
generate "run_detail" "run_detail.ts"  &
wait
echo "sync-types: done"
