#!/usr/bin/env bash
# 等待设备 WebSocket Agent 上线（无线主控，不依赖 ADB）
# 用法:
#   bash wait_ws_agent.sh [device_id] [sdk_base] [max_wait_sec]
#   bash wait_ws_agent.sh -d device_id -b http://127.0.0.1:8899 -t 3600
set -euo pipefail
DEVICE_ID="xgfe65eimrrofyws"
SDK_BASE="http://127.0.0.1:8899"
MAX_WAIT="600"
INTERVAL="5"

while [[ $# -gt 0 ]]; do
  case "$1" in
    -d) DEVICE_ID="${2:?}"; shift 2 ;;
    -b|--base) SDK_BASE="${2:?}"; shift 2 ;;
    -t) MAX_WAIT="${2:?}"; shift 2 ;;
    -i) INTERVAL="${2:?}"; shift 2 ;;
    -*) echo "未知参数: $1" >&2; exit 2 ;;
    *) DEVICE_ID="$1"; shift; [[ $# -gt 0 ]] && SDK_BASE="$1" && shift; [[ $# -gt 0 ]] && MAX_WAIT="$1" && shift; break ;;
  esac
done

echo "等待 WS Agent: ${DEVICE_ID} @ ${SDK_BASE}（最长 ${MAX_WAIT}s）"
deadline=$((SECONDS + MAX_WAIT))
while (( SECONDS < deadline )); do
  json=$(curl -s --max-time 8 "${SDK_BASE}/api/v3/connection/status" || echo "")
  online=$(echo "$json" | python3 -c "
import sys, json
try:
  d = json.load(sys.stdin)['data']
  ids = d.get('online_device_ids') or []
  print('1' if '${DEVICE_ID}' in ids else '0')
except Exception:
  print('0')
" 2>/dev/null || echo "0")
  if [[ "$online" == "1" ]]; then
    echo "✅ WS Agent 在线: ${DEVICE_ID}"
    exit 0
  fi
  echo "  … $(date '+%H:%M:%S') 尚未连接，${INTERVAL}s 后重试"
  sleep "$INTERVAL"
done
echo "❌ 超时：${DEVICE_ID} WS Agent 未上线"
exit 1
