#!/usr/bin/env bash
# Type safety pipeline: generate TypeScript types from the OpenAPI spec.
# Run from the project root.
# Requires: openapi-typescript (npm), tsc, curl, jq

set -euo pipefail

BACKEND_URL="${BACKEND_URL:-http://localhost:8000}"
OPENAPI_PATH="/api/v1/openapi.json"
OUTPUT_FILE="frontend/src/types/api.generated.ts"

echo "Type Safety Pipeline"
echo "===================="

# 1. Wait for backend to be reachable (up to 15 seconds)
echo "[1/4] Checking backend availability at ${BACKEND_URL}..."
for i in $(seq 1 15); do
    if curl -sf "${BACKEND_URL}/health" > /dev/null 2>&1; then
        echo "  Backend is reachable."
        break
    fi
    if [ "$i" -eq 15 ]; then
        echo "  ERROR: Backend not reachable at ${BACKEND_URL} after 15 seconds."
        echo "  Start the backend first, or set BACKEND_URL to the correct address."
        exit 1
    fi
    sleep 1
done

# 2. Fetch the OpenAPI spec
echo "[2/4] Fetching OpenAPI spec..."
SPEC_FILE=$(mktemp /tmp/openapi-spec.XXXXXX.json)
curl -sf "${BACKEND_URL}${OPENAPI_PATH}" | jq '.' > "${SPEC_FILE}"
echo "  Saved spec to ${SPEC_FILE} ($(jq '.paths | keys | length' "${SPEC_FILE}") endpoints)."

# 3. Generate TypeScript types
echo "[3/4] Generating TypeScript types..."
mkdir -p "$(dirname "${OUTPUT_FILE}")"
npx openapi-typescript "${SPEC_FILE}" -o "${OUTPUT_FILE}"
echo "  Generated ${OUTPUT_FILE}."
rm -f "${SPEC_FILE}"

# Check for uncommitted type changes
if ! git diff --quiet -- "${OUTPUT_FILE}" 2>/dev/null; then
    echo "  WARNING: Generated types differ from committed version."
    echo "  Run 'git diff ${OUTPUT_FILE}' to inspect changes."
fi

# 4. Verify TypeScript compiles
echo "[4/4] Running TypeScript compiler check..."
cd frontend
npx tsc --noEmit
echo "  TypeScript compilation passed."

echo ""
echo "Pipeline complete. Types are up to date."
