#!/usr/bin/env bash
# WP-WX-04：真机 WS 在线后一键探针（扫码加友契约层）
# 用法：DEVICE_ID=xgfe65eimrrofyws bash sdk/scripts/probe_wp_wx04_when_ws_online.sh
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
DEVICE_ID="${DEVICE_ID:-xgfe65eimrrofyws}"
# Mac Docker：localhost(IPv6) 才打到 workphone-sdk；127.0.0.1 可能落到旧进程
BASE="${WORKPHONE_SDK_URL:-http://localhost:8899}"
BASE="${BASE%/}"
DEFAULT_IMAGE_FILE="$ROOT_DIR/开发文档/8、部署/05-测试验收/screenshots/verification_110/H26_二维码_generate_my_qr_code_1779086272.png"
IMAGE_URL="${IMAGE_URL:-}"
IMAGE_FILE="${IMAGE_FILE:-}"
IMAGE_BASE64="${IMAGE_BASE64:-}"
VERIFY_MESSAGE="${VERIFY_MESSAGE:-WP-WX-04 probe}"

if [[ -z "$IMAGE_URL" && -z "$IMAGE_FILE" && -z "$IMAGE_BASE64" && -f "$DEFAULT_IMAGE_FILE" ]]; then
  IMAGE_FILE="$DEFAULT_IMAGE_FILE"
fi

TMP_EXTRACT="$(mktemp /tmp/wpwx04_extract.XXXXXX.json)"
TMP_ADD="$(mktemp /tmp/wpwx04_add.XXXXXX.json)"
cleanup() {
  rm -f "$TMP_EXTRACT" "$TMP_ADD"
}
trap cleanup EXIT

python3 - "$TMP_EXTRACT" "$TMP_ADD" "$DEVICE_ID" "$IMAGE_FILE" "$IMAGE_BASE64" "$IMAGE_URL" "$VERIFY_MESSAGE" <<'PY'
import base64
import json
import os
import sys

extract_path, add_path, device_id, image_file, image_b64, image_url, verify_message = sys.argv[1:]
payload = {"device_id": device_id, "platform": "wechat"}
if image_url:
    payload["image_url"] = image_url
elif image_file:
    with open(image_file, "rb") as f:
        payload["image_base64"] = base64.b64encode(f.read()).decode("ascii")
elif image_b64:
    payload["image_base64"] = image_b64
else:
    raise SystemExit("需提供 IMAGE_FILE / IMAGE_URL / IMAGE_BASE64 之一")

with open(extract_path, "w", encoding="utf-8") as f:
    json.dump(payload, f, ensure_ascii=False)

payload["verify_message"] = verify_message
with open(add_path, "w", encoding="utf-8") as f:
    json.dump(payload, f, ensure_ascii=False)
PY

echo "▶ SDK=$BASE DEVICE=$DEVICE_ID"
curl -sS --connect-timeout 3 --max-time 8 "$BASE/health" | python3 -m json.tool 2>/dev/null || true
echo "▶ connection/status"
curl -sS --connect-timeout 3 --max-time 10 "$BASE/api/v3/connection/status" \
  | python3 -c "import sys,json;d=json.load(sys.stdin)['data'];print('online_ws_count=',d.get('online_ws_count'),'devices=',d.get('online_device_ids'))"
echo "▶ POST /scan/extract-qr"
curl -sS --connect-timeout 3 --max-time 90 -X POST "$BASE/api/v3/scan/extract-qr" \
  -H 'Content-Type: application/json' \
  --data-binary "@$TMP_EXTRACT" \
  | python3 -m json.tool 2>/dev/null || true

echo "▶ POST /scan/add-friend-from-image"
curl -sS --connect-timeout 3 --max-time 120 -X POST "$BASE/api/v3/scan/add-friend-from-image" \
  -H 'Content-Type: application/json' \
  --data-binary "@$TMP_ADD" \
  | python3 -m json.tool 2>/dev/null || true
