name: Sync upstream obra/superpowers

on:
  schedule:
    - cron: '0 */6 * * *'
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      statuses: write

    steps:
      - name: Checkout fork
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Configure git
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Add upstream remote
        run: git remote add upstream https://github.com/obra/superpowers.git

      - name: Fetch upstream
        run: git fetch upstream main

      - name: Attempt merge
        id: merge
        run: |
          if git merge upstream/main --no-edit; then
            echo "MERGE_FAILED=false" >> $GITHUB_OUTPUT
          else
            echo "MERGE_FAILED=true" >> $GITHUB_OUTPUT
            git merge --abort
          fi

      - name: Push to fork
        if: steps.merge.outputs.MERGE_FAILED == 'false'
        run: git push origin main

      - name: Create commit status on conflict
        if: steps.merge.outputs.MERGE_FAILED == 'true'
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.repos.createCommitStatus({
              owner: context.repo.owner,
              repo: context.repo.repo,
              sha: context.sha,
              state: 'failure',
              description: 'Merge conflict with upstream obra/superpowers',
              context: 'Sync'
            });
