#!/usr/bin/env bash
# Type-C 红米 USB 一键解封：等 ADB → oneclick → 解封批量
# 用法：
#   bash sdk/scripts/wechat_unblock_typec_oneshot.sh
# 环境：
#   USB_VENDOR=0x2717      Xiaomi
#   WAIT_SEC=900           等待 ADB 上线最长 900 秒
#   UNBLOCK_REASON         传给批量脚本作为 reason
set -euo pipefail

SDK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WAIT_SEC="${WAIT_SEC:-900}"
REDMI_SERIAL="${REDMI_SERIAL:-xgfe65eimrrofyws}"
REASON="${UNBLOCK_REASON:-账号被误判限制登录，本人正常使用未做违规操作}"
LOG="${SDK_ROOT}/tmp/wechat_typec_oneshot_$(date +%Y%m%d_%H%M%S).log"
mkdir -p "${SDK_ROOT}/tmp"

exec > >(tee -a "$LOG") 2>&1
echo "=== 红米 Type-C USB 一键解封 ==="
echo "日志: $LOG"
echo ""

# 1. 提示
echo "【请在红米 Note 13 上操作（一次性）】"
echo "  1) 设置 → 我的设备 → 全部参数与信息 → 连点 7 次「OS 版本」/「MIUI 版本」"
echo "  2) 设置 → 更多设置 → 开发者选项 → 打开「USB 调试」+「USB 安装」"
echo "  3) 数据线拔插一次，弹「允许 USB 调试？」勾「始终允许」→ 允许"
echo ""

adb start-server >/dev/null 2>&1

# 仅认 Type-C USB 红米（排除 192.168.* 无线 ADB，避免误连其他手机）
pick_usb_redmi() {
  local s
  s="$(adb devices | awk -v t="${REDMI_SERIAL}" '$1==t && $2=="device"{print $1; exit}')"
  if [[ -n "${s}" ]]; then
    echo "${s}"
    return 0
  fi
  adb devices | awk '/\tdevice$/{print $1}' | while read -r d; do
    if [[ "${d}" != *:* ]]; then
      echo "${d}"
      break
    fi
  done
}

# 2. 轮询等待 ADB
echo "等待红米 USB ADB 上线（serial=${REDMI_SERIAL}，最长 ${WAIT_SEC}s）..."
echo "（已忽略无线 ADB，仅 Type-C USB）"
DEAD=$((SECONDS + WAIT_SEC))
DEV=""
while (( SECONDS < DEAD )); do
  DEV="$(pick_usb_redmi | head -1)"
  if [[ -n "$DEV" ]]; then
    echo ""
    echo "✅ ADB 设备已上线: $DEV"
    break
  fi
  if (( SECONDS % 10 == 0 )); then
    # 每 10s 打一行状态
    state=$(adb devices | tail -n +2 | head -1)
    [[ -n "$state" ]] && echo "  [$SECONDS s] $state"
  fi
  sleep 2
done

if [[ -z "$DEV" ]]; then
  echo "❌ 等待超时，仍未检测到 ADB 设备。请确认手机端「USB 调试」已开启 + 已授权此 Mac。"
  ioreg -p IOUSB -l 2>/dev/null | grep -A 3 "Xiaomi\|2312DRAABC" | head -10 || true
  exit 2
fi

adb -s "$DEV" shell "getprop ro.product.model; getprop ro.build.version.release; pidof com.tencent.mm; dumpsys package com.tencent.mm | grep versionName | head -1" 2>&1 | head -8
echo ""

# 2.5 初始化 uiautomator2（ATX + u2.jar，Agent 解封依赖 u2）
echo "=== 初始化 uiautomator2 ==="
if python3 -m uiautomator2 init --serial "$DEV" 2>&1 | tail -8; then
  echo "✅ u2 init 完成"
else
  echo "⚠️ u2 init 失败，继续尝试 oneclick（Agent 可能无 u2）"
fi
echo ""

# 3. oneclick 起 SDK + Frida + Agent
echo "=== 启动 oneclick（WS + Frida）==="
DEVICE_SERIAL="$DEV" bash "${SDK_ROOT}/scripts/frida_workphone_oneclick.sh" 2>&1 | tail -25
echo ""

# 4. 等 WS Agent 上线
echo "等 WS Agent 上线..."
for i in $(seq 1 30); do
  ws=$(curl -s --max-time 3 http://127.0.0.1:8899/api/v3/connection/status 2>/dev/null \
    | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['online_ws_count'])" 2>/dev/null || echo 0)
  if [[ "$ws" -ge 1 ]]; then
    echo "✅ WS Agent online"
    break
  fi
  sleep 2
done

# 5. 写入临时配置
CONF="${SDK_ROOT}/tmp/unblock_typec_$(date +%H%M%S).yaml"
cat > "$CONF" <<EOF
sdk_base: "http://127.0.0.1:8899"
default_max_rounds: 18
default_chat_interval_sec: 8
default_use_web_search: true
concurrency: 1
retry_on_fallback: 1
between_task_sleep_sec: 4
targets:
  - device_id: "$DEV"
    wxid: ""
    phone: ""
    reason: "$REASON"
    enabled: true
    note: "Type-C 红米 一键"
EOF
echo "临时配置: $CONF"

# 6. 跑批量
echo "=== 跑批量解封 ==="
python3 "${SDK_ROOT}/scripts/wechat_unblock_batch.py" -c "$CONF" 2>&1 | tail -30 || true

# 7. 报告
LATEST=$(ls -t "${SDK_ROOT}"/tmp/unblock_batch_*/summary.md 2>/dev/null | head -1)
echo ""
echo "=== 报告 ==="
[[ -f "$LATEST" ]] && cat "$LATEST"
echo ""
echo "全部日志：$LOG"
