name: CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.9", "3.10", "3.11", "3.12"]

    steps:
    - uses: actions/checkout@v3

    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v4
      with:
        python-version: ${{ matrix.python-version }}

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -e ".[dev,langgraph,tui]"

    - name: Lint with Ruff
      run: |
        ruff check .

    - name: Type checking with mypy
      run: |
        mypy src/agent_vcr/

    - name: Test with pytest
      run: |
        pytest tests/ -v --cov=agent_vcr --cov-report=xml

    - name: Upload coverage reports to Codecov
      uses: codecov/codecov-action@v3
      with:
        token: ${{ secrets.CODECOV_TOKEN }}
        file: ./coverage.xml
        flags: unittests
        name: codecov-umbrella
        fail_ci_if_error: false

  benchmark:
    name: Performance Benchmarks
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write
      deployments: write
    # Only run on pushes to main (not on PRs) so gh-pages history stays clean
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    steps:
    - uses: actions/checkout@v3

    - name: Set up Python 3.11
      uses: actions/setup-python@v4
      with:
        python-version: "3.11"

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -e ".[dev]" pytest-benchmark

    - name: Run benchmarks
      run: |
        pytest tests/benchmarks/ -v --benchmark-only --no-cov \
          --benchmark-json=benchmark_results.json \
          --benchmark-name=short \
          --benchmark-columns="min,max,mean,stddev,rounds" \
          --tb=short

    - name: Store benchmark results
      uses: benchmark-action/github-action-benchmark@v1
      with:
        name: Agent VCR Benchmarks
        tool: pytest
        output-file-path: benchmark_results.json
        github-token: ${{ secrets.GITHUB_TOKEN }}
        auto-push: false
        save-data-file: true
        benchmark-data-dir-path: docs/dev/bench
        # Alert if performance regresses by more than 20%
        alert-threshold: "120%"
        comment-on-alert: true
        fail-on-alert: false
        alert-comment-cc-users: "@ruzvad"

    - name: Commit and push benchmark results
      run: |
        git config --global user.name 'github-actions[bot]'
        git config --global user.email '41898282+github-actions[bot]@users.noreply.github.com'
        git add docs/dev/bench/
        git diff --quiet && git diff --staged --quiet || (git commit -m "chore: update benchmarks [skip ci]" && git push)

