name: Benchmarks

on:
  pull_request:
    paths:
      - '**/*.go'
      - 'go.mod'
      - 'go.sum'
  push:
    branches: [main]
    paths:
      - '**/*.go'
      - 'go.mod'
      - 'go.sum'
  workflow_dispatch:

env:
  GO_VERSION: "1.24"

jobs:
  benchmarks:
    name: Run Benchmarks
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: ${{ env.GO_VERSION }}

    - name: Download dependencies
      run: go mod download

    - name: Run benchmarks
      run: |
        go test -bench=. -benchmem -count=3 ./... | tee benchmark_results.txt

    - name: Upload benchmark results
      uses: actions/upload-artifact@v4
      with:
        name: benchmark-results
        path: benchmark_results.txt
        retention-days: 30

    - name: Comment benchmark results on PR
      if: github.event_name == 'pull_request'
      uses: actions/github-script@v7
      with:
        script: |
          const fs = require('fs');

          let comment = '## 📊 Benchmark Results\n\n';

          try {
            if (fs.existsSync('benchmark_results.txt')) {
              const benchmarks = fs.readFileSync('benchmark_results.txt', 'utf8');
              const lines = benchmarks.split('\n').filter(line =>
                line.includes('Benchmark') || line.includes('ns/op') || line.includes('ok')
              );

              if (lines.length > 0) {
                comment += '```\n';
                comment += lines.slice(0, 20).join('\n');
                if (lines.length > 20) {
                  comment += `\n... and ${lines.length - 20} more lines\n`;
                }
                comment += '\n```\n';
              } else {
                comment += 'No benchmark results found.\n';
              }
            }
          } catch (error) {
            comment += `⚠️ Could not read benchmark results: ${error.message}\n`;
          }

          github.rest.issues.createComment({
            issue_number: context.issue.number,
            owner: context.repo.owner,
            repo: context.repo.repo,
            body: comment
          });
