# ═══════════════════════════════════════════════
# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001
# 📜 Copyright: 国作登字-2026-A-00037559
# ═══════════════════════════════════════════════
name: 铸渊 · 广播分发

on:
  push:
    branches: [main]
    paths:
      - 'broadcasts-outbox/**'
  workflow_dispatch:

jobs:
  distribute:
    name: 📡 分发广播到开发者目录
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4
        with:
          ref: main

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Distribute broadcasts
        run: node scripts/distribute-broadcasts.js

      - name: Commit distribution
        run: |
          git config user.name "铸渊 (ZhùYuān)"
          git config user.email "zhuyuan@guanghulab.com"
          git add .
          git diff --cached --quiet || git commit -m "📡 铸渊广播分发 · $(date +%Y-%m-%d)"
          git push

      # ━━━ 🧬 双端神经系统·自报告 ━━━
      - name: "🧬 写入神经自报告"
        if: always()
        run: |
          WORKFLOW_ID="broadcast"
          BRAIN="SY-03"
          REPORT_DIR="data/neural-reports/broadcast"
          TIMESTAMP=$(TZ=Asia/Shanghai date +%Y-%m-%d-%H%M)
          STATUS="${{ job.status }}"

          mkdir -p "$REPORT_DIR"

          cat > "${REPORT_DIR}/${WORKFLOW_ID}-${TIMESTAMP}.json" << EOF
          {
            "workflow_id": "${WORKFLOW_ID}",
            "run_id": "${{ github.run_id }}",
            "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
            "status": "${STATUS}",
            "brain": "${BRAIN}",
            "event": "${{ github.event_name }}",
            "branch": "${{ github.ref_name }}",
            "commit": "${{ github.sha }}"
          }
          EOF

          git config user.name "zhuyuan-bot"
          git config user.email "zhuyuan@guanghulab.com"
          git add "$REPORT_DIR/"
          git diff --cached --quiet || \
            git commit -m "🧬 ${WORKFLOW_ID} 自报告 · ${TIMESTAMP} [skip ci]"
          git push || echo "⚠️ 自报告push失败（不阻断主流程）"
      # ━━━ 📡 指令回执·自动同步 ━━━
      - name: "📡 同步回执到 Notion"
        if: always()
        env:
          NOTION_API_KEY: ${{ secrets.NOTION_API_KEY }}
          RECEIPT_DB_ID: ${{ secrets.RECEIPT_DB_ID }}
        run: |
          node scripts/neural/write-receipt-to-notion.js \
            --instruction-id "${{ github.event.inputs.instruction_id || 'AUTO' }}" \
            --status "${{ job.status }}" \
            --workflow "broadcast" \
            --summary "broadcast 自动执行" \
            --related-agent "SY-03"

