#!/bin/bash
#
# 工作手机 SDK 本地启动脚本
# 用法：在「工作手机」项目根目录执行
#   cd sdk && ./scripts/start_sdk.sh
# 或从 sdk 目录：
#   ./scripts/start_sdk.sh
#

set -e
SDK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$SDK_ROOT"

echo "============================================"
echo "  工作手机 SDK 本地启动"
echo "============================================"
echo "SDK 目录: $SDK_ROOT"
echo ""

# 1. 检查 Python
if ! command -v python3 &> /dev/null; then
    echo "❌ 未找到 python3"
    exit 1
fi

# 2. 检查依赖
if ! python3 -c "import uvicorn" 2>/dev/null; then
    echo "安装依赖: pip install -r requirements.txt"
    pip install -r requirements.txt
fi

# 3. 启动 SDK 服务（工作目录须为 sdk/app）
echo "[1/2] 启动 SDK 服务 (localhost:8899)..."
(cd "$SDK_ROOT/app" && python3 -m uvicorn main:app --host 0.0.0.0 --port 8899) &
SDK_PID=$!
sleep 3

# 4. 健康检查
if curl -s http://localhost:8899/health > /dev/null 2>&1; then
    echo "✅ SDK 服务已启动"
    curl -s http://localhost:8899/health | python3 -c "import json,sys; d=json.load(sys.stdin); print(f'   devices_online={d.get(\"devices_online\",0)}, adb_devices={d.get(\"adb_devices\",0)}')" 2>/dev/null || true
else
    echo "❌ SDK 启动失败"
    kill $SDK_PID 2>/dev/null
    exit 1
fi

echo ""
echo "[2/2] 启动 Agent（需模拟器已运行）..."
if adb devices 2>/dev/null | grep -q "emulator.*device"; then
    (cd "$SDK_ROOT/agent" && python3 agent.py -d emulator-5554 -s ws://127.0.0.1:8899/ws/device --heartbeat 10) &
    echo "✅ Agent 已启动（连接 emulator-5554）"
else
    echo "⚠️ 未检测到模拟器，跳过 Agent"
    echo "   启动模拟器后手动执行："
    echo "   cd $SDK_ROOT/agent && python3 agent.py -d emulator-5554 -s ws://127.0.0.1:8899/ws/device --heartbeat 10"
fi

echo ""
echo "============================================"
echo "  启动完成"
echo "============================================"
echo "SDK API:     http://localhost:8899"
echo "API 文档:    http://localhost:8899/docs"
echo "控制中心:    http://localhost:8899/static/index.html"
echo ""
echo "验证: curl -s localhost:8899/health | jq ."
echo "============================================"
