#!/usr/bin/env bash
# check-api-paths.sh - Frontend API paths vs Backend routes consistency check
#
# Usage: bash scripts/check-api-paths.sh
# Returns: 0=pass, 1=mismatch found

set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

FRONTEND_PATHS=$(mktemp)
BACKEND_ROUTES=$(mktemp)
KNOWN_PREFIXES=$(mktemp)
trap 'rm -f "$FRONTEND_PATHS" "$BACKEND_ROUTES" "$KNOWN_PREFIXES"' EXIT

echo "=========================================="
echo "  Frontend-Backend API Path Consistency"
echo "=========================================="

# --- Extract frontend API paths ---
# Single-quoted paths from api/ modules
grep -rohE "'\/[^']+'" apps/web/src/api/ --include="*.ts" | tr -d "'" > "$FRONTEND_PATHS"
# Template literal paths
grep -rohE '`/[^`]+`' apps/web/src/api/ --include="*.ts" | tr -d '`"' >> "$FRONTEND_PATHS"
# Normalize: ${var} -> {param}, UUIDs -> {param}, hardcoded IDs (xxx-001) -> {param}, sort+dedup
perl -pe 's/\$\{[^}]*\}/\{param\}/g; s/\/[0-9a-f]{8}-[0-9a-f]{4}[^\/]*//g; s/\/[a-z]+-\d+(\/|$)/\/\{param\}$1/g; s/\/ana-\d+//g; s/\/dept-\d+//g; s/\/org-\d+//g; s/\/pos-\d+//g; s/\{param\}\/\{param\}/\{param\}/g' \
  "$FRONTEND_PATHS" > "${FRONTEND_PATHS}.tmp"
sort -u "${FRONTEND_PATHS}.tmp" > "$FRONTEND_PATHS"
rm -f "${FRONTEND_PATHS}.tmp"

# --- Extract backend Axum routes ---
# From .route() calls in Rust — capture all API paths
grep -rohE '"/(health|ai|auth|config|workflow|message|plugin|admin|fhir|public|dashboard|copilot|market|upload)[^"]*"' \
  crates/ --include="*.rs" \
  | tr -d '"' \
  | sed 's/:[a-z_][a-z0-9_]*/\{param\}/g' \
  | sed 's/{[^}]*}/{param}/g' \
  | sort -u > "$BACKEND_ROUTES"
# Also capture base module routes (users, roles, etc.) from module.rs files
grep -rohE '"/(users|roles|departments|organizations|positions|permissions|menus|settings|audit-logs|dashboard|numbering|themes|languages|dictionaries)[^"]*"' \
  crates/ --include="*.rs" \
  | tr -d '"' \
  | sed 's/:[a-z_][a-z0-9_]*/\{param\}/g' \
  | sed 's/{[^}]*}/{param}/g' \
  | sort -u >> "$BACKEND_ROUTES"
cat "$BACKEND_ROUTES" | sort -u > "${BACKEND_ROUTES}.tmp" && mv "${BACKEND_ROUTES}.tmp" "$BACKEND_ROUTES"

# --- Known prefixes that have dynamic/different routing ---
# Plugin dynamic table routes: /plugins/crm/{table} - registered at runtime
cat > "$KNOWN_PREFIXES" <<'EOF'
/admin/plugins
/plugins/crm
/plugins/{param}
/market
/api/v1/public/brand
/api/v1
/dashboard
/new
/config/settings/
EOF

FE_COUNT=$(wc -l < "$FRONTEND_PATHS")
BE_COUNT=$(wc -l < "$BACKEND_ROUTES")
echo ""
echo "Stats: Frontend ${FE_COUNT} paths | Backend ${BE_COUNT} routes"
echo ""

ERRORS=0

# --- Check 1: Frontend paths that have no backend route ---
echo "--- Check 1: Frontend paths missing from backend ---"
while IFS= read -r fpath; do
  [ -z "$fpath" ] && continue

  # Skip known dynamic prefixes (plugin routes registered at runtime)
  skip=false
  while IFS= read -r prefix; do
    [ -z "$prefix" ] && continue
    case "$fpath" in
      "$prefix"*) skip=true; break ;;
    esac
  done < "$KNOWN_PREFIXES"
  [ "$skip" = true ] && continue

  # Remove trailing /{param} for loose matching
  clean_path="${fpath%/{param}}"
  found=false
  while IFS= read -r bpath; do
    [ -z "$bpath" ] && continue
    clean_bpath="${bpath%/{param}}"
    # Exact match or prefix match
    if [ "$fpath" = "$bpath" ] || [ "$clean_path" = "$clean_bpath" ]; then
      found=true
      break
    fi
    case "$fpath" in
      "$bpath"/*|"$clean_bpath"/*) found=true; break ;;
      "$bpath"|"$clean_bpath") found=true; break ;;
    esac
  done < "$BACKEND_ROUTES"

  if [ "$found" = false ]; then
    echo -e "  ${RED}MISSING${NC} Frontend '${fpath}' not found in backend routes"
    ERRORS=$((ERRORS + 1))
  fi
done < "$FRONTEND_PATHS"

if [ $ERRORS -eq 0 ]; then
  echo -e "  ${GREEN}OK${NC} All frontend paths have backend routes"
fi

echo ""

# --- Check 2: Backend route parameter format ---
echo "--- Check 2: Backend route param format ---"
bad_format=$(grep -E ':[a-z_]+[/"]' "$BACKEND_ROUTES" || true)
if [ -n "$bad_format" ]; then
  echo -e "  ${YELLOW}WARN${NC} Routes using old :param syntax:"
  echo "$bad_format" | while IFS= read -r line; do echo "    $line"; done
else
  echo -e "  ${GREEN}OK${NC} All routes use {param} syntax"
fi

echo ""
echo "=========================================="
if [ $ERRORS -gt 0 ]; then
  echo -e "  ${RED}FAIL${NC} ${ERRORS} mismatches"
  exit 1
else
  echo -e "  ${GREEN}PASS${NC} All paths consistent"
  exit 0
fi
