name: Codeflash AiService

on:
  pull_request:
    paths:
      - "django/aiservice/**"
  workflow_dispatch:

permissions:
  contents: read
  pull-requests: read
  checks: read

defaults:
  run:
    working-directory: django/aiservice

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  # This job checks if the workflow should run based on file changes
  check-changes:
    runs-on: ubuntu-latest
    outputs:
      should-run: ${{ steps.filter.outputs.aiservice }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: dorny/paths-filter@v3
        id: filter
        with:
          filters: |
            aiservice:
              - 'django/aiservice/**'

  # This job always runs and succeeds, allowing PRs to be merged when paths don't match
  no-aiservice-changes:
    name: No aiservice changes detected
    needs: check-changes
    if: needs.check-changes.outputs.should-run != 'true'
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: .
    steps:
      - name: Skip optimization
        run: echo "Skipping codeflash optimization - no changes in django/aiservice/"

  optimize:
    needs: [check-changes]
    if: needs.check-changes.outputs.should-run == 'true' && github.actor != 'codeflash-ai[bot]'
    name: Optimize new code in this PR
    runs-on: ubuntu-latest
    env:
      CODEFLASH_API_KEY: ${{ secrets.CODEFLASH_API_KEY }}
      CODEFLASH_PR_NUMBER: ${{ github.event.number }}
      DATABASE_URL: ${{ secrets.DATABASE_URL }}
      DJANGO_SETTINGS_MODULE: aiservice.settings

      COLUMNS: 110

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up Python
        uses: astral-sh/setup-uv@v7
        with:
          python-version: "3.12"

      - name: Install Project Dependencies
        run: |
          uv sync --refresh --isolated --active

      - name: Install Codeflash in separate venv
        working-directory: .
        run: |
          uv venv .codeflash-venv
          source .codeflash-venv/bin/activate
          uv pip install pytest-asyncio black
          uv pip install git+https://github.com/codeflash-ai/codeflash@main

      - name: Run Codeflash to optimize code
        id: optimize_code
        working-directory: .
        run: |
          source .codeflash-venv/bin/activate
          cd django/aiservice
          codeflash --async --verbose
