name: Update Benchmarks in Repo

on:
  # Só corre quando tu mandas (botão "Run workflow")
  workflow_dispatch:

permissions:
  # Dá permissão ao bot para escrever no repositório (fazer git push)
  contents: write

env:
  CARGO_TERM_COLOR: always
  SYMBOLICA_LICENSE: ${{ secrets.SYMBOLICA_LICENSE }}

jobs:
  benchmark-and-commit:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v4
        with:
          # É preciso fazer checkout com o token para poder fazer push depois
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Rust Cache
        uses: swatinem/rust-cache@v2

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.x'

      # Corre os benchmarks e escreve para ficheiro de texto simples (raw)
      - name: Run Benchmarks
        run: |
          echo "Running benchmarks..."
          
          # Header simples
          echo "SymbAnaFis Benchmarks" > benches/bench_output.txt
          echo "Date: $(date)" >> benches/bench_output.txt
          echo "Commit: ${{ github.sha }}" >> benches/bench_output.txt
          echo "----------------------------------------" >> benches/bench_output.txt
          
          # Captura o output real para o ficheiro
          cargo bench --all-features >> benches/bench_output.txt 2>&1
          
          echo "Benchmarks finished."

      # Formata o output para markdown
      - name: Format Benchmark Results
        run: |
          echo "Formatting benchmark results..."
          python3 scripts/format_benchmarks.py < benches/bench_output.txt > benches/CI_Bench_Results.md
          echo "Formatting complete."

      # Verifica se houve mudanças e faz commit
      - name: Commit and Push Results
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "chore: update benchmark results [skip ci]"
          file_pattern: "benches/bench_output.txt benches/CI_Bench_Results.md"
          branch: ${{ github.ref }}
