name: nightly-snapshot-check

# 独立 CI 任务：定时跑生产脱敏快照的 L1c 数据质量校验
# 不绑 L1-L4 任一环境，临时拉起 DB → 加载脱敏快照 → 跑校验 → 销毁
#
# 触发时机：
#   - 每日 02:00 UTC 自动跑（生产真实数据漂移监测）
#   - PR develop→staging 合并前手动触发（L3 准入条件）
#   - PR staging→production 合并前手动触发（L4 准入条件）
#
# ⚠️ 启用前置条件：
#   1. 脱敏快照定期生成（生产 → 脱敏 → 上传到对象存储）
#   2. scripts/ops/snapshot-loader.sh 已实现
#   3. Gitea secret SNAPSHOT_S3_URL / SNAPSHOT_DECRYPT_KEY 已添加

permissions:
  contents: read

on:
  # schedule:
  #   - cron: '0 2 * * *'  # 每天 UTC 02:00
  workflow_dispatch:

jobs:
  snapshot-data-quality:
    runs-on: uat-with-docker
    timeout-minutes: 60
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Load production sanitized snapshot to ephemeral DB
        env:
          SNAPSHOT_S3_URL: ${{ secrets.SNAPSHOT_S3_URL }}
          SNAPSHOT_DECRYPT_KEY: ${{ secrets.SNAPSHOT_DECRYPT_KEY }}
        run: |
          bash scripts/ops/snapshot-loader.sh load

      - name: Install dependencies
        run: |
          export NVM_DIR="$HOME/.nvm"
          [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
          (cd testing && npm install)
          (cd backend && npm install)

      - name: Run L1c data quality on snapshot
        run: |
          export NVM_DIR="$HOME/.nvm"
          [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
          cd testing
          # DATABASE_URL 由 snapshot-loader.sh 写到 $GITHUB_ENV，自动注入此 step
          # data-quality-check.ts 启动期会做 connectivity probe，连不上立即退出
          # （不像之前 docker exec 默认值会沉默假阳性）
          DATA_SOURCE=snapshot npm run test:data-quality

      - name: Cleanup ephemeral DB
        if: always()
        run: bash scripts/ops/snapshot-loader.sh cleanup

      - name: Notify Discord on failure
        if: failure()
        run: |
          # TODO: 发 Discord webhook，附带快照日期 + 失败项摘要
          echo "TODO: notify Discord about snapshot check failure"
