# ═══════════════════════════════════════════════
# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001
# 📜 Copyright: 国作登字-2026-A-00037559
# ═══════════════════════════════════════════════
name: 铸渊 · 每日自检

on:
  schedule:
    - cron: '0 0 * * *'  # UTC 00:00 = 北京时间 08:00
  workflow_dispatch:      # 也支持手动触发

jobs:
  # ── AGE OS v1.0: 核心大脑唤醒（所有流程的前提）──
  wake-brain:
    name: 🌅 唤醒核心大脑
    runs-on: ubuntu-latest
    permissions:
      contents: read
    outputs:
      brain_awake: ${{ steps.wake.outputs.brain_awake }}

    steps:
      - uses: actions/checkout@v4

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

      - name: 🧠 唤醒铸渊核心大脑
        id: wake
        env:
          LLM_API_KEY: ${{ secrets.ZY_LLM_API_KEY }}
          LLM_BASE_URL: ${{ secrets.ZY_LLM_BASE_URL }}
          ANTHROPIC_API_KEY: ${{ secrets.ZY_LLM_API_KEY }}
          OPENAI_API_KEY: ${{ secrets.ZY_LLM_API_KEY }}
          DASHSCOPE_API_KEY: ${{ secrets.ZY_LLM_API_KEY }}
          DEEPSEEK_API_KEY: ${{ secrets.ZY_LLM_API_KEY }}
        run: |
          node core/brain-wake --task "每日自检" || {
            echo "⚠️ 核心大脑唤醒失败，使用 dry-run 模式继续"
            echo "brain_awake=dry-run" >> "$GITHUB_OUTPUT"
          }
          echo "🌊 加载光湖存在级安全协议..."
          if [ -f ".github/persona-brain/security-protocol.json" ]; then
            PROTOCOL_LEVEL=$(cat .github/persona-brain/security-protocol.json | python3 -c "import sys,json; print(json.load(sys.stdin)['level'])")
            echo "✅ 安全协议已加载 · 等级: ${PROTOCOL_LEVEL}"
          else
            echo "❌ 安全协议缺失！创建工单！"
          fi

  selfcheck:
    name: 🔍 铸渊自检
    needs: wake-brain
    runs-on: ubuntu-latest
    permissions:
      contents: write
      issues: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4

      # 🌊 进入光湖
      - name: 🌊 进入光湖
        uses: ./.github/actions/guanghu-shell
        with:
          agent_id: 'AG-ZY-058'
          action: 'enter'

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

      - name: Run self-check
        id: check
        run: node scripts/selfcheck.js

      - name: 设置自检日期
        run: echo "CHECK_DATE=$(TZ='Asia/Shanghai' date '+%Y-%m-%d')" >> $GITHUB_ENV

      - name: DC-01 Notion Usage Snapshot
        env:
          NOTION_TOKEN: ${{ secrets.ZY_NOTION_TOKEN }}
        run: node scripts/dc-notion-usage.js

      - name: DC-02 Workflow Performance Snapshot
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: node scripts/dc-workflow-perf.js

      - name: Commit self-check result
        run: |
          git config user.name "zhuyuan-bot"
          git config user.email "zhuyuan@guanghulab.com"
          git add .github/persona-brain/memory.json data/dc-reports/ .github/brain/shell-status.json .github/brain/shell-errors.json
          if ! git diff --cached --quiet; then
            git commit -m "🔍 铸渊每日自检 · ${{ env.CHECK_DATE }} [skip ci]"
            for i in 1 2 3; do
              if git push; then
                echo "✅ 自检结果已推送"
                break
              fi
              echo "⚠️ 推送失败（第 $i 次），拉取后重试..."
              git pull --rebase origin main
              if [ $i -eq 3 ]; then
                echo "⚠️ 推送失败 3 次，跳过"
              fi
            done
          else
            echo "📌 无变化，跳过提交"
          fi

      # 🌊 离开光湖（成功时）
      - name: 🌊 离开光湖
        if: success()
        uses: ./.github/actions/guanghu-shell
        with:
          agent_id: 'AG-ZY-058'
          action: 'exit'
          detail: 'daily selfcheck completed'

      # 🌊 异常上报（失败时）
      - name: 🌊 异常上报
        if: failure()
        uses: ./.github/actions/guanghu-shell
        with:
          agent_id: 'AG-ZY-058'
          action: 'error'
          detail: 'daily selfcheck workflow failed'

      # ━━━ 🧬 双端神经系统·自报告 ━━━
      - name: "🧬 写入神经自报告"
        if: always()
        run: |
          WORKFLOW_ID="brain-check"
          BRAIN="AG-TY-01"
          REPORT_DIR="data/neural-reports/brain-check"
          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.ZY_NOTION_TOKEN }}
          RECEIPT_DB_ID: ${{ secrets.ZY_NOTION_RECEIPT_DB }}
        run: |
          node scripts/neural/write-receipt-to-notion.js \
            --instruction-id "${{ github.event.inputs.instruction_id || 'AUTO' }}" \
            --status "${{ job.status }}" \
            --workflow "brain-check" \
            --summary "brain-check 自动执行" \
            --related-agent "AG-TY-01"

