#!/usr/bin/env bash
# 微信安全批量验收：仅对白名单测试联系人执行，默认 dry-run。
set -euo pipefail

DEVICE="${SDK_DEVICE_ID:-xgfe65eimrrofyws}"
BASE="${SDK_BASE_URL:-http://127.0.0.1:8899}"
TO_IDS_RAW="${WORKPHONE_TEST_TO_IDS:-}"
CONTENT="${WORKPHONE_TEST_CONTENT:-[工作手机白名单批量验收] $(date +%Y%m%d-%H%M%S)}"
INTERVAL="${WORKPHONE_BATCH_INTERVAL:-65}"
DRY_RUN="${WORKPHONE_DRY_RUN:-1}"
MAX_COUNT="${WORKPHONE_MAX_COUNT:-20}"

if [[ -z "${TO_IDS_RAW}" ]]; then
  echo "缺少 WORKPHONE_TEST_TO_IDS。示例："
  echo "  WORKPHONE_TEST_TO_IDS='filehelper,wxid_test_1' WORKPHONE_DRY_RUN=1 bash sdk/scripts/run_wechat_safe_batch_acceptance.sh"
  exit 2
fi

IFS=',' read -r -a TO_IDS <<< "${TO_IDS_RAW}"
if (( ${#TO_IDS[@]} > MAX_COUNT )); then
  echo "白名单数量 ${#TO_IDS[@]} 超过上限 ${MAX_COUNT}，拒绝执行。"
  exit 3
fi

TS="$(date +%Y%m%d-%H%M%S)"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
EVID_DIR="${ROOT}/开发文档/8、部署/05-测试验收/$(date +%Y%m%d)_微信安全批量验收"
mkdir -p "${EVID_DIR}"
REPORT="${EVID_DIR}/safe_batch_${TS}.jsonl"

probe="$(curl -sS --max-time 40 "${BASE}/api/v3/hook/probe/${DEVICE}")"
supports="$(echo "${probe}" | jq -r '.supports_hook // false' 2>/dev/null || echo false)"
if [[ "${supports}" != "true" ]]; then
  echo "Hook 未就绪，拒绝批量验收。"
  echo "${probe}" > "${EVID_DIR}/probe_${TS}.json"
  exit 4
fi

echo "设备=${DEVICE} count=${#TO_IDS[@]} interval=${INTERVAL}s dry_run=${DRY_RUN}"
for to_id in "${TO_IDS[@]}"; do
  to_id="$(echo "${to_id}" | xargs)"
  [[ -z "${to_id}" ]] && continue
  if [[ "${DRY_RUN}" == "1" ]]; then
    row="$(jq -cn \
      --arg to_id "$to_id" \
      --arg content "$CONTENT" \
      --argjson timestamp "$(date +%s)" \
      '{dry_run:true,to_id:$to_id,content:$content,timestamp:$timestamp}')"
    echo "$row" | tee -a "$REPORT"
    continue
  fi

  resp="$(curl -sS --max-time 120 -X POST "${BASE}/api/v3/message/send" \
    -H 'Content-Type: application/json' \
    -d "{\"device_id\":\"${DEVICE}\",\"platform\":\"wechat\",\"to_id\":\"${to_id}\",\"content\":\"${CONTENT}\",\"msg_type\":\"text\",\"channel\":\"hook\"}")"
  row="$(jq -cn \
    --arg to_id "$to_id" \
    --arg raw "$resp" \
    --argjson timestamp "$(date +%s)" \
    '{dry_run:false,to_id:$to_id,response:(try ($raw|fromjson) catch {raw:$raw}),timestamp:$timestamp}')"
  echo "$row" | tee -a "$REPORT"
  sleep "${INTERVAL}"
done

echo "报告: ${REPORT}"
