#!/usr/bin/env python3
"""
奥创 SDK 通信协议（客服通信接口总目录 · EnumMsgType 指令类 Task）↔ 工作手机 SDK action 覆盖矩阵。

目的：对照奥创 proto 的服务端→设备「指令类任务」(1070-1270)，核对本 SDK 是否已具备
可下发的等价 action（ACTION_TO_RPC + ACTION_ALIASES catalog）。锁定真实缺口，禁止漏项。

用法: python3 sdk/scripts/aochuang_protocol_coverage.py [--md 输出.md]
真机铁律：本脚本仅做「能力覆盖」静态核对，不代表真机已验收。
"""
from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
HE = ROOT / "sdk/agent/hook/hook_executor.py"

# 奥创协议「服务端/PC → 设备」指令类任务枚举 → 本 SDK 期望 action（None = 缺口）
# 依据 资料/工作手机客服通信接口总目录(带通信协议)SDK.doc EnumMsgType
PROTO_TASKS: dict[str, tuple[str, str | None]] = {
    "TalkToFriendTask(1070)":            ("给好友发消息", "send_message"),
    "PostSNSNewsTask(1071)":             ("发朋友圈", "post_moments"),
    "AddFriendsTask(1072)":              ("主动添加好友", "add_friend"),
    "DeleteSNSNewsTask(1074)":           ("删除朋友圈", "delete_moments"),
    "AcceptFriendAddRequestTask(1075)":  ("接受好友请求", "accept_friend"),
    "WeChatGroupSendTask(1076)":         ("群发消息", "mass_send"),
    "WeChatMaintenanceTask(1077)":       ("养号任务", "start_nurture"),
    "RequestTalkDetailTask(1078)":       ("请求图片/视频详情", "get_message_raw_xml"),
    "PullWeChatQrCodeTask(1079)":        ("上传当前微信二维码", "generate_my_qr_code"),
    "TriggerFriendPushTask(1080)":       ("推送好友列表", "get_contacts"),
    "TriggerCirclePushTask(1081)":       ("推送朋友圈列表", "get_moments"),
    "CircleCommentDeleteTask(1082)":     ("朋友圈评论删除", "delete_moment_comment"),
    "CircleCommentReplyTask(1084)":      ("朋友圈评论回复", "reply_moment_comment"),
    "TriggerMessageReadTask(1086)":      ("聊天窗口置已读", "mark_conversation_read"),
    "RevokeMessageTask(1087)":           ("消息撤回", "revoke_message"),
    "ForwardMessageTask(1088)":          ("转发消息", "forward_message"),
    "TriggerHistoryMsgPushTask(1089)":   ("推送历史聊天记录", "get_recent_messages"),
    "PullChatRoomQrCodeTask(1090)":      ("获取群二维码", "generate_group_qr_code"),
    "SendMultiPictureTask(1091)":        ("发送多张图片", "send_multi_image"),
    "ForwardMultiMessageTask(1092)":     ("转发多条消息", "forward_multiple"),
    "PostFriendDetectTask(1095)":        ("清粉任务", "detect_zombie_fans"),
    "PostStopFriendDetectTask(1096)":    ("终止清粉", "stop_detect_zombie_fans"),
    "PostMomentsPraiseTask(1098)":       ("朋友圈点赞", "like_moments"),
    "PostStopMomentsPraiseTask(1099)":   ("停止朋友圈点赞", "stop_moments_praise"),
    "PostStopWeChatMaintenanceTask(1100)": ("养号停止", "stop_nurture"),
    "ModifyFriendMemoTask(1101)":        ("修改备注", "set_friend_remark"),
    "AddFriendWithSceneTask(1102)":      ("场景加好友", "add_friend_with_scene"),
    "TakeLuckyMoneyTask(1200)":          ("领取红包/转账", "receive_red_packet"),
    "PullFriendCircleTask(1201)":        ("获取指定好友朋友圈", "get_friend_moments"),
    "PullCircleDetailTask(1202)":        ("获取朋友圈图片", "get_moment_detail"),
    "CircleLikeTask(1203)":              ("单条朋友圈点赞", "like_moments"),
    "TriggerChatroomPushTask(1210)":     ("推送群聊列表", "get_groups"),
    "RequestChatRoomInfoTask(1211)":     ("群聊详情", "get_group_info"),
    "RequestContactsInfoTask(1212)":     ("联系人详情", "get_contact_info"),
    "ChatRoomActionTask(1213)":          ("群聊管理", "set_group_name"),
    "AddFriendInChatRoomTask(1214)":     ("群内加好友", "add_friend_in_room"),
    "AddFriendFromPhonebookTask(1215)":  ("通讯录加好友", "add_friend_from_phonebook"),
    "DeleteFriendTask(1216)":            ("删除好友", "delete_friend"),
    "SendLuckyMoneyTask(1217)":          ("发红包", "send_red_packet"),
    "RequestTalkContentTask(1218)":      ("获取消息原始xml", "get_message_raw_xml"),
    "ForwardMessageByContentTask(1220)": ("转发消息内容", "forward_message"),
    "ChatRoomInviteApproveTask(1221)":   ("群主确认入群申请", "approve_group_invite"),
    "WechatLogoutTask(1222)":            ("微信登出", "logout"),
    "PhoneActionTask(1223)":             ("手机操作(重启等)", "phone_action"),
    "ContactLabelTask(1224)":            ("设置联系人标签", "set_contact_label"),
    "ContactLabelDeleteTask(1225)":      ("删除联系人标签", "delete_label"),
    "VoiceTransTextTask(1226)":          ("语音转文字", "voice_to_text"),
    "FindContactTask(1227)":             ("查找微信联系人", "search_contacts"),
    "AgreeJoinChatRoomTask(1229)":       ("同意加入群聊", "agree_join_group"),
    "ClearAllChatMsgTask(1230)":         ("清空聊天记录", "clear_chat_history"),
    "SendFriendVerifyTask(1231)":        ("聊天界面发送朋友验证", "send_friend_verify"),
    "TriggerConversationPushTask(1232)": ("会话列表推送", "get_conversations"),
    "WechatSettingTask(1233)":           ("微信设置(昵称/头像)", "set_nickname"),
    "PullFriendAddReqListTask(1234)":    ("加好友请求列表", "get_friend_requests"),
    "TriggerBizContactPushTask(1235)":   ("公众号列表", "get_official_accounts"),
    "AddFriendNameCardTask(1236)":       ("名片加好友", "add_friend_by_card"),
    "TriggerChatMsgIdsPushTask(1251)":   ("时间段内 msgSvrId", "get_msg_ids_by_time"),
    "RequestTalkMsgTask(1252)":          ("按 msgSvrId 取消息", "get_message_by_id"),
    "SearchBizContactTask(1254)":        ("搜索公众号/小程序", "search_official_account"),
    "PhoneStateTask(1256)":              ("手机状态(电量/存储)", "get_device_info"),
    "WeChatLocationTask(1258)":          ("微信查手机位置", "get_wechat_location"),
    "RemittanceTask(1260)":              ("转账", "send_transfer"),
    "WalletBalanceTask(1262)":           ("钱包余额", "get_wallet_balance"),
    "QueryHbDetailTask(1265)":           ("查询红包详情", "query_red_packet"),
    "JoinGroupByQrTask(1267)":           ("扫二维码进群", "join_group_by_qr"),
    "SendJielongTask(1268)":             ("发接龙消息", "send_jielong"),
    "ContactSetLabelTask(1270)":         ("设置用户标签", "set_contact_label"),
    "WechatLogoutTask(cmd)":             ("账号登出命令", "logout"),
    "PhoneActionTask(cmd-reboot)":       ("重启手机等命令", "phone_action"),
    "UpgradeDeviceAppNotice(cmd)":       ("软件升级通知", "check_for_update"),
}


def load_sdk_catalog() -> set[str]:
    text = HE.read_text(encoding="utf-8", errors="ignore")
    a = text.split("ACTION_TO_RPC:", 1)[1].split("ACTION_ALIASES:", 1)[0]
    b = text.split("ACTION_ALIASES:", 1)[1].split("\n\n", 1)[0]
    rpc = set(re.findall(r'"([a-z_]+)"\s*:', a))
    alias = set(re.findall(r'"([a-z_]+)"\s*:', b))
    return rpc | alias


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--md", default="")
    args = ap.parse_args()

    catalog = load_sdk_catalog()
    covered, gaps = [], []
    for task, (cn, action) in PROTO_TASKS.items():
        if action and action in catalog:
            covered.append((task, cn, action))
        elif action and action not in catalog:
            gaps.append((task, cn, f"{action}(映射缺失)"))
        else:
            gaps.append((task, cn, "无对应 action"))

    total = len(PROTO_TASKS)
    lines = [
        "# 奥创协议 ↔ 工作手机 SDK action 覆盖矩阵",
        "",
        f"> 真源：`资料/工作手机客服通信接口总目录(带通信协议)SDK.doc` · 自动生成 `sdk/scripts/aochuang_protocol_coverage.py`",
        f"> 指令类任务 **{total}** 项 · 已覆盖 **{len(covered)}** · 缺口 **{len(gaps)}** · 覆盖率 **{len(covered)*100//total}%**",
        "> 真机铁律：覆盖=能力映射就绪；真机 E2E 另见验收清单，禁止无证据标功能 ✅",
        "",
        "## 一、已覆盖",
        "",
        "| 协议任务 | 中文 | SDK action |",
        "|:---|:---|:---|",
    ]
    for t, cn, a in covered:
        lines.append(f"| {t} | {cn} | `{a}` |")
    lines += ["", "## 二、缺口（待补 action）", "", "| 协议任务 | 中文 | 现状 |", "|:---|:---|:---|"]
    for t, cn, a in gaps:
        lines.append(f"| {t} | {cn} | {a} |")

    md = "\n".join(lines) + "\n"
    if args.md:
        Path(args.md).write_text(md, encoding="utf-8")
        print(f"已写入 {args.md}")
    print(f"覆盖 {len(covered)}/{total} · 缺口 {len(gaps)}")
    for t, cn, _ in gaps:
        print(f"  GAP {t} {cn}")
    return 0


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