# ═══════════════════════════════════════════════
# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001
# 📜 Copyright: 国作登字-2026-A-00037559
# ═══════════════════════════════════════════════
name: 铸渊 · 光湖纪元 模块文档自动生成

on:
  push:
    branches: [main]
    paths:
      - 'm01-login/**'
      - 'm03-personality/**'
      - 'm05-user-center/**'
      - 'm06-ticket/**'
      - 'm07-dialogue-ui/**'
      - 'm10-cloud/**'
      - 'm11-module/**'
      - 'm12-kanban/**'
      - 'm15-cloud-drive/**'
      - 'm18-health-check/**'
      - 'dingtalk-bot/**'
      - 'backend-integration/**'
      - 'status-board/**'
      - 'backend/**'
      - 'frontend/**'
      - 'notification/**'
      - 'ticket-system/**'
      - 'scripts/generate-module-doc.js'
  workflow_dispatch:

jobs:
  generate-doc:
    name: 📋 生成部署模块总文档
    runs-on: ubuntu-latest
    permissions:
      contents: write

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

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

      - name: 生成光湖纪元模块文档
        run: node scripts/generate-module-doc.js

      - name: 提交更新文档
        run: |
          git config user.name "铸渊 (ZhùYuān)"
          git config user.email "zhuyuan@guanghulab.com"
          git add docs/HoloLake-Era-OS-Modules.md
          if git diff --cached --quiet; then
            echo "📋 文档无变化，跳过提交"
          else
            git commit -m "📋 自动更新光湖纪元模块文档 · $(date -u +%Y-%m-%d\ %H:%M\ UTC)"
            git pull --rebase origin main || echo "⚠️ rebase 失败（可能有冲突），尝试直接推送..."
            git push || {
              echo "⚠️ 推送失败，尝试重新拉取后再推送..."
              git pull --rebase origin main
              git push
            }
          fi

  check-and-notify:
    name: 🔍 模块自检 + 📧 通知推送者
    runs-on: ubuntu-latest
    # 仅 push 事件触发（workflow_dispatch 为手动，不发通知）
    if: github.event_name == 'push'
    permissions:
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 2

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

      - name: 获取本次 push 改动的文件列表
        id: changed
        run: |
          # 获取本次 push 相对于上一个 commit 改动的文件
          FILES=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git show --name-only --format="" HEAD)
          echo "files<<EOF" >> $GITHUB_OUTPUT
          echo "$FILES" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT
          echo "📄 改动文件：$FILES"

      - name: 🔍 模块自检
        id: check
        run: |
          CHANGED_FILES="${{ steps.changed.outputs.files }}"
          MODULES="m01-login m03-personality m05-user-center m06-ticket m07-dialogue-ui m10-cloud m11-module m12-kanban m15-cloud-drive m18-health-check dingtalk-bot backend-integration status-board backend frontend notification ticket-system"

          RESULT="pass"
          DETAILS=""

          for mod in $MODULES; do
            # 只检查本次有改动的模块
            if echo "$CHANGED_FILES" | grep -q "^${mod}/"; then
              echo "🔍 检查模块: $mod"

              if [ -d "$mod" ]; then
                if [ ! -f "$mod/README.md" ]; then
                  DETAILS="${DETAILS}❌ ${mod} 缺少 README.md（必须提供）"$'\n'
                  RESULT="fail"
                fi
                if [ ! -f "$mod/package.json" ]; then
                  DETAILS="${DETAILS}⚠️ ${mod} 缺少 package.json（建议补充）"$'\n'
                fi
                if [ ! -d "$mod/src" ]; then
                  DETAILS="${DETAILS}⚠️ ${mod} 缺少 src/ 目录（建议补充）"$'\n'
                fi

                # 检查 package.json 格式是否正确
                if [ -f "$mod/package.json" ]; then
                  if ! node -e "JSON.parse(require('fs').readFileSync('$mod/package.json','utf8'))" 2>/dev/null; then
                    DETAILS="${DETAILS}❌ ${mod}/package.json 格式错误（JSON 解析失败）"$'\n'
                    RESULT="fail"
                  else
                    DETAILS="${DETAILS}✅ ${mod} 结构检查通过"$'\n'
                  fi
                else
                  DETAILS="${DETAILS}✅ ${mod} 基本结构检查通过"$'\n'
                fi
              fi
            fi
          done

          if [ -z "$DETAILS" ]; then
            DETAILS="✅ 所有模块检查通过"
          fi

          echo "test_result=$RESULT" >> $GITHUB_OUTPUT
          # 使用 heredoc 方式输出多行详情
          echo "test_details<<EOF" >> $GITHUB_OUTPUT
          echo "$DETAILS" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT
          echo "🔍 自检结果: $RESULT"

      - name: 📧 发送模块收讫通知（Commit Comment → 推送者本人）
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_REPO: ${{ github.repository }}
          PUSHER_LOGIN: ${{ github.actor }}
          CHANGED_FILES: ${{ steps.changed.outputs.files }}
          COMMIT_SHA: ${{ github.sha }}
          COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
          TEST_RESULT: ${{ steps.check.outputs.test_result }}
          TEST_DETAILS: ${{ steps.check.outputs.test_details }}
        run: node scripts/notify-module-received.js

