#!/usr/bin/env bash
# 等待 ADB device → oneclick → 微信登录 E2E（无人值守续跑）
# 用法: bash sdk/scripts/wait_adb_then_login.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SDK_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
SERIAL="${REDMI_SERIAL:-xgfe65eimrrofyws}"
WAIT_SEC="${WAIT_SEC:-600}"
API="${SDK_API:-http://127.0.0.1:8899}"
export ANDROID_ADB_SERVER_PORT="${ANDROID_ADB_SERVER_PORT:-5038}"
ADB=(adb -P "${ANDROID_ADB_SERVER_PORT}")
LOG="${SDK_ROOT}/logs/wait_adb_then_login.log"

mkdir -p "${SDK_ROOT}/logs"
log() { echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

is_phone_serial() {
  local s="$1"
  local brand
  brand=$("${ADB[@]}" -s "$s" shell getprop ro.product.brand 2>/dev/null | tr -d '\r')
  [[ "$brand" != "haier" ]]
}

log "wait_adb_then_login start serial=${SERIAL} wait=${WAIT_SEC}s adb_port=${ANDROID_ADB_SERVER_PORT}"

DEAD=$((SECONDS + WAIT_SEC))
found=""

while (( SECONDS < DEAD )); do
  if "${ADB[@]}" -s "$SERIAL" get-state 2>/dev/null | grep -qx device && is_phone_serial "$SERIAL"; then
    found="$SERIAL"
    break
  fi
  while IFS= read -r any; do
    [[ -z "$any" ]] && continue
    is_phone_serial "$any" || continue
    found="$any"
    SERIAL="$any"
    break
  done < <("${ADB[@]}" devices 2>/dev/null | awk '/\tdevice$/{print $1}')
  [[ -n "$found" ]] && break
  ANDROID_ADB_SERVER_PORT="${ANDROID_ADB_SERVER_PORT}" bash "${SCRIPT_DIR}/connection_keeper_daemon.sh" --once >>"$LOG" 2>&1 || true
  sleep 10
done

if [[ -z "$found" ]]; then
  log "timeout: no phone adb device after ${WAIT_SEC}s"
  exit 2
fi

log "adb online serial=${found} → oneclick"
DEVICE_SERIAL="$found" ANDROID_ADB_SERVER_PORT="${ANDROID_ADB_SERVER_PORT}" \
  bash "${SCRIPT_DIR}/frida_workphone_oneclick.sh" -d "$found" >>"$LOG" 2>&1 || true

ws="$(curl -s "${API}/api/v3/connection/status" | python3 -c "import sys,json;print(json.load(sys.stdin).get('data',{}).get('online_ws_count',0))" 2>/dev/null || echo 0)"
log "ws_online=${ws}"

if [[ "$ws" -lt 1 ]]; then
  log "ws still 0, waiting 120s for Agent..."
  bash "${SCRIPT_DIR}/wait_ws_agent.sh" -d xgfe65eimrrofyws -b "$API" -t 120 -i 5 >>"$LOG" 2>&1 || true
fi

log "wechat login test..."
REDMI_SERIAL="$found" bash "${SCRIPT_DIR}/wechat_login_typec_test.sh" 2>&1 | tee -a "$LOG"

log "done"
