#!/bin/bash
#
# 一键设置模拟器：创建红米13 AVD + 中文系统 + 搜狗五笔 + Agent
# 前置：已安装 Android SDK（sdkmanager/avdmanager/emulator/adb）
#
set -e

ANDROID_HOME="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
export PATH="$ANDROID_HOME/emulator:$ANDROID_HOME/platform-tools:$ANDROID_HOME/cmdline-tools/latest/bin:$PATH"

AVD_NAME="Redmi13"
IMAGE="system-images;android-34;google_apis;arm64-v8a"
SDK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

echo "============================================"
echo "  红米13模拟器 一键设置"
echo "============================================"

# 1. 检查镜像
if [ ! -d "$ANDROID_HOME/system-images/android-34/google_apis/arm64-v8a" ]; then
  echo "[1/6] 下载 ARM64 系统镜像..."
  yes | sdkmanager "$IMAGE"
else
  echo "[1/6] 系统镜像已存在 ✓"
fi

# 检查 emulator
if [ ! -f "$ANDROID_HOME/emulator/emulator" ]; then
  echo "[1b] 下载 emulator..."
  yes | sdkmanager "emulator"
fi

# 2. 创建 AVD
if $ANDROID_HOME/emulator/emulator -list-avds 2>/dev/null | grep -q "$AVD_NAME"; then
  echo "[2/6] AVD $AVD_NAME 已存在 ✓"
else
  echo "[2/6] 创建 AVD: $AVD_NAME（红米13: 1080x2400, 8GB RAM）"
  echo "no" | avdmanager create avd -n "$AVD_NAME" -k "$IMAGE" -d "pixel_6" --force
  # 配置：8GB RAM、128GB 存储、1080x2400
  AVD_INI="$HOME/.android/avd/${AVD_NAME}.avd/config.ini"
  if [ -f "$AVD_INI" ]; then
    cat >> "$AVD_INI" <<'CONF'
hw.ramSize=8192
disk.dataPartition.size=128G
hw.lcd.width=1080
hw.lcd.height=2400
hw.lcd.density=420
hw.keyboard=yes
hw.gpu.enabled=yes
hw.gpu.mode=auto
skin.dynamic=yes
CONF
    echo "   配置已写入: 8GB RAM, 1080x2400, 128GB"
  fi
fi

# 3. 启动模拟器
echo "[3/6] 启动模拟器..."
$ANDROID_HOME/emulator/emulator -avd "$AVD_NAME" -no-snapshot-save -gpu auto &
EMU_PID=$!
echo "   模拟器 PID: $EMU_PID"

# 等设备上线
echo "   等待设备就绪（最多 120s）..."
for i in $(seq 1 60); do
  if adb shell getprop sys.boot_completed 2>/dev/null | grep -q "1"; then
    echo "   设备已就绪 ✓ (${i}x2s)"
    break
  fi
  sleep 2
done

SERIAL=$(adb devices | grep "emulator" | head -1 | awk '{print $1}')
if [ -z "$SERIAL" ]; then
  echo "❌ 模拟器未上线，请检查"
  exit 1
fi
echo "   设备序列号: $SERIAL"

# 4. 设置中文
echo "[4/6] 设置中文系统..."
adb -s "$SERIAL" shell "settings put system system_locales zh-CN"
adb -s "$SERIAL" shell "setprop persist.sys.language zh"
adb -s "$SERIAL" shell "setprop persist.sys.country CN"
adb -s "$SERIAL" shell "setprop persist.sys.localevar"
adb -s "$SERIAL" shell "settings put global device_name '红米13'"
echo "   中文系统设置完成 ✓"

# 5. 安装搜狗五笔输入法
echo "[5/6] 安装搜狗五笔输入法..."
SOGOU_APK="$SDK_ROOT/apks/sogou_wubi.apk"
if [ -f "$SOGOU_APK" ]; then
  adb -s "$SERIAL" install -r "$SOGOU_APK"
  echo "   搜狗五笔已安装 ✓"
  # 设为默认输入法
  adb -s "$SERIAL" shell "ime enable com.sohu.inputmethod.sogou.wubi/.SogouIME" 2>/dev/null || true
  adb -s "$SERIAL" shell "ime set com.sohu.inputmethod.sogou.wubi/.SogouIME" 2>/dev/null || true
  echo "   搜狗五笔已设为默认 ✓"
else
  echo "   ⚠️ 未找到 $SOGOU_APK"
  echo "   请下载搜狗五笔 APK 到 $SDK_ROOT/apks/sogou_wubi.apk 后重新执行本脚本"
  echo "   或手动安装：adb install sogou_wubi.apk"
fi

# 6. 安装并启动 Agent
echo "[6/6] 安装 Agent 到模拟器..."
# 先安装 Python（如果是 Termux 环境；模拟器走 ADB push）
AGENT_DIR="$SDK_ROOT/agent"
REMOTE_DIR="/data/local/tmp/workphone-agent"
adb -s "$SERIAL" shell "mkdir -p $REMOTE_DIR"
adb -s "$SERIAL" push "$AGENT_DIR/agent.py" "$REMOTE_DIR/"
adb -s "$SERIAL" push "$AGENT_DIR/skill_executor.py" "$REMOTE_DIR/"
adb -s "$SERIAL" push "$AGENT_DIR/error_handler.py" "$REMOTE_DIR/"
adb -s "$SERIAL" push "$AGENT_DIR/vision_helper.py" "$REMOTE_DIR/"
adb -s "$SERIAL" push "$AGENT_DIR/voice_agent.py" "$REMOTE_DIR/"
adb -s "$SERIAL" push "$AGENT_DIR/requirements.txt" "$REMOTE_DIR/"
adb -s "$SERIAL" shell "mkdir -p $REMOTE_DIR/skills"
for sk in wechat douyin xhs xianyu; do
  adb -s "$SERIAL" shell "mkdir -p $REMOTE_DIR/skills/$sk"
  adb -s "$SERIAL" push "$AGENT_DIR/skills/$sk/" "$REMOTE_DIR/skills/$sk/" 2>/dev/null || true
done
adb -s "$SERIAL" push "$AGENT_DIR/skills/__init__.py" "$REMOTE_DIR/skills/"
adb -s "$SERIAL" push "$AGENT_DIR/skills/base.py" "$REMOTE_DIR/skills/"
adb -s "$SERIAL" push "$AGENT_DIR/skills/app_manager.py" "$REMOTE_DIR/skills/"
adb -s "$SERIAL" push "$AGENT_DIR/skills/search.py" "$REMOTE_DIR/skills/"
adb -s "$SERIAL" push "$AGENT_DIR/skills/voice_control.py" "$REMOTE_DIR/skills/"

# 写 config.json
adb -s "$SERIAL" shell "cat > $REMOTE_DIR/config.json" <<AGENTCONF
{
  "device_id": "$SERIAL",
  "server_url": "ws://10.0.2.2:8899/ws/device",
  "heartbeat_interval": 10,
  "project_id": "cunkebao"
}
AGENTCONF
echo "   Agent 文件已推送 ✓"
echo "   注意：10.0.2.2 是模拟器访问宿主机的地址"

echo ""
echo "============================================"
echo "  设置完成！"
echo "============================================"
echo "模拟器: $AVD_NAME ($SERIAL)"
echo "控制台: http://localhost:8899/static/index.html"
echo "API:    http://localhost:8899/docs"
echo ""
echo "下一步："
echo "  1. 先启动 SDK：cd sdk && ./scripts/start_sdk.sh"
echo "  2. 手动下载搜狗五笔 APK 到 sdk/apks/ 后执行本脚本"
echo "  3. 模拟器内启动 Agent（需 Termux 或 ADB shell）"
echo "============================================"
