name: lockfile-diff

# 拦元根因 2（依赖关系不可见演化）：PR 改动 package-lock.json 时
# diff transitive dep major bump，命中高风险 watchlist 的包在 PR comment 用 ⚠️ 高亮。
#
# 不阻断 PR（软规则 / 仅提醒），跟 PR 模板「依赖」checkbox 双层防御。
#
# 详见：
#   - 工单 #249【2】+【10】（合并实现）
#   - docs/standards/12-five-meta-rules.md 规则 2
#   - scripts/ops/lockfile-risk-watchlist.txt（高风险包名单）
#   - scripts/ops/lockfile-diff.py（diff 算法）

on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  diff:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout (need full history for base + head)
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Diff each changed lockfile
        id: diff
        run: |
          set -e
          BASE_SHA="${{ github.event.pull_request.base.sha }}"
          HEAD_SHA="${{ github.event.pull_request.head.sha }}"

          CHANGED_LOCKS=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" | grep -E '(^|/)package-lock\.json$' || true)
          if [ -z "$CHANGED_LOCKS" ]; then
            echo "no lockfile changes in this PR"
            exit 0
          fi

          OUTPUT_FILE=/tmp/lockfile-diff-comment.md
          : > "$OUTPUT_FILE"
          HAS_OUTPUT=0

          for lock in $CHANGED_LOCKS; do
            BASE_TMP=$(mktemp); HEAD_TMP=$(mktemp)
            if ! git show "$BASE_SHA:$lock" > "$BASE_TMP" 2>/dev/null; then echo "{}" > "$BASE_TMP"; fi
            if ! git show "$HEAD_SHA:$lock" > "$HEAD_TMP" 2>/dev/null; then echo "{}" > "$HEAD_TMP"; fi
            # stderr 留到 step 日志方便排查；stdout 才是 markdown SECTION
            SECTION=$(python3 scripts/ops/lockfile-diff.py "$BASE_TMP" "$HEAD_TMP" --label "$lock") || {
              echo "❌ lockfile-diff.py failed for $lock (stderr 见上)" >&2
              rm -f "$BASE_TMP" "$HEAD_TMP"
              continue
            }
            if [ -n "$SECTION" ]; then
              {
                echo "$SECTION"
                echo
              } >> "$OUTPUT_FILE"
              HAS_OUTPUT=1
            fi
            rm -f "$BASE_TMP" "$HEAD_TMP"
          done

          if [ "$HAS_OUTPUT" = "0" ]; then
            echo "no major bumps across changed lockfiles"
            exit 0
          fi

          echo "---" >> "$OUTPUT_FILE"
          echo "_由 lockfile-diff workflow 生成 · 工单 #249【2】+【10】_" >> "$OUTPUT_FILE"

          echo "comment_file=$OUTPUT_FILE" >> "$GITHUB_OUTPUT"

      - name: Post comment to PR
        if: steps.diff.outputs.comment_file
        env:
          GITEA_TOKEN: ${{ secrets.AI_REVIEW_GITEA_TOKEN }}
        run: |
          set -e
          if [ -z "$GITEA_TOKEN" ]; then
            echo "⚠️ AI_REVIEW_GITEA_TOKEN 未配置，跳过 PR comment（diff 结果在 step 日志）"
            cat "${{ steps.diff.outputs.comment_file }}"
            exit 0
          fi

          BODY=$(cat "${{ steps.diff.outputs.comment_file }}")
          API_BASE="${GITHUB_SERVER_URL:-http://43.130.59.228}"
          curl -fsS -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            "${API_BASE}/api/v1/repos/${GITHUB_REPOSITORY}/issues/${{ github.event.pull_request.number }}/comments" \
            -d "$(jq -nc --arg body "$BODY" '{body: $body}')" >/dev/null
          echo "✅ PR comment 已发"
