"""Benchmark every get_tracks backend on scored muon-collider graphs: physics and time.

    python muon_collider_segmentation_benchmark.py <scored dir>/valset -o out_dir -j 64
    python muon_collider_segmentation_benchmark.py --report out_dir   # table from out_dir/raw.pkl

Per event and backend: get_tracks wall time (1 thread, loading and evaluation excluded),
then acorn matching (ATLAS and two_way, 50%, min 5 hits) with and without a common
post-filter: mean score of the track's internal edges above 0.01 >= Q, and >= L hits.
Counts follow segmentation/scan.py, dropping the BIB "particle 0".
A backend that runs past --timeout on an event is recorded as timed out.
"""
import argparse, glob, os, pickle, signal, time
from multiprocessing import Pool

import numpy as np
import torch

CONFIGS = {  # name: (backend, cuts)
    "cc": ("cc", dict(cc_cut=0.01)),
    "cc@0.5": ("cc", dict(cc_cut=0.5)),
    "cc@0.9": ("cc", dict(cc_cut=0.9)),
    "cc_walk": ("cc_walk", dict(cc_cut=0.01, walk_min=0.3, walk_add=0.8)),
    "cc_score_guided_walk": ("cc_score_guided_walk",
                             dict(cc_cut=0.01, walk_min=0.3, walk_add=0.8, guidance_mode=2)),
    "cc_bestpred_walk": ("cc_bestpred_walk", dict(cc_cut=0.01, walk_min=0.3, walk_add=0.8)),
    "cc_junction_removal": ("cc_junction_removal",
                            dict(cc_cut=0.7, min_chain_length=3, junction_cut=0.5)),
}
Q, L, Q_EDGE = 0.5, 7, 0.01


def post_filter(g, trks):
    idx = {h: i for i, h in enumerate(g.hit_id.tolist())}
    label = np.full(g.hit_id.shape[0], -1)
    flat = [(m, t) for m, ts in trks.items() for t in ts]
    for i, (_, t) in enumerate(flat):
        label[[idx[h] for h in t]] = i
    src, dst = g.edge_index.numpy()
    s = g.edge_scores.float().numpy()
    k = (s > Q_EDGE) & (label[src] >= 0) & (label[src] == label[dst])
    tot = np.bincount(label[src][k], s[k], len(flat))
    cnt = np.bincount(label[src][k], minlength=len(flat))
    mean = np.divide(tot, cnt, out=np.zeros(len(flat)), where=cnt > 0)
    out = {m: [] for m in trks}
    for (m, t), q in zip(flat, mean):
        if len(t) >= L and q >= Q:
            out[m].append(t)
    return out


def counts(g, trks, style):
    from acorn.stages.track_building import utils as tbu
    from acorn.stages.track_building.models.cc_and_walk_utils import add_track_labels

    g = g.clone()
    add_track_labels(g, trks)
    d = tbu.evaluate_labelled_graph(g, sel_conf={"pt": [0, float("inf")]}, matching_fraction=0.5,
                                    matching_style=style, min_track_length=5)
    real = d[d.particle_id != 0]
    parts = real[real.is_reconstructable]
    reco = parts[(parts.track_id != -1) & parts.is_reconstructed & parts.is_matchable]
    trk = d[(d.track_id != -1) & d.is_matchable]
    mt = real[(real.track_id != -1) & real.is_matched & real.is_matchable]
    return np.array([len(parts.drop_duplicates(["event_id", "particle_id"])),
                     len(reco.drop_duplicates(["event_id", "particle_id"])), len(reco),
                     len(trk.drop_duplicates(["event_id", "track_id"])),
                     len(mt.drop_duplicates(["event_id", "track_id"]))])


def _alarm(*_):
    raise TimeoutError


def run_event(args):
    f, timeout = args
    torch.set_num_threads(1)
    from acorn.stages.track_building.segmentation import get_tracks
    from acorn.utils.loading_utils import add_variable_name_prefix_in_pyg, load_pyg

    g0 = add_variable_name_prefix_in_pyg(load_pyg(f.removesuffix(".gz"), weights_only=False))
    g0.edge_scores = g0.edge_scores.float()
    signal.signal(signal.SIGALRM, _alarm)
    out = {"event": os.path.basename(f), "n_hits": g0.hit_id.shape[0], "n_edges": g0.edge_index.shape[1]}
    for name, (backend, cuts) in CONFIGS.items():
        g = g0.clone()
        signal.alarm(timeout)
        try:
            t0 = time.perf_counter()
            trks = get_tracks(g, backend, **cuts)
            dt = time.perf_counter() - t0
        except TimeoutError:
            out[name] = None
            continue
        finally:
            signal.alarm(0)
        res = {"time": dt}
        for tag, t in [("raw", trks), ("filt", post_filter(g, trks))]:
            res[tag] = np.concatenate([counts(g, t, "ATLAS"), counts(g, t, "two_way")])
        out[name] = res
    return out


def report(rows, fh):
    ok = [r for r in rows if all(r[n] is not None for n in CONFIGS)]
    p = lambda *a: print(*a, file=fh)
    p(f"{len(rows)} events; {len(ok)} where every backend finished (physics uses those)")
    p(f"filter: mean internal edge score (edges > {Q_EDGE}) >= {Q}, >= {L} hits\n")
    p(f"{'backend':22s} {'filter':6s} {'eff':>6s} {'fake':>6s} {'dup':>6s} {'eff2way':>7s} "
      f"{'trk/evt':>7s} | {'t_mean':>7s} {'t_med':>7s} {'t_p99':>7s} {'t_max':>7s} {'timeouts':>8s}")
    for n, (backend, cuts) in CONFIGS.items():
        t = np.array([r[n]["time"] for r in rows if r[n] is not None])
        nto = sum(r[n] is None for r in rows)
        for tag in ["raw", "filt"]:
            c = sum(r[n][tag] for r in ok)
            eff, fake = c[1] / c[0], 1 - c[4] / c[3]
            dup, eff2 = (c[2] - c[1]) / c[1], c[6] / c[5]
            tm = (f"{t.mean():7.3f} {np.median(t):7.3f} {np.percentile(t, 99):7.3f} "
                  f"{t.max():7.1f} {nto:8d}") if tag == "raw" else ""
            p(f"{n:22s} {tag:6s} {eff:6.3f} {fake:6.3f} {dup:6.3f} {eff2:7.3f} "
              f"{c[3] / len(ok):7.2f} | {tm}")
    p("\ncuts: " + "; ".join(f"{n} {c}" for n, (_, c) in CONFIGS.items()))
    p("time = get_tracks wall seconds per event, 1 thread, loading and matching excluded")


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("input_dir", nargs="?")
    ap.add_argument("-o", "--out", required=False)
    ap.add_argument("-n", type=int, default=None)
    ap.add_argument("-j", type=int, default=32)
    ap.add_argument("--timeout", type=int, default=600, help="seconds per backend per event")
    ap.add_argument("--report", help="print the table from <dir>/raw.pkl")
    a = ap.parse_args()
    if a.report:
        report(pickle.load(open(f"{a.report}/raw.pkl", "rb")), None)
        raise SystemExit
    os.makedirs(a.out, exist_ok=True)
    files = sorted(glob.glob(f"{a.input_dir}/*.pyg*"))[: a.n]
    rows = []
    with Pool(a.j, maxtasksperchild=20) as pool:
        for i, r in enumerate(pool.imap_unordered(run_event, [(f, a.timeout) for f in files])):
            rows.append(r)
            if i % 50 == 0:
                print(f"{i + 1}/{len(files)}", flush=True)
                pickle.dump(rows, open(f"{a.out}/raw.pkl", "wb"))
    pickle.dump(rows, open(f"{a.out}/raw.pkl", "wb"))
    with open(f"{a.out}/table.txt", "w") as fh:
        report(rows, fh)
    print(open(f"{a.out}/table.txt").read())
