name: Lint Command

on:
  issue_comment:
    types: [created]

  workflow_dispatch:
    inputs:
      pr_number:
        description: 'PR number to run lint on'
        required: true

permissions:
  contents: write
  pull-requests: write
  issues: write

jobs:
  lint-command:
    name: Handle /lint command
    runs-on: ubuntu-latest
    if: |
      (github.event_name == 'workflow_dispatch' && github.event.inputs.pr_number) ||
      (github.event_name == 'issue_comment' &&
      github.event.issue.pull_request &&
      contains(github.event.comment.body, '/lint') &&
      startsWith(github.event.comment.body, '/lint'))

    steps:
    - name: Add acknowledgment reaction
      if: github.event_name == 'issue_comment'
      uses: peter-evans/create-or-update-comment@v4
      with:
        comment-id: ${{ github.event.comment.id }}
        reactions: eyes

    - name: Check permissions
      if: github.event_name == 'issue_comment'
      uses: actions/github-script@v7
      with:
        script: |
          const { data: collaborator } = await github.rest.repos.getCollaboratorPermissionLevel({
            owner: context.repo.owner,
            repo: context.repo.repo,
            username: context.actor
          });

          if (!['admin', 'write'].includes(collaborator.permission)) {
            github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: '❌ You need write permissions to run lint commands.'
            });
            core.setFailed('Insufficient permissions');
          }

    - name: Get PR information
      id: pr
      uses: actions/github-script@v7
      with:
        script: |
          const pr_number = context.eventName === 'issue_comment'
            ? context.issue.number
            : ${{ github.event.inputs.pr_number || 'null' }};

          const { data: pr } = await github.rest.pulls.get({
            owner: context.repo.owner,
            repo: context.repo.repo,
            pull_number: pr_number
          });

          core.setOutput('branch', pr.head.ref);
          core.setOutput('repo', pr.head.repo.full_name);
          core.setOutput('sha', pr.head.sha);
          core.setOutput('number', pr_number);

    - name: Checkout PR branch
      uses: actions/checkout@v4
      with:
        ref: ${{ steps.pr.outputs.branch }}
        token: ${{ secrets.GITHUB_TOKEN }}
        fetch-depth: 0

    - name: Set up python 3.12
      id: setup-python
      uses: actions/setup-python@v5
      with:
        python-version: 3.12

    - name: Install uv
      run: |
          curl -LsSf https://astral.sh/uv/install.sh | sh
          echo "$HOME/.cargo/bin" >> $GITHUB_PATH

    - name: Install dependencies
      run: uv sync --extra dev --extra postgres --extra external-tools
      working-directory: .

#    - name: Run ruff check with fixes
#      run: uv run ruff check --fix .
#
#    - name: Run ruff format
#      run: uv run ruff format .

    - name: Run isort, black, autoflake
      run: uv run isort . --profile black && uv run black . && uv run autoflake --remove-all-unused-imports --remove-unused-variables --in-place --recursive --ignore-init-module-imports .
      working-directory: .


    - name: Check for changes
      id: changes
      run: |
        if [[ -n $(git status --porcelain) ]]; then
          echo "changes=true" >> $GITHUB_OUTPUT
        else
          echo "changes=false" >> $GITHUB_OUTPUT
        fi

    - name: Commit and push changes
      if: steps.changes.outputs.changes == 'true'
      run: |
        git config --global user.name "github-actions[bot]"
        git config --global user.email "github-actions[bot]@users.noreply.github.com"
        git add .
        git commit -m "style: lint / fmt

        Triggered by /lint command from @${{ github.actor }}"
        git push

    - name: Comment on success
      if: steps.changes.outputs.changes == 'true'
      uses: peter-evans/create-or-update-comment@v4
      with:
        issue-number: ${{ steps.pr.outputs.number }}
        body: |
          ✅ **Lint fixes applied successfully!**

          Ruff has automatically fixed linting issues and formatted the code.
          Changes have been committed to the PR branch.

    - name: Comment on no changes
      if: steps.changes.outputs.changes == 'false'
      uses: peter-evans/create-or-update-comment@v4
      with:
        issue-number: ${{ steps.pr.outputs.number }}
        body: |
          ✅ **No lint issues found!**

          The code is already properly formatted and passes all linting checks.

    - name: Comment on failure
      if: failure()
      uses: peter-evans/create-or-update-comment@v4
      with:
        issue-number: ${{ steps.pr.outputs.number }}
        body: |
          ❌ **Lint command failed!**

          There was an error while running the lint fixes. Please check the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details.
