name: Latency Benchmark
on:
  push:
    branches: [main]
    paths: ['products/01-llm-cost-router/src/proxy/**']

jobs:
  benchmark:
    runs-on: ubuntu-latest  # Gitea runner on NAS — consistent CPU
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - name: Run proxy latency benchmark
        run: cargo bench --bench proxy_latency 2>&1 | tee bench-output.txt
        working-directory: products/01-llm-cost-router

      - name: Assert P99 < 5ms
        run: |
          # Extract P99 from criterion output
          P99=$(grep -oP 'median\s+\K[\d.]+' bench-output.txt | head -1 || echo "0")
          echo "P99 latency: ${P99}ns"
          # 5ms = 5,000,000ns
          if [ "$(echo "$P99 > 5000000" | bc -l 2>/dev/null || echo 0)" = "1" ]; then
            echo "❌ P99 latency ${P99}ns exceeds 5ms budget"
            exit 1
          fi
          echo "✅ P99 within budget"
        working-directory: products/01-llm-cost-router
