#!/usr/bin/env bash
# 工作手机 Agent 连接顺序：① NAS 局域网 ② 本机 Docker ③ NAS 外网 frp
# 用法: bash sdk/scripts/nas_primary_agent_setup.sh [device_id]
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SDK_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DEVICE_ID="${1:-xgfe65eimrrofyws}"
SDK_PORT="${WORKPHONE_SDK_PORT:-8899}"
NAS_FRP_HOST="${WORKPHONE_NAS_FRP_HOST:-open.quwanzhi.com}"
ADB_PORT="${ANDROID_ADB_SERVER_PORT:-5038}"
ADB=(adb -P "${ADB_PORT}")
export ANDROID_ADB_SERVER_PORT="${ADB_PORT}"

pick_mac_lan_ip() {
  local ip
  for ip in $(ifconfig 2>/dev/null | awk '/inet /{print $2}' | grep -v '^127\.'); do
    [[ "$ip" == 198.18.* ]] && continue
    [[ "$ip" == 192.168.110.* ]] && { echo "$ip"; return; }
  done
  for ip in $(ifconfig 2>/dev/null | awk '/inet /{print $2}' | grep -v '^127\.'); do
    [[ "$ip" == 198.18.* ]] && continue
    [[ "$ip" == 192.168.* ]] && { echo "$ip"; return; }
  done
  echo "127.0.0.1"
}

health_ok() {
  curl -sf --max-time 3 "http://$1:${SDK_PORT}/health" >/dev/null 2>&1
}

MAC_IP="$(pick_mac_lan_ip)"

# ① NAS 局域网 → ② 本机 Docker → ③ NAS 外网
PRIMARY_HOST=""
PRIMARY_TIER="nas_lan"
for h in 192.168.110.101 192.168.1.201; do
  if health_ok "$h"; then
    PRIMARY_HOST="$h"
    break
  fi
done
if [[ -z "${PRIMARY_HOST}" && "${MAC_IP}" != "127.0.0.1" ]] && health_ok "${MAC_IP}"; then
  PRIMARY_HOST="${MAC_IP}"
  PRIMARY_TIER="mac_docker"
fi
if [[ -z "${PRIMARY_HOST}" ]] && health_ok "${NAS_FRP_HOST}"; then
  PRIMARY_HOST="${NAS_FRP_HOST}"
  PRIMARY_TIER="nas_frp"
fi
if [[ -z "${PRIMARY_HOST}" ]]; then
  PRIMARY_HOST="192.168.110.101"
  echo "[nas-primary] 警告: ①②③ 均不可达，server_url 仍写 NAS 局域网 ${PRIMARY_HOST}（Agent 将按序探测）"
fi

PRIMARY_WS="ws://${PRIMARY_HOST}:${SDK_PORT}/ws/device"
CONFIG_TMP="$(mktemp)"
export DEVICE_ID PRIMARY_WS SDK_PORT MAC_IP NAS_FRP_HOST CONFIG_TMP
python3 - <<'PY'
import json, os

port = os.environ["SDK_PORT"]
mac = os.environ["MAC_IP"]
frp = os.environ["NAS_FRP_HOST"]
primary = os.environ["PRIMARY_WS"]

# 固定回退顺序：NAS 内网 → 本机 Docker → NAS 外网
ordered = [
    f"ws://192.168.110.101:{port}/ws/device",
    f"ws://192.168.1.201:{port}/ws/device",
    f"ws://{mac}:{port}/ws/device",
    f"ws://{frp}:{port}/ws/device",
]
pubs = []
seen = {primary}
for u in ordered:
    if u not in seen:
        seen.add(u)
        pubs.append(u)

cfg = {
    "device_id": os.environ["DEVICE_ID"],
    "server_url": primary,
    "public_servers": pubs,
    "heartbeat_interval": 10,
    "project_id": "cunkebao",
    "connection_priority": ["nas_lan", "mac_docker", "nas_frp"],
}
with open(os.environ["CONFIG_TMP"], "w", encoding="utf-8") as f:
    json.dump(cfg, f, ensure_ascii=False, indent=2)
PY

echo "[nas-primary] 连接顺序: ①NAS局域网 ②本机Docker ③NAS外网(${NAS_FRP_HOST})"
echo "[nas-primary] 当前主服 tier=${PRIMARY_TIER} host=${PRIMARY_HOST}"
echo "[nas-primary] server_url: ${PRIMARY_WS}/${DEVICE_ID}"
cat "${CONFIG_TMP}"

REMOTE_CFG="/data/data/com.termux/files/home/workphone/agent/config.json"
SERIAL="$("${ADB[@]}" devices 2>/dev/null | awk '/device$/{print $1; exit}')"
PUBLIC_LIST="ws://192.168.110.101:${SDK_PORT}/ws/device,ws://192.168.1.201:${SDK_PORT}/ws/device,ws://${MAC_IP}:${SDK_PORT}/ws/device,ws://${NAS_FRP_HOST}:${SDK_PORT}/ws/device"

if [[ -n "${SERIAL}" ]]; then
  echo "[nas-primary] 推送 config → ${SERIAL}"
  "${ADB[@]}" -s "${SERIAL}" push "${CONFIG_TMP}" "${REMOTE_CFG}" 2>/dev/null || \
    "${ADB[@]}" -s "${SERIAL}" push "${CONFIG_TMP}" /sdcard/workphone_config.json
  echo "[nas-primary] Termux:"
  echo "  export WP_SERVER_URL=${PRIMARY_WS}"
  echo "  export WP_PUBLIC_SERVERS=${PUBLIC_LIST}"
  echo "  export WP_AUTO_DISCOVER=1"
  echo "  cd ~/workphone/agent && python agent.py -d ${DEVICE_ID}"
else
  echo "[nas-primary] 未检测到 adb device → ${SDK_ROOT}/agent/config.nas-active.json"
  cp "${CONFIG_TMP}" "${SDK_ROOT}/agent/config.nas-active.json"
fi
rm -f "${CONFIG_TMP}"
