#!/bin/bash
#
# 等待设备授权后自动启动 Agent
# 用法: bash wait_and_start.sh [server_url]
#
SERVER_URL="${1:-ws://192.168.1.100:8899/ws/device}"
DEVICE_SERIAL="dc9c23e00510"
MAX_WAIT=300  # 最多等5分钟

echo "⏳ 等待设备 $DEVICE_SERIAL 授权..."
echo ""
echo "📱 请在 Redmi Note 11 上执行以下操作："
echo "   1. 设置 → 更多设置 → 开发者选项"
echo "   2. 确认「USB调试」已开启"
echo "   3. ⚠️ 关键：开启「USB调试（安全设置）」← 小米/红米特有！"
echo "   4. 如果没有弹出授权弹窗，点击「撤销USB调试授权」后重新插拔USB线"
echo "   5. 弹窗出现后，勾选「始终允许」→ 点「确定」"
echo ""

SECONDS_WAITED=0
while [ $SECONDS_WAITED -lt $MAX_WAIT ]; do
    STATE=$(adb -s "$DEVICE_SERIAL" get-state 2>/dev/null)
    if [ "$STATE" = "device" ]; then
        echo "✅ 设备已授权！"
        MODEL=$(adb -s "$DEVICE_SERIAL" shell getprop ro.product.model 2>/dev/null)
        ANDROID=$(adb -s "$DEVICE_SERIAL" shell getprop ro.build.version.release 2>/dev/null)
        MIUI=$(adb -s "$DEVICE_SERIAL" shell getprop ro.miui.ui.version.name 2>/dev/null)
        echo "   型号: $MODEL | Android: $ANDROID | MIUI: $MIUI"
        echo ""
        echo "🚀 正在启动 Agent..."
        cd "$(dirname "$0")"
        python3 agent.py -s "$SERVER_URL"
        exit 0
    fi
    sleep 3
    SECONDS_WAITED=$((SECONDS_WAITED + 3))
    printf "\r   已等待 %ds / %ds... (状态: %s)" "$SECONDS_WAITED" "$MAX_WAIT" "${STATE:-offline}"
done

echo ""
echo "❌ 等待超时，请检查手机设置"
exit 1
