"""
中台 AI Brain · Skill 注册表唯一真源

服务端 GET /api/v3/ai/brain/skill-registry 与存客宝 BFF 均以此为准。
设备端 Agent _execute_skill(script, action) 须能 getattr(skill, action)。
"""

from __future__ import annotations

from typing import Any, Dict, List

# script → {name, icon, package, modules: {模块名: [action, ...]}}
SKILL_REGISTRY: Dict[str, Dict[str, Any]] = {
    "wechat": {
        "name": "微信",
        "icon": "💬",
        "package": "com.tencent.mm",
        "modules": {
            "消息": [
                "send_message", "get_messages", "forward_message", "recall_message",
                "send_card", "batch_send_message", "send_voice_message", "mass_send",
            ],
            "好友": [
                "add_friend", "accept_friend", "set_remark", "delete_friend",
                "get_contacts", "search_contact", "get_friend_info", "batch_add_friend",
            ],
            "群聊": [
                "create_group", "invite_to_group", "remove_from_group", "set_group_notice",
                "set_group_name", "send_group_message", "set_group_welcome",
                "get_groups", "get_group_members", "quit_group",
            ],
            "标签": [
                "add_tag", "remove_tag", "create_tag", "delete_tag",
                "get_tags", "get_users_by_tag",
            ],
            "朋友圈": [
                "post_moments", "like_moments", "comment_moments", "get_moments",
                "delete_moments", "set_moments_cover", "set_moments_privacy", "forward_moments_link",
            ],
            "个人资料": [
                "get_profile", "set_nickname", "set_signature", "set_avatar",
                "set_gender", "set_region",
            ],
            "账号安全": [
                "check_account_status", "unblock_account", "safety_center", "change_password",
                "unblock_self", "unblock_appeal", "check_restrictions", "appeal_restriction",
                "unblock_with_sms", "unblock_via_customer_service", "check_login_state",
            ],
            "支付": [
                "send_red_packet", "transfer", "show_payment_code", "receive_payment",
                "view_wallet", "view_transactions", "receive_red_packet",
            ],
            "会话管理": ["set_chat_top", "set_mute_chat", "clear_chat_history"],
            "收藏": ["add_to_favorites", "get_favorites"],
            "小程序": ["open_mini_program"],
            "公众号": ["follow_official_account"],
            "视频号": [
                "open_video_channel", "get_video_list", "like_video", "comment_video",
                "follow_video_creator", "share_video",
            ],
            "扫一扫": ["scan_qr_code", "scan_add_friend", "show_my_qr", "extract_qr_from_image"],
            "通话": ["voice_call", "video_call"],
            "搜索发现": ["wechat_search", "top_stories"],
            "微信运动": ["get_steps", "like_steps"],
            "位置表情文件": [
                "send_location", "share_real_time_location", "send_emoji", "get_sticker_list",
                "send_file_from_chat", "download_file",
            ],
            "设置": ["toggle_do_not_disturb", "clear_cache", "check_for_update", "logout", "switch_account"],
        },
    },
    "douyin": {
        "name": "抖音",
        "icon": "🎵",
        "package": "com.ss.android.ugc.aweme",
        "modules": {
            "消息": ["send_message", "get_messages", "batch_send_message"],
            "粉丝互动": [
                "get_fans", "follow_user", "unfollow_user", "search_user",
                "get_comments", "reply_comment", "like_video", "collect_video", "share_video",
            ],
            "联系人": [
                "get_contacts", "add_friend", "accept_friend", "set_remark",
                "delete_friend", "batch_add_friend",
            ],
        },
    },
    "xhs": {
        "name": "小红书",
        "icon": "📕",
        "package": "com.xingin.xhs",
        "modules": {
            "消息": ["send_message", "get_messages", "batch_send_message"],
            "笔记互动": [
                "get_fans", "follow_user", "unfollow_user", "search_user",
                "get_comments", "reply_comment", "like_note", "collect_note",
                "share_note", "search_note", "post_note",
            ],
            "联系人": [
                "get_contacts", "add_friend", "accept_friend", "set_remark",
                "delete_friend", "batch_add_friend",
            ],
        },
    },
    "xianyu": {
        "name": "闲鱼",
        "icon": "🐟",
        "package": "com.taobao.idlefish",
        "modules": {
            "消息": ["send_message", "get_messages", "batch_send_message"],
            "联系人": [
                "get_contacts", "add_friend", "accept_friend", "set_remark",
                "delete_friend", "batch_add_friend", "follow_user", "unfollow_user",
            ],
        },
    },
    "soul": {
        "name": "Soul",
        "icon": "👻",
        "package": "cn.soulapp.android",
        "modules": {
            "消息": ["send_message", "get_messages"],
            "动态": ["post_moments"],
        },
    },
    "system": {
        "name": "系统控制",
        "icon": "⚙️",
        "package": "",
        "modules": {
            "设备操作": [
                "screenshot", "click", "click_text", "input", "swipe",
                "press_key", "ui_tree", "device_info", "status",
            ],
            "应用管理": ["app_start", "app_stop", "current_app", "installed_apps"],
            "网络": ["reconnect_network"],
            "守护": ["dismiss_popups", "connection_guard"],
        },
    },
    "hook": {
        "name": "Hook 引擎",
        "icon": "🪝",
        "package": "",
        "modules": {
            "Frida 消息": ["hook_send_message", "hook_get_messages", "hook_recall_message"],
            "Frida 联系人": ["hook_get_contacts", "hook_get_contact_info", "hook_search_contact"],
            "Frida 群聊": ["hook_get_groups", "hook_get_group_members", "hook_create_group", "hook_invite_to_group"],
            "Frida 朋友圈": ["hook_get_moments", "hook_post_moment", "hook_like_moment"],
            "Frida 标签": ["hook_get_labels", "hook_add_label", "hook_remove_label"],
            "Frida 支付": ["hook_get_transfers", "hook_get_red_packets"],
            "Frida 设备": ["hook_get_device_info", "hook_get_wechat_version"],
            "Frida 数据库": ["hook_query_db", "hook_get_db_tables"],
        },
    },
    "ai_brain": {
        "name": "AI Brain",
        "icon": "🧠",
        "package": "",
        "modules": {
            "决策引擎": ["think", "heartbeat_cycle", "autonomous_loop"],
            "任务管理": ["add_task", "add_standing_order", "flush_offline_buffer"],
            "API调用": ["call_ai", "get_status"],
        },
    },
    "anti_ban": {
        "name": "防封引擎",
        "icon": "🛡️",
        "package": "",
        "modules": {
            "拟人化": ["human_delay", "human_type", "human_click", "human_swipe", "human_browse"],
            "设备守卫": ["device_guard_check", "root_hide_check", "frida_detect_check"],
            "风控哨兵": ["risk_check", "rate_limit", "content_filter"],
            "养号调度": ["nurture_plan", "nurture_execute"],
            "传感器": ["sensor_simulate", "touch_harden"],
        },
    },
}

# 设备端 Agent 可执行的 script（须存在 get_skill(script)）
DEVICE_EXECUTABLE_SCRIPTS = frozenset({"wechat", "douyin", "xhs", "xianyu", "soul"})


def flatten_actions(script: str) -> List[str]:
    """返回某 script 下全部 action 列表"""
    entry = SKILL_REGISTRY.get(script, {})
    modules = entry.get("modules") or {}
    out: List[str] = []
    for actions in modules.values():
        out.extend(actions)
    return out


def registry_summary() -> Dict[str, int]:
    total_skills = len(SKILL_REGISTRY)
    total_modules = sum(len(s.get("modules", {})) for s in SKILL_REGISTRY.values())
    total_actions = sum(len(a) for s in SKILL_REGISTRY.values() for a in s.get("modules", {}).values())
    platform_actions = sum(len(flatten_actions(s)) for s in DEVICE_EXECUTABLE_SCRIPTS if s in SKILL_REGISTRY)
    return {
        "total_skills": total_skills,
        "total_modules": total_modules,
        "total_actions": total_actions,
        "platform_actions": platform_actions,
    }
