#!/usr/bin/env bash
# 等设备 WS 在线后自动跑卡若 gateway ai/chat 验收
set -euo pipefail
DEVICE="${DEVICE:-xgfe65eimrrofyws}"
API="${SDK_API:-http://127.0.0.1:8899}"
WAIT="${WAIT_SEC:-600}"

echo "等待设备 ${DEVICE} 上线（最长 ${WAIT}s）..."
dead=$((SECONDS + WAIT))
while (( SECONDS < dead )); do
  if curl -sf "${API}/api/v3/devices" | python3 -c "
import sys,json
d=json.load(sys.stdin)
arr=d if isinstance(d,list) else d.get('data',[])
print('yes' if any(x.get('device_id')=='${DEVICE}' for x in arr) else 'no')
" | grep -q yes; then
    echo "✅ 设备在线: ${DEVICE}"
    break
  fi
  sleep 5
done

curl -s -X POST "${API}/api/v3/devices/${DEVICE}/ai/chat" \
  -H "Content-Type: application/json" \
  -d '{"instruction":"获取微信版本号","timeout":120}' | python3 -m json.tool
