# Install in the claimed public repository at .github/workflows/mcpchannel-issues.yml
# on its default branch. Enable Issues and Actions; no PAT or secrets are needed.
# Approve a report on MCPChannel, then run this workflow from Actions or wait
# for the hourly schedule. Guide: https://www.mcpchannel.ai/guides/github-issue-sync
name: Publish approved MCPChannel reports
on:
  workflow_dispatch:
  schedule:
    - cron: '17 * * * *'
permissions:
  id-token: write
  issues: write
concurrency:
  group: mcpchannel-issue-publication
  cancel-in-progress: false
jobs:
  sync:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    env:
      GH_TOKEN: ${{ github.token }}
    steps:
      - name: Publish reviewed issues
        shell: bash
        run: |
          set -euo pipefail
          endpoint=https://www.mcpchannel.ai/api/issue-sync
          sync_request() {
            # Request a fresh repository identity. Never send GH_TOKEN to MCPChannel.
            identity=$(curl --silent --show-error --fail --get \
              -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
              --data-urlencode "audience=$endpoint" "$ACTIONS_ID_TOKEN_REQUEST_URL" | jq -er .value)
            echo "::add-mask::$identity" >&2
            curl --silent --show-error --fail --max-time 25 -H "Authorization: Bearer $identity" \
              -H 'Content-Type: application/json' --data-binary "$1" "$endpoint"
          }
          reports=$(sync_request '{"action":"poll"}')
          while IFS= read -r report; do
            id=$(jq -er .id <<<"$report")
            marker="<!-- mcpchannel-report:$id -->"
            if [[ $(jq -r .state <<<"$report") == approved ]]; then
              claim=$(sync_request "$(jq -nc --arg id "$id" '{action:"reserve",id:$id}')")
              [[ $(jq -r .changed <<<"$claim") == true ]] || continue
              # Pass report text as JSON data, not commands or Actions expressions.
              number=$(jq -c --arg marker "$marker" '{title:.public_title,body:(.public_body+"\n\n"+$marker)}' <<<"$report" |
                gh api --method POST "repos/$GITHUB_REPOSITORY/issues" --input - --jq '.number')
            else
              # An earlier create may have succeeded before acknowledgement.
              # Never blindly create again after an ambiguous write.
              number=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues?state=all&per_page=100" |
                jq -sr --arg marker "$marker" '[.[][] | select(.pull_request == null and .user.login=="github-actions[bot]" and ((.body // "")|endswith($marker))) | .number] | first // empty')
              if [[ -z "$number" ]]; then
                echo "::warning::Could not confirm an issue for report $id. Inspect the earlier workflow run before retrying publication."
                continue
              fi
            fi
            sync_request "$(jq -nc --arg id "$id" --argjson n "$number" '{action:"ack",id:$id,number:$n}')" | jq -e '.changed == true' >/dev/null
          done < <(jq -c '.reports[]' <<<"$reports")
