#!/usr/bin/env python3
"""Tab Groups 扩展规则优化脚本（可重复执行）
通过 Browser 级 CDP attach 到扩展 SW，写入 chrome.storage.sync
扩展通过 storage.sync.onChanged 热加载规则；存量未分组 tab 由脚本直接调 SW 的 autoGroup 处理

用法:
  python3 tabgroups_rule_sync.py --host=<host>          # 只检查现状
  python3 tabgroups_rule_sync.py --host=<host> --apply  # 写入缺失规则并触发归组

注意: SW 休眠时 attach 会失败，此时脚本自动打开 rules.html 顶起 SW，结束时自动关闭。
      rules.html 页面上下文没有 autoGroup 函数，存量归组需 SW 存活时执行（重跑一次即可）。
"""
import json, os, re, sys, urllib.request
from urllib.parse import urlparse
from websocket import create_connection

EXT_ID = "nplimhmoanghlebhdiboeellhgmgommi"
args = sys.argv[1:]
APPLY = "--apply" in args
HOST = next((a.split("=", 1)[1] for a in args if a.startswith("--host=")), "localhost")

for k in ("HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy","ALL_PROXY","all_proxy"):
    os.environ.pop(k, None)
os.environ["NO_PROXY"] = "localhost,127.0.0.1"

# ============ 规则维护区：以后有新站点/新 rule_id 段，在这里加 ============
CUSTOM_RULES = {
    # --- 规则平台规则页细分 ---
    "rule-biz-p26-533657": {
        "enabled": True, "groupColor": "yellow",
        "groupName": "🧪云查杀 533657", "id": "rule-biz-p26-533657",
        "ruleName": "云查杀 533657 测试",
        "urlMatches": [{"method": "includes", "target": "href", "value": "rule_id=533657"}],
    },
    # 测试平台 533657 之后的新大规则自动归组（533658~533999），兜底防落网
    "rule-biz-zcloud26-inc": {
        "enabled": True, "groupColor": "yellow",
        "groupName": "🧪云查杀 测试", "id": "rule-biz-zcloud26-inc",
        "ruleName": "测试平台新大规则自动归类（533658~533999）",
        "urlMatches": [{"method": "regex", "target": "href",
                        "value": r"rule_id=(53365[7-9]|5336[6-9]\d|533[7-9]\d\d)"}],
    },
    # 正式平台 733130~733999 的新大规则自动归组
    "rule-biz-zcloud64-inc": {
        "enabled": True, "groupColor": "blue",
        "groupName": "云查杀新大规则", "id": "rule-biz-zcloud64-inc",
        "ruleName": "正式平台新大规则自动归类（733130~733999）",
        "urlMatches": [{"method": "regex", "target": "href",
                        "value": r"rule_id=(733(1[3-9]\d|[2-9]\d\d))"}],
    },
    # --- 内部站点 ---
    "rule-new-wisgit": {
        "enabled": True, "groupColor": "blue",
        "groupName": "👀代码仓库", "id": "rule-new-wisgit",
        "ruleName": "WisGit 内部 Git",
        "urlMatches": [{"method": "includes", "target": "hostname", "value": "git.example-corp.com"}],
    },
    "rule-new-threat-intel": {
        "enabled": True, "groupColor": "green",
        "groupName": "🔬安全/逆向", "id": "rule-new-threat-intel",
        "ruleName": "威胁情报/测绘",
        "urlMatches": [
            {"method": "includes", "target": "hostname", "value": "fofa.info"},
            {"method": "includes", "target": "hostname", "value": "intel.example.com"},
            {"method": "includes", "target": "hostname", "value": "hunter.example.com"},
        ],
    },
    "rule-new-intranet": {
        "enabled": True, "groupColor": "orange",
        "groupName": "🤺公司工作", "id": "rule-new-intranet",
        "ruleName": "公司内部系统（培训/审计/运维监控）",
        "urlMatches": [
            {"method": "includes", "target": "hostname", "value": "learn.example-corp.com"},
            {"method": "includes", "target": "hostname", "value": "audit.example-corp.com"},
            {"method": "includes", "target": "hostname", "value": "ops.example-corp.com"},
        ],
    },
}

# ============ CDP 连接 ============
def connect_ext():
    ver = json.loads(urllib.request.urlopen(f"http://{HOST}:9222/json/version").read())
    ws = create_connection(ver["webSocketDebuggerUrl"], timeout=20, http_no_proxy=True, http_proxy_host=None)
    n = [1]
    def rpc(method, params=None, session=None):
        i = n[0]; n[0] += 1
        msg = {"id": i, "method": method, "params": params or {}}
        if session: msg["sessionId"] = session
        ws.send(json.dumps(msg))
        while True:
            m = json.loads(ws.recv())
            if m.get("id") == i: return m
    r = rpc("Target.getTargets", {}, None)
    infos = r["result"]["targetInfos"]
    sw_tid = next((t["targetId"] for t in infos
                   if t["type"] == "service_worker" and EXT_ID in t["url"]), None)
    page_tid = None
    if sw_tid:
        tid, is_sw = sw_tid, True
    else:
        # SW 休眠：打开扩展页面顶起 SW（页面上下文无 autoGroup，只能读写 storage）
        r = rpc("Target.createTarget", {"url": f"chrome-extension://{EXT_ID}/rules.html"}, None)
        page_tid = r["result"]["targetId"]
        import time; time.sleep(1.5)  # 等 SW 被 top 起来
        r = rpc("Target.getTargets", {}, None)
        sw_tid = next((t["targetId"] for t in r["result"]["targetInfos"]
                       if t["type"] == "service_worker" and EXT_ID in t["url"]), None)
        if sw_tid:
            tid, is_sw = sw_tid, True
        else:
            tid, is_sw = page_tid, False
    r = rpc("Target.attachToTarget", {"targetId": tid, "flatten": True}, None)
    sid = r["result"]["sessionId"]
    return ws, rpc, sid, page_tid, is_sw

def eval_json(rpc, sid, expr):
    r = rpc("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True}, sid)
    res = r.get("result", {})
    if res.get("subtype") == "error":
        raise RuntimeError(res.get("exceptionDetails", {}).get("exception", {}).get("description", "")[:300])
    val = res.get("result", {}).get("value")
    try: return json.loads(val)
    except (json.JSONDecodeError, TypeError): return val

def match_cond(c, url):
    m, t, v = c.get("method"), c.get("target"), c.get("value", "")
    hay = urlparse(url).netloc if t == "hostname" else url
    if m == "includes": return v in hay
    if m == "regex":
        try: return bool(re.search(v, hay))
        except: return False
    return False

def match_rule(r, url):
    return any(match_cond(c, url) for c in r.get("urlMatches", []))

def main():
    ws, rpc, sid, page_tid, is_sw = connect_ext()
    try:
        rules = eval_json(rpc, sid, """
            new Promise(res => chrome.storage.sync.get(null, all => {
                const o = {};
                for (const [k, v] of Object.entries(all)) if (k.startsWith('rule-')) o[k] = v;
                res(JSON.stringify(o));
            }))""")
        tabs = eval_json(rpc, sid, """
            new Promise(res => chrome.tabs.query({}, ts => res(JSON.stringify(ts.map(t => ({
                id: t.id, url: t.url || '', groupId: t.groupId, pinned: t.pinned
            }))))))""")

        enabled = [r for r in rules.values() if r.get("enabled", True)]
        ungrouped = [t for t in tabs if t["groupId"] == -1 and not t["pinned"]
                     and not t["url"].startswith(("edge://", "chrome://", "chrome-extension://"))]
        missing = [t for t in ungrouped if not any(match_rule(r, t["url"]) for r in enabled)]

        print(f"规则总数: {len(rules)}, 未分组 tab: {len(ungrouped)}, 规则未覆盖: {len(missing)}")
        for t in missing:
            print(f"  ⬜ {t['url'][:90]}")

        to_add = {k: v for k, v in CUSTOM_RULES.items() if k not in rules}
        if to_add:
            print(f"\n待写入规则: {len(to_add)}")
            for k, v in to_add.items(): print(f"  + {k} -> {v['groupName']}")
        else:
            print("\n自定义规则已全部在库")

        if APPLY and to_add:
            r = eval_json(rpc, sid, """
                new Promise((resolve, reject) => {
                    chrome.storage.sync.set(%s, () => {
                        if (chrome.runtime.lastError) reject(chrome.runtime.lastError.message);
                        else resolve('OK');
                    });
                })""" % json.dumps(to_add))
            print("写入结果:", r)

        # 存量未分组 tab 归组：只有 SW 上下文有 autoGroup
        if APPLY and is_sw:
            r = eval_json(rpc, sid, """
                new Promise((resolve, reject) => {
                    if (typeof autoGroup !== 'function') { resolve('SKIP'); return; }
                    chrome.tabs.query({}, ts => {
                        const pending = ts.filter(t => !t.pinned &&
                            t.groupId === chrome.tabGroups.TAB_GROUP_ID_NONE &&
                            t.url && !t.url.startsWith('edge://'));
                        for (const t of pending) autoGroup(t.url, true, t);
                        resolve(JSON.stringify(pending.length));
                    });
                })""")
            print("触发归组 tab 数:", r)
        elif APPLY and not is_sw:
            print("⚠ SW 未能唤醒，存量 tab 未归组；新 tab 不受影响，或稍后重跑 --apply")
    finally:
        if page_tid:
            try:
                rpc("Target.closeTarget", {"targetId": page_tid}, None)
                print("(已关闭临时 rules.html)")
            except Exception:
                pass
        ws.close()

if __name__ == "__main__":
    main()
