#!/usr/bin/env bash
# auto_accept_when_ready.sh - guard: when phone frida attaches WeChat, auto run 3-item acceptance
# Polls hook/probe; on supports_hook=true runs run_three_acceptance.sh and archives evidence.
# Usage: bash sdk/scripts/auto_accept_when_ready.sh [device_id] [max_wait_sec]
set -o pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
DEVICE="${1:-xgfe65eimrrofyws}"
MAX_WAIT="${2:-7200}"
BASE="${SDK_BASE_URL:-http://127.0.0.1:8899}"
INTERVAL=10
LOG="$ROOT/sdk/logs/auto_accept_${DEVICE}.log"
mkdir -p "$(dirname "$LOG")"

echo "[auto-accept] start $(date) device=$DEVICE max=${MAX_WAIT}s" | tee -a "$LOG"
deadline=$(( $(date +%s) + MAX_WAIT ))

while [ "$(date +%s)" -lt "$deadline" ]; do
  # 就绪信号：diag_wcdb RPC 可用（= 新 wechat_hook_v2.js 已重载，含 WCDB 2.x 适配）
  DIAG="$(curl -s --max-time 30 -X POST "$BASE/api/v3/hook/execute" -H 'Content-Type: application/json' \
    -d "{\"device_id\":\"$DEVICE\",\"platform\":\"wechat\",\"action\":\"diag_wcdb\",\"params\":{},\"hook_only\":true}" 2>/dev/null)"
  SUP="$(printf '%s' "$DIAG" | python3 -c 'import sys,json
try:
    d=json.load(sys.stdin); inner=d.get("data",d)
    # 最新 JS 标志：diag_wcdb 含 main_query 实读测试字段
    print("True" if (inner.get("success") and "main_query" in inner) else "ERR")
except Exception:
    print("ERR")' 2>/dev/null)"
  SUP="${SUP:-ERR}"
  if [ "$SUP" = "True" ]; then
    echo "[auto-accept] $(date) diag_wcdb ok (new JS loaded) -> run 3-item acceptance" | tee -a "$LOG"
    echo "[auto-accept] WCDB diag: $DIAG" >> "$LOG"
    bash "$ROOT/sdk/scripts/run_three_acceptance.sh" "$DEVICE" 2>&1 | tee -a "$LOG"
    RC="${PIPESTATUS[0]:-0}"
    echo "[auto-accept] acceptance exit=$RC $(date)" | tee -a "$LOG"
    exit "$RC"
  fi
  echo "[auto-accept] $(date '+%H:%M:%S') 新JS未就绪(diag_wcdb=$SUP)，等手机重启Agent，retry ${INTERVAL}s" >> "$LOG"
  sleep "$INTERVAL"
done

echo "[auto-accept] timeout, frida not ready $(date)" | tee -a "$LOG"
exit 1
