#!/bin/bash
# Syncs the scope API client from Enterprise to OSS.
#
# This script:
# 1. Regenerates the Enterprise API client from the OpenAPI spec
# 2. Copies the generated endpoints.gen.ts to OSS
#
# Prerequisites:
# - The OpenAPI spec must exist at data/openapi/scope.grafana.app-v0alpha1.json
#   (generated by running TestIntegrationOpenAPIs in pkg/extensions/apiserver/tests/)
#
# Usage: ./sync-from-enterprise.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GRAFANA_ROOT="$(cd "$SCRIPT_DIR/../../../../.." && pwd)"

# Source and destination directories for the generated API client
ENTERPRISE_SCOPE_API_DIR="$GRAFANA_ROOT/public/app/extensions/api/clients/scope/v0alpha1"
OSS_SCOPE_API_DIR="$SCRIPT_DIR"

cd "$GRAFANA_ROOT"

# Check if OpenAPI spec exists
if [ ! -f "data/openapi/scope.grafana.app-v0alpha1.json" ]; then
  echo "Error: OpenAPI spec not found at data/openapi/scope.grafana.app-v0alpha1.json"
  echo "Run TestIntegrationOpenAPIs in pkg/extensions/apiserver/tests/ to generate it."
  exit 1
fi

echo "Step 1: Generating Enterprise API client from OpenAPI spec..."
yarn workspace @grafana/api-clients process-specs && npx rtk-query-codegen-openapi ./local/generate-enterprise-apis.ts

if [ ! -f "$ENTERPRISE_SCOPE_API_DIR/endpoints.gen.ts" ]; then
  echo "Error: Enterprise endpoints.gen.ts not found after generation"
  exit 1
fi

echo "Step 2: Copying endpoints.gen.ts from Enterprise to OSS..."
cp "$ENTERPRISE_SCOPE_API_DIR/endpoints.gen.ts" "$OSS_SCOPE_API_DIR/endpoints.gen.ts"

echo "Done! Scope API client synced from Enterprise."
