name: Post-Merge Version Bump

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      skip_version_bump:
        description: 'Skip version bump'
        required: false
        type: boolean
        default: false

permissions:
  contents: write
  pull-requests: write

jobs:
  check-trigger:
    name: Check if Version Bump Needed
    runs-on: ubuntu-latest
    outputs:
      should_bump: ${{ steps.check.outputs.should_bump }}
      bump_type: ${{ steps.check.outputs.bump_type }}
    
    steps:
      - name: Checkout code
        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 2
      
      - name: Check if this was a version bump PR
        id: check_pr_labels
        uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
        with:
          script: |
            // Get the commit that triggered this workflow
            const commit = context.sha;
            
            // Find PRs that were merged with this commit
            const { data: prs } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
              owner: context.repo.owner,
              repo: context.repo.repo,
              commit_sha: commit
            });
            
            // Check if any of these PRs had the version-bump or automated label
            const hasVersionBumpLabel = prs.some(pr => 
              pr.labels.some(label => 
                label.name === 'version-bump' || 
                label.name === 'automated'
              )
            );
            
            core.setOutput('skip_version_bump', hasVersionBumpLabel);
            
            if (hasVersionBumpLabel) {
              console.log('This PR had version-bump or automated label - skipping to prevent loop');
            }
      
      - name: Determine if sync needed
        id: check
        run: |
          # Skip if the merged PR was a version bump PR
          if [ "${{ steps.check_pr_labels.outputs.skip_version_bump }}" = "true" ]; then
            echo "should_bump=false" >> $GITHUB_OUTPUT
            echo "Version bump PR detected - skipping to prevent loops"
            exit 0
          fi
          
          # Check commit title (first line only) for skip patterns
          COMMIT_TITLE=$(git log -1 --pretty=%s)
          
          # Skip if this is an automated version bump commit to prevent loops
          # Only check the title, not the full body to avoid false positives
          if echo "$COMMIT_TITLE" | grep -qE "^chore: bump version to v"; then
            echo "should_bump=false" >> $GITHUB_OUTPUT
            echo "Automated version bump commit detected - skipping to prevent loops"
            exit 0
          fi
          
          # Get full commit message for version bump type detection
          COMMIT_MSG=$(git log -1 --pretty=%B)
          
          # Determine version bump type from commit message
          if echo "$COMMIT_MSG" | grep -qiE "^(feat|feature)\(.*\)!:|^BREAKING CHANGE:|^[a-z]+!:"; then
            echo "bump_type=major" >> $GITHUB_OUTPUT
          elif echo "$COMMIT_MSG" | grep -qiE "^(feat|feature)(\(.*\))?:"; then
            echo "bump_type=minor" >> $GITHUB_OUTPUT
          elif echo "$COMMIT_MSG" | grep -qiE "^(fix|bugfix)(\(.*\))?:"; then
            echo "bump_type=patch" >> $GITHUB_OUTPUT
          else
            echo "bump_type=patch" >> $GITHUB_OUTPUT
          fi
          
          echo "should_bump=true" >> $GITHUB_OUTPUT
          echo "Will create version bump PR"

  create-version-bump-pr:
    name: Create Version Bump PR
    runs-on: ubuntu-latest
    needs: check-trigger
    if: |
      needs.check-trigger.outputs.should_bump == 'true' &&
      github.event.inputs.skip_version_bump != 'true'
    
    steps:
      - name: Checkout code
        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 0
      
      - name: Setup Node.js
        uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
        with:
          node-version: '20'
      
      - name: Configure Git
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
      
      - name: Create version bump branch
        id: create_branch
        run: |
          BRANCH_NAME="chore/version-bump-$(date +%Y%m%d-%H%M%S)"
          echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT
          git checkout -b "$BRANCH_NAME"
      
      - name: Bump version
        id: bump_version
        run: |
          BUMP_TYPE="${{ needs.check-trigger.outputs.bump_type }}"
          
          # Get current version
          CURRENT_VERSION=$(cat VERSION)
          echo "Current version: $CURRENT_VERSION"
          
          # Bump version
          npm run version:bump:$BUMP_TYPE
          
          # Get new version
          NEW_VERSION=$(cat VERSION)
          echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
          echo "New version: $NEW_VERSION"
      
      - name: Update CHANGELOG
        run: |
          NEW_VERSION="${{ steps.bump_version.outputs.new_version }}"
          DATE=$(date +%Y-%m-%d)
          COMMIT_TITLE=$(git log -1 --pretty=%s)
          
          # Create changelog entry
          printf "## [%s] - %s\n\n### Changes\n- %s\n\n" "$NEW_VERSION" "$DATE" "$COMMIT_TITLE" > /tmp/changelog_entry.md
          
          # Prepend to CHANGELOG.md (after the header)
          if [ -f CHANGELOG.md ]; then
            awk '/^## \[/ && !found {print; system("cat /tmp/changelog_entry.md"); found=1; next} 1' CHANGELOG.md > /tmp/changelog_new.md
            mv /tmp/changelog_new.md CHANGELOG.md
          fi
      
      - name: Commit version bump
        run: |
          NEW_VERSION="${{ steps.bump_version.outputs.new_version }}"
          
          git add VERSION package.json CHANGELOG.md
          git commit -m "chore: bump version to v$NEW_VERSION"
      
      - name: Push branch
        run: |
          BRANCH_NAME="${{ steps.create_branch.outputs.branch_name }}"
          git push -u origin "$BRANCH_NAME"
      
      - name: Create Pull Request
        id: create_pr
        run: |
          NEW_VERSION="${{ steps.bump_version.outputs.new_version }}"
          BUMP_TYPE="${{ needs.check-trigger.outputs.bump_type }}"
          BRANCH_NAME="${{ steps.create_branch.outputs.branch_name }}"
          
          # Create PR body
          cat > /tmp/pr_body.md << 'EOFPR'
          ## 🤖 Automated Version Bump
          
          ### Version Update
          - **New Version:** v$NEW_VERSION
          - **Bump Type:** $BUMP_TYPE
          
          ### Changes Included
          - ✅ VERSION file updated
          - ✅ package.json version updated  
          - ✅ CHANGELOG.md updated with latest changes
          
          ### Next Steps
          1. Review the version bump is correct
          2. Merge this PR to apply the version bump
          
          ---
          
          **Note:** This PR was created automatically by the post-merge workflow.
          
          **Documentation updates:** If registry or component changes require documentation updates, the separate "Sync Documentation" workflow will handle that automatically when `registry.json` or `.opencode/` files are modified.
          EOFPR
          
          # Replace variables
          sed -i "s/\$NEW_VERSION/$NEW_VERSION/g" /tmp/pr_body.md
          sed -i "s/\$BUMP_TYPE/$BUMP_TYPE/g" /tmp/pr_body.md
          
          # Create PR
          gh pr create \
            --title "chore: bump version to v$NEW_VERSION" \
            --body-file /tmp/pr_body.md \
            --base main \
            --head "$BRANCH_NAME" \
            --label "automated,version-bump"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
