#!/usr/bin/env nu

# Benchmark route resolution performance
#
# Usage: nu benchmark-route.nu <path> [iterations]
# Example: nu benchmark-route.nu /services 1000

def main [route_path: string = "/", iterations: int = 1000] {
    let base_url = $env.BASE_URL? | default "http://localhost:3030"

    print $"🧭 Benchmarking route resolution: ($route_path)"
    print $"🔄 Iterations: ($iterations)"
    print $"🌐 Base URL: ($base_url)"

    # Check if server is running
    let health_check = try { http get $"($base_url)/health" } catch { null }
    if ($health_check | is-empty) {
        print "❌ Server not running at ($base_url)"
        print "💡 Start server with: just dev::with-nav-test"
        exit 1
    }

    # Run benchmark
    print "⏱️  Running benchmark..."
    let response = try {
        http get $"($base_url)/api/nav-test/benchmark?path=($route_path)&iterations=($iterations)"
    } catch { |e|
        print $"❌ Benchmark failed: ($e.msg)"
        exit 1
    }

    print "✅ Benchmark completed"

    # Display performance information
    print "📊 Performance Metrics:"
    print $"  Path: ($response.path)"
    print $"  Component: ($response.component | default 'None')"
    print $"  Language: ($response.language)"
    print $"  Iterations: ($response.iterations)"
    print $"  Total Time: ($response.total_time_ms)ms"
    print $"  Average Time: ($response.avg_time_ms)ms"
    print $"  Min Time: ($response.min_time_ms)ms"
    print $"  Max Time: ($response.max_time_ms)ms"

    # Calculate performance rating
    let avg_time = $response.avg_time_ms
    if $avg_time < 0.1 {
        print "🚀 Excellent performance (< 0.1ms avg)"
    } else if $avg_time < 1.0 {
        print "✅ Good performance (< 1ms avg)"
    } else if $avg_time < 10.0 {
        print "⚠️  Acceptable performance (< 10ms avg)"
    } else {
        print "🐌 Slow performance (> 10ms avg)"
    }

    # Show requests per second
    let total_time_s = $response.total_time_ms / 1000
    if $total_time_s > 0 {
        let rps = $response.iterations / $total_time_s | math round
        print $"⚡ Requests per second: ~($rps)"
    }

    print ""
    print "🎉 Benchmark completed successfully"
}
