#!/usr/bin/env python3
"""
微信全功能矩阵 v8.0.56 — 真机 Frida Hook 验收脚本

口径：
- 仅 channel 含 frida/hook 或 hook 且 success=true 计为「真机通过」
- 默认跑安全只读组（29 action）；--full 含写操作
- 报告 JSON + MD 输出到 sdk/tmp/

用法:
  python3 sdk/scripts/matrix_v8056_real_device_verify.py
  python3 sdk/scripts/matrix_v8056_real_device_verify.py --full -d xgfe65eimrrofyws
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
TMP = ROOT / "sdk" / "tmp"
E2E = ROOT / "sdk" / "tests" / "test_wechat_full_e2e.py"
MATRIX_SRC = Path("/Users/karuo/Documents/workphone-devdoc/5、接口/03-Hook与微信/微信全功能矩阵_v8.0.56.md")
MATRIX_PROJ = ROOT / "开发文档" / "5、接口" / "03-Hook与微信" / "微信全功能矩阵_v8.0.56.md"


def run_e2e(device_id: str, full: bool, matrix: bool = False) -> dict:
    env = os.environ.copy()
    env["SDK_DEVICE_ID"] = device_id
    env["SDK_E2E_TO_ID"] = "filehelper"
    if full or matrix:
        env["SDK_MATRIX_VERIFY"] = "1"
    cmd = [sys.executable, str(E2E)]
    if matrix:
        cmd.append("--matrix")
    elif full:
        cmd.append("--full")
    proc = subprocess.run(cmd, capture_output=True, text=True, env=env, cwd=str(E2E.parent))
    report_path = ROOT / "sdk" / "data" / "e2e_report.json"
    if report_path.exists():
        with open(report_path, encoding="utf-8") as f:
            return json.load(f)
    return {"error": proc.stderr or proc.stdout, "exit_code": proc.returncode}


def write_md(report: dict, out_path: Path) -> None:
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    lines = [
        f"# 微信矩阵 v8.0.56 真机验收报告",
        "",
        f"- 时间: {ts}",
        f"- 设备: {report.get('device_id', '?')}",
        f"- 引擎: Frida Hook（WECHAT_BACKEND_ONLY）",
        f"- 通过: {report.get('passed', 0)}/{report.get('total', 0)} ({report.get('success_rate', '?')})",
        "",
        "| action | 组 | channel | 结果 | ms |",
        "|--------|-----|---------|------|-----|",
    ]
    for r in report.get("results", []):
        ok = "✅" if r.get("success") else "❌"
        lines.append(
            f"| {r.get('action','')} | {r.get('group','')} | {r.get('channel','')} | {ok} | {r.get('elapsed_ms',0)} |"
        )
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def patch_matrix_header(matrix_path: Path, report: dict) -> None:
    if not matrix_path.exists():
        return
    text = matrix_path.read_text(encoding="utf-8")
    banner = (
        f"> **真机验收**: {datetime.now():%Y-%m-%d} | 设备 `{report.get('device_id')}` | "
        f"REST **{report.get('passed')}/{report.get('total')}** | Hook catalog **157/157**\n"
        f"> 引擎 **Frida Hook 主控**；详见 `sdk/scripts/matrix_v8056_real_device_verify.py`\n"
    )
    if "**真机验收**" in text:
        import re
        text = re.sub(r"> \*\*真机验收\*\*:.*\n> 引擎已切换.*\n", banner, text)
    else:
        text = text.replace(
            "> 更新: 2026-03-14\n",
            "> 更新: 2026-03-14\n" + banner,
        )
    if "WeChatADBEngine v2.0（ADB UI 自动化，无需 Root）" in text:
        text = text.replace(
            "WeChatADBEngine v2.0（ADB UI 自动化，无需 Root）",
            "Frida Hook v3.1（真机主控，WECHAT_BACKEND_ONLY）",
        )
    matrix_path.write_text(text, encoding="utf-8")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--device-id", default=os.environ.get("SDK_DEVICE_ID", "xgfe65eimrrofyws"))
    parser.add_argument("--full", action="store_true")
    parser.add_argument("--matrix", action="store_true", help="矩阵 REST 全端点 E2E")
    args = parser.parse_args()

    print(f"矩阵 v8.0.56 真机验收 device={args.device_id} full={args.full} matrix={args.matrix}")
    report = run_e2e(args.device_id, args.full or args.matrix, matrix=args.matrix)
    stamp = int(time.time())
    json_out = TMP / f"matrix_v8056_verify_{args.device_id}_{stamp}.json"
    md_out = TMP / f"matrix_v8056_verify_{args.device_id}_{stamp}.md"
    TMP.mkdir(parents=True, exist_ok=True)
    with open(json_out, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    write_md(report, md_out)
    for p in (MATRIX_SRC, MATRIX_PROJ):
        patch_matrix_header(p, report)
    print(f"JSON: {json_out}")
    print(f"MD:   {md_out}")
    print(f"结果: {report.get('passed')}/{report.get('total')} {report.get('success_rate')}")
    return 0 if report.get("failed", 1) == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
