#!/usr/bin/env bash
# Validates that FE endpoint keys map to real BE routes.
# Diffs: gb4.7mfe Gb5ApiEndpoints URLs vs docs/api-snapshot.json paths
#
# Usage:
#   bash tools/validate-contract.sh           # report only
#   bash tools/validate-contract.sh --fix     # (future: auto-correct mismatches)
#
# Exit code: 0 if no drift, 1 if mismatches found.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
FE_ROOT="${GB5_FE_ROOT:-$HOME/gb/gb4.7mfe}"
SNAPSHOT="$REPO_ROOT/docs/api-snapshot.json"
FE_ENDPOINTS_DIR="$FE_ROOT/projects/gbhost/public/api/gb5api"

# ── Guard: swagger snapshot must exist ────────────────────────────────────────
if [[ ! -f "$SNAPSHOT" ]]; then
  echo "api-snapshot.json not found. Run:"
  echo "  curl -s \"\$GB5_API_BASE/swagger/v1/swagger.json\" > docs/api-snapshot.json"
  exit 0
fi

# ── Guard: FE endpoints dir must exist ────────────────────────────────────────
if [[ ! -d "$FE_ENDPOINTS_DIR" ]]; then
  echo "FE endpoints dir not found: $FE_ENDPOINTS_DIR"
  echo "Set GB5_FE_ROOT in ~/.gb5-mcp.env"
  exit 0
fi

# ── Extract BE paths from swagger snapshot ────────────────────────────────────
BE_PATHS=$(python3 -c "
import json, sys
spec = json.load(open('$SNAPSHOT'))
for path in sorted(spec.get('paths', {}).keys()):
    print(path)
")

# ── Extract FE URL values from Gb5ApiEndpoints files ─────────────────────────
# Matches patterns like: 'some.key': '/module/Entity/GetEntity'
FE_URLS=$(grep -rh "': '/" "$FE_ENDPOINTS_DIR"/ 2>/dev/null \
  | grep -oE "'(/[^']+)'" \
  | tr -d "'" \
  | sort -u)

# ── Compare ────────────────────────────────────────────────────────────────────
FE_MISSING=()
BE_MISSING=()

while IFS= read -r fe_url; do
  [[ -z "$fe_url" ]] && continue
  # Strip module prefix (e.g. /as/, /mms/, /fws/) for matching against BE paths
  # BE paths in swagger don't include the YARP prefix
  stripped=$(echo "$fe_url" | sed 's|^/[a-z][a-z0-9]*/||')
  # Check if the stripped path matches any BE path
  if ! echo "$BE_PATHS" | grep -qF "/$stripped"; then
    FE_MISSING+=("$fe_url  →  /$stripped  (not in swagger)")
  fi
done <<< "$FE_URLS"

while IFS= read -r be_path; do
  [[ -z "$be_path" ]] && continue
  # Strip leading slash for comparison
  path_no_slash="${be_path#/}"
  if ! echo "$FE_URLS" | grep -qF "$path_no_slash"; then
    BE_MISSING+=("$be_path  (not in FE Gb5ApiEndpoints)")
  fi
done <<< "$BE_PATHS"

# ── Report ─────────────────────────────────────────────────────────────────────
drift=0

if [[ ${#FE_MISSING[@]} -gt 0 ]]; then
  echo ""
  echo "FE KEYS → MISSING FROM BE SWAGGER (${#FE_MISSING[@]}):"
  for item in "${FE_MISSING[@]}"; do
    echo "  MISSING: $item"
  done
  drift=1
fi

if [[ ${#BE_MISSING[@]} -gt 0 ]]; then
  echo ""
  echo "BE ROUTES → MISSING FROM FE Gb5ApiEndpoints (${#BE_MISSING[@]}):"
  for item in "${BE_MISSING[@]}"; do
    echo "  MISSING: $item"
  done
  drift=1
fi

if [[ $drift -eq 0 ]]; then
  echo "Contract OK — all FE endpoint keys map to known BE routes"
fi

exit $drift
