"""Which raced cells launch the SIZED arm on a card (ag_mma_plan and ag_mma_sized_splits mirrored for the report), and
the MMA arm's B/A per chain on exactly those; every other cell runs machine code identical to the base's.
usage: sized_cells.py DIR TAG_A TAG_B N_SMS"""
import glob, json, statistics, sys
D, TA, TB, SMS = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4])
def plan(K, N):
    blocks, bands = K // 128, (N + 127) // 128
    want = 2 * SMS; splits = (want + bands - 1) // bands
    if splits <= 1: kc = K
    else:
        wb = (blocks + splits - 1) // splits; b = 1
        while 2 * b <= wb and 2 * b * 128 <= 512: b *= 2
        kc = b * 128
    kc = min(kc, K); splits = (K + kc - 1) // kc
    slots = 4 * SMS
    if splits == 1 and bands < slots:
        best = -1; prev = 0
        for w in range(1, blocks + 1):
            per = (blocks + w - 1) // w; sp = (blocks + per - 1) // per
            if sp == prev: continue
            prev = sp
            cost = ((bands * sp + slots - 1) // slots) * (per + 1)
            if best < 0 or cost < best: best, kc, splits = cost, per * 128, sp
    return splits
sized = lambda s: s > 1 and (s <= 8 or 12 < s <= 16)
rows = {}
for model in ("27b", "df", "flint"):
    for t in (TA, TB):
        for f in sorted(glob.glob(f"{D}/race_{model}_{t}_c*.json")):
            for r in json.load(open(f)):
                if r["kind"] == "cell": key, N, arm = (model, f'{r["in_f"]}x{r["out_f"]}', r["M"]), r["out_f"], "mma"
                else: key, N, arm = (model, f'{r["in_f"]}x' + "+".join(map(str, r["widths"])), r["M"]), sum(r["widths"]), "mma_group"
                if arm in r["us"]: rows.setdefault(key, {"splits": plan(r["in_f"], N)}).setdefault(t, []).append(r["us"][arm])
n_s = n_p = 0; worst = []
for key, v in rows.items():
    if TA not in v or TB not in v: continue
    if not sized(v["splits"]) or key[2] > 64: n_p += 1; continue
    n_s += 1
    a, b = statistics.median(v[TA]), statistics.median(v[TB])
    allslower = all(y > x for x, y in zip(v[TA], v[TB]))
    worst.append((b / a - 1, key, v["splits"], [round(x, 2) for x in v[TA]], [round(x, 2) for x in v[TB]], allslower))
worst.sort(reverse=True)
print(f"SMs {SMS}: {n_s} (cell, rows) on the SIZED arm, {n_p} on plain arms")
print("sized, B/A-1: median %.2f%%, min %.2f%%, max %.2f%%" % tuple(100 * x for x in (statistics.median(w[0] for w in worst), worst[-1][0], worst[0][0])))
print("slower on all three chains by more than 0.5%:")
for w in worst:
    if w[0] > 0.005 and w[5]: print("  ", w[1], "splits", w[2], f"{100*w[0]:+.2f}%", w[3], "->", w[4])
print("largest:"); [print("  ", w[1], "splits", w[2], f"{100*w[0]:+.2f}%", w[3], "->", w[4], "all-chains-slower" if w[5] else "") for w in worst[:5]]
