#!/usr/bin/env python3
"""Aggregates the mutant study into out/mutants.json."""
import json, os, re, sys
R = sys.argv[1]
sys.path.insert(0, R)
from mutants import MUTANTS  # noqa: E402

ZONES = ["UTC", "America/New_York", "Europe/London", "Australia/Lord_Howe", "America/Santiago", "Asia/Kuala_Lumpur"]
rows = []
for mid, plat, kind, old, new, desc in MUTANTS:
    W = os.path.join(R, "mut", mid)
    c = open(os.path.join(W, "contract.txt")).read()
    exitcode = int(re.search(r"exit=(\d+)", c).group(1))
    m = re.findall(r"\+(\d+)(?: -(\d+))?: ", c)
    passed, failed = (int(m[-1][0]), int(m[-1][1] or 0)) if m else (None, None)
    changed = 0; total = 0; missing = []
    for z in ZONES:
        f = z.replace("/", "_")
        p = os.path.join(W, f"{plat}_{f}.json")
        if not os.path.exists(p): missing.append(z); continue
        a = json.load(open(p)); b = json.load(open(os.path.join(R, "out", f"{plat}_{f}.json")))
        for key in ("instant", "shown"):
            for x, y in zip(a[key], b[key]):
                total += len(x); changed += sum(1 for u, v in zip(x, y) if u != v)
    rows.append({"id": mid, "platform": plat, "kind": kind, "description": desc, "old": old, "new": new,
                 "contractExit": exitcode, "contractPassed": passed, "contractFailed": failed,
                 "contractKilled": exitcode != 0, "answersChanged": changed, "answersCompared": total,
                 "differentialKilled": changed > 0, "missingZones": missing})
beh = [r for r in rows if r["kind"] == "behaviour"]; ref = [r for r in rows if r["kind"] == "refactor"]
out = {"zones": ZONES, "mutants": rows, "behaviourCount": len(beh), "refactorCount": len(ref),
       "contractBehaviourKilled": sum(r["contractKilled"] for r in beh), "differentialBehaviourKilled": sum(r["differentialKilled"] for r in beh),
       "contractRefactorKilled": sum(r["contractKilled"] for r in ref), "differentialRefactorKilled": sum(r["differentialKilled"] for r in ref)}
json.dump(out, open(os.path.join(R, "out", "mutants.json"), "w"), indent=1)
for r in rows: print(r["id"], r["kind"], "contract", r["contractPassed"], "pass", r["contractFailed"], "fail", "| diff changed", r["answersChanged"], "/", r["answersCompared"], r["missingZones"])
print({k: v for k, v in out.items() if k not in ("mutants", "zones")})
