#!/bin/bash
# scripts/api-contract-validator.sh
# Validates API contract between frontend and backend
#
# Discovers:
# - Frontend API calls (from Next.js/React code)
# - Backend routes (from Laravel route files)
# - Mismatches (missing routes, orphaned routes, method conflicts)
#
# Exit codes:
#   0 = All contracts valid
#   1 = Contract violations found
#
# Usage: ./scripts/api-contract-validator.sh [frontend-path]

set -e

FRONTEND_PATH=${1:-"/Users/charlie/code/showprima-frontend-integration"}
BACKEND_PATH="."

echo "🔗 API Contract Validator"
echo "========================="
echo ""
echo "Frontend: $FRONTEND_PATH"
echo "Backend: $BACKEND_PATH"
echo ""

# Temporary files
FRONTEND_CALLS=$(mktemp)
BACKEND_ROUTES=$(mktemp)
REPORT=$(mktemp)

# Cleanup on exit
trap "rm -f $FRONTEND_CALLS $BACKEND_ROUTES $REPORT" EXIT

# ============================================================================
# Part 1: Extract Frontend API Calls
# ============================================================================

echo "🔍 Step 1/4: Scanning frontend for API calls..."

if [ ! -d "$FRONTEND_PATH" ]; then
    echo "⚠️  Frontend path not found: $FRONTEND_PATH"
    echo "   Skipping frontend analysis"
else
    # Search for API calls in TypeScript/JavaScript files
    # Patterns: fetch('/api/...'), axios.post('/api/...'), apiClient.get('/api/...')

    find "$FRONTEND_PATH" -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" \) \
        -not -path "*/node_modules/*" \
        -not -path "*/.next/*" \
        -not -path "*/dist/*" \
        -exec grep -oh "\(fetch\|axios\|apiClient\)[^)]*['\"][^'\"]*\/api\/[^'\"]*['\"]" {} \; 2>/dev/null | \
        sed -E "s/.*['\"]([^'\"]*\/api\/[^'\"]*)['\"].*/\1/" | \
        sort -u > "$FRONTEND_CALLS" || true

    FRONTEND_COUNT=$(wc -l < "$FRONTEND_CALLS" | tr -d ' ')
    echo "✓ Found $FRONTEND_COUNT API calls in frontend"
fi

# ============================================================================
# Part 2: Extract Backend Routes
# ============================================================================

echo ""
echo "🔍 Step 2/4: Scanning backend for route definitions..."

# Extract routes from Laravel route files
# Patterns: Route::get('/api/...'), Route::post('/api/...')

find routes/api -type f -name "*.php" \
    -exec grep -oh "Route::\(get\|post\|put\|patch\|delete\)(['\"][^'\"]*['\"]" {} \; 2>/dev/null | \
    sed -E "s/Route::(get|post|put|patch|delete)\(['\"]([^'\"]*)['\"].*/\U\1\E \2/" | \
    grep -E "/(api/|^[^/])" | \
    sed 's|^|/api/|' | \
    sed 's|/api//api/|/api/|' | \
    sort -u > "$BACKEND_ROUTES" || true

BACKEND_COUNT=$(wc -l < "$BACKEND_ROUTES" | tr -d ' ')
echo "✓ Found $BACKEND_COUNT routes in backend"

# ============================================================================
# Part 3: Match Contracts
# ============================================================================

echo ""
echo "🔍 Step 3/4: Matching frontend calls to backend routes..."
echo ""

MATCHED=0
MISSING=0
ORPHAN=0

{
    echo "# API Contract Validation Report"
    echo ""
    echo "## Summary"
    echo ""
    echo "| Metric | Count |"
    echo "|--------|-------|"
    echo "| Frontend API calls | $FRONTEND_COUNT |"
    echo "| Backend routes | $BACKEND_COUNT |"
    echo ""
} > "$REPORT"

# Check for missing backend routes
if [ $FRONTEND_COUNT -gt 0 ]; then
    echo "### Missing Backend Routes (Frontend calls but backend doesn't have)"
    echo ""
    echo "| Endpoint | Status |"
    echo "|----------|--------|"

    while IFS= read -r CALL; do
        # Normalize call (remove /api prefix if exists, add it back)
        NORMALIZED=$(echo "$CALL" | sed 's|^/api/||' | sed 's|^|/api/|')

        # Check if route exists (fuzzy match for path params)
        ENDPOINT_PATH=$(echo "$NORMALIZED" | sed 's|/[0-9]\+|/{id}|g' | sed 's|/[a-f0-9-]\{36\}|/{uuid}|g')

        if grep -q "$ENDPOINT_PATH" "$BACKEND_ROUTES" 2>/dev/null; then
            MATCHED=$((MATCHED + 1))
        else
            echo "| \`$NORMALIZED\` | ❌ MISSING |"
            MISSING=$((MISSING + 1))
        fi
    done < "$FRONTEND_CALLS"

    if [ $MISSING -eq 0 ]; then
        echo "| _No missing routes_ | ✅ |"
    fi

    echo ""
fi >> "$REPORT"

# Check for orphan backend routes (backend has but frontend never calls)
if [ $BACKEND_COUNT -gt 0 ]; then
    {
        echo "### Orphan Backend Routes (Backend has but frontend never calls)"
        echo ""
        echo "| Method | Route | Status |"
        echo "|--------|-------|--------|"
    } >> "$REPORT"

    while IFS= read -r ROUTE; do
        METHOD=$(echo "$ROUTE" | awk '{print $1}')
        PATH=$(echo "$ROUTE" | awk '{print $2}')

        # Normalize path for comparison
        NORMALIZED=$(echo "$PATH" | sed 's|{[^}]*}|*|g')

        # Check if frontend calls this (fuzzy match)
        if grep -qE "$(echo $NORMALIZED | sed 's/\*/[^\/]+/g')" "$FRONTEND_CALLS" 2>/dev/null; then
            MATCHED=$((MATCHED + 1))
        else
            # Skip admin routes (not called by public frontend)
            if [[ "$PATH" == */admin/* ]]; then
                continue
            fi
            echo "| $METHOD | \`$PATH\` | ⚠️ ORPHAN |" >> "$REPORT"
            ORPHAN=$((ORPHAN + 1))
        fi
    done < "$BACKEND_ROUTES"

    if [ $ORPHAN -eq 0 ]; then
        echo "| _No orphan routes_ | ✅ |" >> "$REPORT"
    fi

    echo "" >> "$REPORT"
fi

# ============================================================================
# Part 4: Generate Report
# ============================================================================

echo "🔍 Step 4/4: Generating report..."
echo ""

# Update summary
{
    echo "| Matched contracts | $MATCHED |"
    echo "| Missing backend routes | $MISSING |"
    echo "| Orphan backend routes | $ORPHAN |"
    echo ""
} | cat - "$REPORT" > "$REPORT.tmp" && mv "$REPORT.tmp" "$REPORT"

# Display report
cat "$REPORT"

# Save report to file
REPORT_FILE="docs/api-contract-validation-report.md"
mkdir -p "$(dirname $REPORT_FILE)"
cp "$REPORT" "$REPORT_FILE"

echo ""
echo "================================"
echo "Full report saved to: $REPORT_FILE"
echo ""

if [ $MISSING -gt 0 ]; then
    echo "❌ Contract validation FAILED"
    echo ""
    echo "⚠️  Found $MISSING frontend calls to non-existent backend routes"
    echo "   These will cause runtime errors!"
    echo ""
    echo "Fix by:"
    echo "  1. Adding missing routes to backend"
    echo "  2. Updating frontend to use correct endpoints"
    echo "  3. Removing dead frontend code"
    exit 1
else
    echo "✅ Contract validation PASSED"
    echo ""
    if [ $ORPHAN -gt 0 ]; then
        echo "⚠️  Found $ORPHAN orphan backend routes (not called by frontend)"
        echo "   Consider removing if unused"
    fi
    exit 0
fi
