name: Check for Merge Conflicts

on:
  pull_request:
    types: [opened, synchronize, reopened]
  # Also run when the base branch is updated
  push:
    branches:
      - main
      - master

jobs:
  check-conflicts:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
      contents: read
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - name: Fetch base branch
        run: |
          git fetch origin ${{ github.base_ref || github.event.repository.default_branch }}
      
      - name: Check for merge conflicts
        id: conflict-check
        run: |
          # Determine the base branch
          BASE_BRANCH="${{ github.base_ref }}"
          if [ -z "$BASE_BRANCH" ]; then
            BASE_BRANCH="${{ github.event.repository.default_branch }}"
          fi
          
          echo "Checking for conflicts with origin/$BASE_BRANCH"
          
          # Try to merge the base branch to see if there are conflicts
          if git merge-tree $(git merge-base HEAD origin/$BASE_BRANCH) origin/$BASE_BRANCH HEAD | grep -q "^<<<<<"; then
            echo "has_conflicts=true" >> $GITHUB_OUTPUT
            echo "✗ Merge conflicts detected!"
          else
            echo "has_conflicts=false" >> $GITHUB_OUTPUT
            echo "✓ No merge conflicts detected"
          fi
      
      - name: Comment on PR if conflicts exist
        if: steps.conflict-check.outputs.has_conflicts == 'true' && github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const comment = `## ⚠️ Merge Conflicts Detected
            
            @copilot This pull request has merge conflicts that need to be resolved.
            
            **Please resolve the conflicts by:**
            1. Merging the latest changes from the base branch
            2. Resolving any conflicting files
            3. Pushing the updated changes
            
            ---
            *This is an automated message from the merge conflict checker.*`;
            
            // Check if we already commented
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });
            
            const botComment = comments.find(comment => 
              comment.user.type === 'Bot' && 
              comment.body.includes('Merge Conflicts Detected')
            );
            
            if (botComment) {
              // Update existing comment
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: comment
              });
            } else {
              // Create new comment
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: comment
              });
            }
      
      - name: Add label if conflicts exist
        if: steps.conflict-check.outputs.has_conflicts == 'true' && github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            try {
              await github.rest.issues.addLabels({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                labels: ['merge-conflict']
              });
            } catch (error) {
              console.log('Label might not exist yet, skipping...');
            }
      
      - name: Remove label if no conflicts
        if: steps.conflict-check.outputs.has_conflicts == 'false' && github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            try {
              await github.rest.issues.removeLabel({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                name: 'merge-conflict'
              });
            } catch (error) {
              console.log('Label does not exist or is not applied, skipping...');
            }
      
      - name: Fail if conflicts exist
        if: steps.conflict-check.outputs.has_conflicts == 'true'
        run: |
          echo "❌ This PR has merge conflicts and cannot be merged."
          exit 1
