"""Inclusive share of non-idle samples under frames matching each pattern in a .cpuprofile."""
import json
import sys

prof = json.load(open(sys.argv[1]))
prof = prof.get("profile", prof)
nodes = {n["id"]: n for n in prof["nodes"]}
parent = {}
for n in prof["nodes"]:
    for c in n.get("children", []):
        parent[c] = n["id"]

def label(n):
    cf = n["callFrame"]
    return f'{cf["functionName"]} {cf["url"]}'

patterns = sys.argv[2:]
total = 0
hits = {p: 0 for p in patterns}
for sid in prof["samples"]:
    if nodes[sid]["callFrame"]["functionName"] == "(idle)":
        continue
    total += 1
    chain = []
    cur = sid
    while cur is not None:
        chain.append(label(nodes[cur]))
        cur = parent.get(cur)
    for p in patterns:
        if any(p in c for c in chain):
            hits[p] += 1
print(f"non-idle samples: {total}")
for p in patterns:
    print(f"{100 * hits[p] / total:5.1f}%  {p}")
