#!/bin/bash
# Validate all configured routes
#
# Usage: ./validate-all-routes.sh

set -e

BASE_URL="${BASE_URL:-http://localhost:3030}"

echo "🧭 Validating all configured routes..."
echo "🌐 Base URL: $BASE_URL"

# Check if server is running
if ! curl -f -s "$BASE_URL/health" > /dev/null 2>&1; then
    echo "❌ Server not running at $BASE_URL"
    echo "💡 Start server with: just dev::with-nav-test"
    exit 1
fi

# Validate all routes
echo "🔍 Running route validation..."
response=$(curl -s "$BASE_URL/api/nav-test/validate-all")

if [ $? -eq 0 ]; then
    echo "✅ Route validation completed"

    # Parse and display summary
    if command -v jq &> /dev/null; then
        echo "📊 Validation Summary:"
        total=$(echo "$response" | jq -r '.total_routes')
        valid=$(echo "$response" | jq -r '.valid_routes')
        invalid=$(echo "$response" | jq -r '.invalid_routes')
        time=$(echo "$response" | jq -r '.validation_time_ms')

        echo "  Total Routes: $total"
        echo "  Valid Routes: $valid"
        echo "  Invalid Routes: $invalid"
        echo "  Validation Time: ${time}ms"

        # Show invalid routes if any
        if [ "$invalid" -gt 0 ]; then
            echo ""
            echo "❌ Invalid Routes:"
            echo "$response" | jq -r '.details[] | select(.valid == false) | "  - " + .path + " (" + .language + "): " + (.error // "Unknown error")'
            exit 1
        fi

        # Show valid routes summary
        if [ "$valid" -gt 0 ]; then
            echo ""
            echo "✅ Valid Routes:"
            echo "$response" | jq -r '.details[] | select(.valid == true) | "  - " + .path + " → " + (.component // "None") + " (" + .language + ")"'
        fi

        # Calculate success rate
        if [ "$total" -gt 0 ]; then
            success_rate=$((valid * 100 / total))
            echo ""
            echo "🎯 Success Rate: ${success_rate}%"

            if [ "$success_rate" -eq 100 ]; then
                echo "🎉 All routes are valid!"
            elif [ "$success_rate" -ge 90 ]; then
                echo "✅ Most routes are valid"
            else
                echo "⚠️  Many routes need attention"
            fi
        fi
    else
        echo "📊 Raw Response:"
        echo "$response"
        echo ""
        echo "💡 Install jq for better output formatting: brew install jq"

        # Simple validation check without jq
        if echo "$response" | grep -q '"invalid_routes":0'; then
            echo "✅ All routes appear valid"
        else
            echo "⚠️  Some routes may be invalid"
            exit 1
        fi
    fi
else
    echo "❌ Route validation failed"
    exit 1
fi

echo ""
echo "🎉 Route validation completed successfully"
