#!/usr/bin/env bash
# 无线无 USB 微信全功能验收（纯 WS · adb_count 须为 0）
# 用法:
#   bash sdk/scripts/run_wireless_wechat_full_suite.sh
#   WORKPHONE_SDK_URL=http://192.168.3.1:8899 DEVICE_ID=xgfe65eimrrofyws bash ...
set -uo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
SDK="${WORKPHONE_SDK_URL:-http://127.0.0.1:8899}"
if [[ -f "$REPO_ROOT/sdk/config/active_sdk.env" ]]; then
  # shellcheck disable=SC1091
  source "$REPO_ROOT/sdk/config/active_sdk.env"
  SDK="${WORKPHONE_SDK_URL:-$SDK}"
fi
DEVICE_ID="${DEVICE_ID:-xgfe65eimrrofyws}"
TS="$(date +%Y%m%d_%H%M%S)"
EVID="${EVIDENCE_DIR:-$REPO_ROOT/开发文档/8、部署/05-测试验收/${TS%_*}_无线无USB全功能}"
mkdir -p "$EVID"

echo "==> 无线全量验收 SDK=$SDK device=$DEVICE_ID"
echo "==> 证据: $EVID"

bash "$REPO_ROOT/sdk/scripts/wait_ws_agent.sh" -d "$DEVICE_ID" -b "$SDK" -t "${WAIT_WS_SEC:-300}" -i 5

ADB_COUNT="$(curl -s -m 8 "$SDK/api/v3/connection/status" | python3 -c "import sys,json; print(json.load(sys.stdin)['data'].get('adb_count',-1))" 2>/dev/null || echo -1)"
WS_COUNT="$(curl -s -m 8 "$SDK/api/v3/connection/status" | python3 -c "import sys,json; print(json.load(sys.stdin)['data'].get('online_ws_count',0))" 2>/dev/null || echo 0)"
echo "transport: ws=$WS_COUNT adb=$ADB_COUNT" | tee "$EVID/00_transport.txt"
if [[ "${WS_COUNT:-0}" -lt 1 ]]; then
  echo "ABORT: WS 未在线" >&2; exit 2
fi

echo "==> Frida 无线 reload"
curl -s -m 35 -X POST "$SDK/api/v3/devices/$DEVICE_ID/modules/reload" \
  -H 'Content-Type: application/json' \
  -d '{"module_ids":["wechat"],"force":true}' | tee "$EVID/frida_reload.json" >/dev/null
sleep 8

EXIT=0
WORKPHONE_SDK_URL="$SDK" DEVICE_ID="$DEVICE_ID" INCLUDE_FORWARD=1 EVIDENCE_DIR="$EVID/realdevice" \
  bash "$REPO_ROOT/sdk/scripts/run_wechat_realdevice_acceptance.sh" 2>&1 | tee "$EVID/01_realdevice.log" || EXIT=1

cd "$REPO_ROOT/../cunkebao_v3/Server" 2>/dev/null || cd "$REPO_ROOT/../../cunkebao_v3/Server"
CKB_PASSWORD="${CKB_PASSWORD:-zhiqun1984}" DEVICE_ID="$DEVICE_ID" TIMEOUT_SEC="${TIMEOUT_SEC:-90}" \
  bash scripts/workphone_bff_acceptance.sh 2>&1 | tee "$EVID/02_bff.log" || EXIT=1

SDK_BASE_URL="$SDK" SDK_DEVICE_ID="$DEVICE_ID" \
  python3 "$REPO_ROOT/sdk/scripts/matrix_hook_catalog_verify.py" -d "$DEVICE_ID" 2>&1 | tee "$EVID/03_hook_catalog.log" || true

export WORKPHONE_SDK_URL="$SDK"
python3 <<'PY' | tee "$EVID/04_revoke_e2e.json"
import json, urllib.request, time, os
SDK=os.environ["WORKPHONE_SDK_URL"]
BFF="http://127.0.0.1:8082"
DEV=os.environ.get("DEVICE_ID","xgfe65eimrrofyws")
out={"wireless_only": True, "results": []}

def req(url, data=None, token=None, timeout=120):
    h={"Content-Type":"application/json"}
    if token: h["Authorization"]="Bearer "+token
    r=urllib.request.Request(url, (json.dumps(data).encode() if data is not None else None), headers=h, method=("POST" if data is not None else "GET"))
    with urllib.request.urlopen(r, timeout=timeout) as resp:
        return json.loads(resp.read())

token=req(BFF+"/v1/auth/login", {"account":"karuo","password":"zhiqun1984","typeId":1})["data"]["token"]
send=req(BFF+"/v1/workphone/message/send", {"device_id":DEV,"platform":"wechat","to_id":"filehelper","content":f"[无线撤回] {time.strftime('%H:%M:%S')}","msg_type":"text"}, token)
sd=(send.get("data") or {}).get("data", send.get("data"))
mid=str(sd.get("message_id")) if isinstance(sd,dict) and sd.get("message_id") else None
out["results"].append({"test":"send","ok":send.get("code")==200 and sd.get("verified"),"message_id":mid})
if mid:
    time.sleep(2)
    body={"device_id":DEV,"action":"revoke_message","params":{"msg_svr_id":mid,"talker":"filehelper"}}
    r=urllib.request.Request(SDK+"/api/v3/wechat/execute", json.dumps(body).encode(), headers={"Content-Type":"application/json"}, method="POST")
    rv=json.loads(urllib.request.urlopen(r, timeout=120).read())
    d=rv.get("data") or {}
    out["results"].append({"test":"revoke_message","ok":bool(d.get("verified") or d.get("success") or d.get("revoked")),"data":d})
    time.sleep(3)
    msgs=req(BFF+f"/v1/workphone/messages?device_id={DEV}&platform=wechat&limit=8&talker=filehelper", token=token)
    items=(msgs.get("data") or {}).get("items") or (msgs.get("data") or {}).get("messages") or []
    out["results"].append({"test":"revoke_in_history","ok":any("撤回" in str(m.get("content","")) or str(m.get("type"))=="10000" for m in items if isinstance(m,dict))})
out["pass"]=sum(1 for x in out["results"] if x.get("ok"))
out["total"]=len(out["results"])
print(json.dumps(out, ensure_ascii=False, indent=2))
PY

if command -v docker >/dev/null && docker ps --format '{{.Names}}' | grep -q cunkebao-server; then
  docker exec cunkebao-server php tests/four_end_device_wechat_chain_test.php 2>&1 | tee "$EVID/05_four_end_chain.log" || EXIT=1
fi

echo "==> 汇总见 $EVID"
exit "$EXIT"
