name: Integration Tests (Manual Trigger)

on:
  issue_comment:
    types: [created]

jobs:
  integration-tests:
    # Only run on PR comments, not issue comments
    # Only run when the comment contains the trigger phrase
    # Only allow andreisavu to trigger
    if: |
      github.event.issue.pull_request &&
      contains(github.event.comment.body, '/run-integration-tests') &&
      github.event.comment.user.login == 'andreisavu'
    runs-on: ubuntu-latest
    steps:
      - name: Add reaction to comment
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.reactions.createForIssueComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: context.payload.comment.id,
              content: 'rocket'
            });

      - name: Get PR branch
        id: pr
        uses: actions/github-script@v7
        with:
          script: |
            const pr = await github.rest.pulls.get({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            });
            core.setOutput('ref', pr.data.head.ref);
            core.setOutput('sha', pr.data.head.sha);

      - uses: actions/checkout@v5
        with:
          ref: ${{ steps.pr.outputs.ref }}

      - name: Install uv
        uses: astral-sh/setup-uv@v7
        with:
          enable-cache: true

      - name: Set up Python
        run: uv python install 3.14

      - name: Install dependencies
        run: uv sync --all-extras

      - name: Run integration tests
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: make integration-tests

      - name: Report success
        if: success()
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: `✅ Integration tests passed on commit ${context.payload.issue.pull_request ? '${{ steps.pr.outputs.sha }}' : 'N/A'}`
            });

      - name: Report failure
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: `❌ Integration tests failed on commit ${{ steps.pr.outputs.sha }}. See [workflow run](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}) for details.`
            });
