name: GitHub Issue → Beads Sync

on:
  issues:
    types: [opened, closed]

# CRITICAL: Serialize all beads writes to prevent mapping file corruption
concurrency:
  group: beads-sync
  cancel-in-progress: false

permissions:
  contents: write   # push .beads/ and mapping file
  issues: write     # post/edit bot comments

jobs:
  sync:
    runs-on: ubuntu-latest
    # Skip if triggered by the bot itself (loop prevention)
    if: github.actor != 'github-actions[bot]'
    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
        with:
          # Need full history for push
          fetch-depth: 0
          # PAT bypasses branch protection for pushing .beads/ changes
          token: ${{ secrets.BEADS_SYNC_TOKEN }}

      - name: Setup Bun
        uses: oven-sh/setup-bun@4bc047ad259df6fc24a6c9b0f9a0cb08cf17fbe5 # v2

      - name: Install Beads CLI (pinned to v1.0.0)
        run: |
          BD_VERSION="1.0.0"
          BD_URL="https://github.com/steveyegge/beads/releases/download/v${BD_VERSION}/beads_${BD_VERSION}_linux_amd64.tar.gz"
          mkdir -p "$HOME/.local/bin"
          curl -fsSL "$BD_URL" | tar -xz -C "$HOME/.local/bin" bd
          chmod +x "$HOME/.local/bin/bd"
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"
      - name: Verify and initialize Beads
        env:
          BEADS_DIR: ${{ github.workspace }}/.beads
        run: |
          bd --version
          # Initialize the current Dolt-backed layout on fresh checkout
          bd init 2>/dev/null || true

      - name: Run sync
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_EVENT_PATH: ${{ github.event_path }}
          GITHUB_REPOSITORY: ${{ github.repository }}
          SYNC_ACTION: ${{ github.event.action }}
          BEADS_SYNC_CONFIG: scripts/github-beads-sync.config.json
          BEADS_DIR: ${{ github.workspace }}/.beads
        run: |
          node scripts/github-beads-sync/index.mjs "$SYNC_ACTION"

      - name: Export backup snapshot
        env:
          BEADS_DIR: ${{ github.workspace }}/.beads
        run: |
          bd backup --force
          mkdir -p .github/beads-snapshots
          cp .beads/backup/issues.jsonl .github/beads-snapshots/issues.jsonl

      - name: Commit and push changes
        env:
          ISSUE_NUM: ${{ github.event.issue.number }}
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          # Stage beads state, mapping changes, and the tracked issue snapshot
          git add .beads/ .github/beads-mapping.json .github/beads-snapshots/issues.jsonl || true

          # Only commit if there are changes
          if git diff --cached --quiet; then
            echo "No changes to commit"
          else
            git commit -m "chore(beads): sync from GitHub issue #${ISSUE_NUM}"

            # Push with retry (handles concurrent runs)
            push_success=false
            for i in 1 2 3; do
              if git push; then
                echo "Push succeeded on attempt $i"
                push_success=true
                break
              fi
              echo "Push failed, attempt $i/3 — pulling with rebase..."
              git rebase --abort 2>/dev/null || true
              git pull --rebase
            done
            if [ "$push_success" = false ]; then
              echo "::error::All 3 push attempts failed"
              exit 1
            fi
          fi
