name: 'Lint Reporter'
description: 'Reports linting results as a PR comment'
inputs:
  title:
    description: 'Title for the lint report section'
    required: true
  lint-result:
    description: 'Linting result (success or failure)'
    required: true
  lint-output:
    description: 'Linting output to include in the report'
    required: true
  github-token:
    description: 'GitHub token for posting comments'
    required: true

runs:
  using: 'composite'
  steps:
    - name: Check permissions
      if: github.event_name == 'pull_request'
      id: check-permissions
      shell: bash
      run: |
        # Check if this is from a fork (external contributor)
        if [[ "${{ github.event.pull_request.head.repo.full_name }}" != "${{ github.repository }}" ]]; then
          echo "is_fork=true" >> $GITHUB_OUTPUT
          echo "ℹ️ PR from fork detected - comment posting may fail due to permissions"
        else
          echo "is_fork=false" >> $GITHUB_OUTPUT
        fi

    - name: Find Comment
      if: github.event_name == 'pull_request'
      uses: peter-evans/find-comment@v3
      id: fc
      continue-on-error: true
      with:
        issue-number: ${{ github.event.pull_request.number }}
        comment-author: 'github-actions[bot]'
        body-includes: '<!-- lint-results -->'
    
    - name: Prepare Comment Body
      if: github.event_name == 'pull_request'
      id: prepare
      continue-on-error: true
      uses: actions/github-script@v7
      with:
        github-token: ${{ inputs.github-token }}
        script: |
          const title = ${{ toJSON(inputs.title) }};
          const result = ${{ toJSON(inputs.lint-result) }};
          const output = ${{ toJSON(inputs.lint-output) }};
          const existingCommentId = '${{ steps.fc.outputs.comment-id }}';
          
          const icon = result === 'success' ? '✅' : '❌';
          const status = result === 'success' ? 'Passed' : 'Failed';
          
          // Create section content
          let sectionContent = `### ${title} ${icon} **Status**: ${status}\n`;
          
          // Special formatting for coverage reports
          if (title.includes('Coverage')) {
            if (result === 'success' || (output && output.includes('%'))) {
              // Show coverage metrics directly (not in details)
              sectionContent += `\n${output}\n`;
            } else if (output && output !== 'No output') {
              sectionContent += `\n<details>\n<summary>Click to see details</summary>\n\n\`\`\`\n${output}\n\`\`\`\n\n</details>\n`;
            }
          } else {
            // Regular lint output
            if (result !== 'success' && output && output !== 'No output') {
              sectionContent += `\n<details>\n<summary>Click to see details</summary>\n\n\`\`\`\n${output}\n\`\`\`\n\n</details>\n`;
            }
          }
          
          let body;
          if (existingCommentId) {
            // Get existing comment body
            const { data: comment } = await github.rest.issues.getComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: parseInt(existingCommentId),
            });
            
            const existingBody = comment.body;
            const sectionHeader = `### ${title}`;
            const nextSectionRegex = /^###\s/m;
            
            if (existingBody.includes(sectionHeader)) {
              // Replace existing section
              const lines = existingBody.split('\n');
              let inSection = false;
              let newLines = [];
              
              for (let i = 0; i < lines.length; i++) {
                if (lines[i] === sectionHeader) {
                  inSection = true;
                  // Add the new section content
                  newLines.push(...sectionContent.trim().split('\n'));
                  continue;
                }
                
                if (inSection && lines[i].match(nextSectionRegex)) {
                  inSection = false;
                }
                
                if (!inSection) {
                  newLines.push(lines[i]);
                }
              }
              
              body = newLines.join('\n');
            } else {
              // Add new section at the end
              body = existingBody + '\n\n' + sectionContent;
            }
          } else {
            // Create new comment
            body = `## 🔍 Code Quality Report\n<!-- lint-results -->\n\nThis comment is automatically updated with linting results from CI.\n\n${sectionContent}`;
          }
          
          // Store the body for the next step
          core.setOutput('comment_body', body);
    
    - name: Create or Update Comment
      if: github.event_name == 'pull_request'
      uses: peter-evans/create-or-update-comment@v4
      continue-on-error: true
      with:
        comment-id: ${{ steps.fc.outputs.comment-id }}
        issue-number: ${{ github.event.pull_request.number }}
        body: ${{ steps.prepare.outputs.comment_body }}
        edit-mode: replace
    
    - name: Log comment status
      if: github.event_name == 'pull_request' && steps.check-permissions.outputs.is_fork == 'true'
      shell: bash
      run: |
        echo "ℹ️ Comment posting may have failed due to fork permissions - this is expected and OK"