"""Three ways to load push events whose payload shape changed over the years, scored on GH Archive samples.

Input: the files written by tools/gharchive_sample.py (one line per push event: its keys, value types and commit
counts). Right means the loaded commit count equals the payload's own `size`.

- strict: the newest shape is required (top-level id and repo, payload commits list and push_id); other rows rejected.
- lenient: every row loads; missing fields become null; commit count = length of the payload's commits list.
- versioned contract: known shapes are mapped (repository to repo, shas to commits), the commit count is the payload's
  size, unknown keys are audited, and a row of no known shape is quarantined.

Usage: python3 -I -B tools/drift.py <samples folder> <out json>
"""
import glob
import gzip
import json
import os
import sys
from collections import Counter

SHAPES = {
    "2012 timeline": {"top": {"repository"}, "payload": {"head", "ref", "shas", "size"}},
    "2015 events": {"top": {"id", "repo"}, "payload": {"before", "commits", "distinct_size", "head", "push_id", "ref", "size"}},
}
KNOWN_PAYLOAD = set().union(*(s["payload"] for s in SHAPES.values()))


def strict(r):
    if not r["id"] or "repo" not in r["top"] or "commits" not in r["payload"] or "push_id" not in r["payload"]:
        return "rejected", None
    return "loaded", r["list_len"].get("commits")


def lenient(r):
    return "loaded", r["list_len"].get("commits")


def versioned(r):
    keys, top = set(r["payload"]), set(r["top"])
    for name, s in SHAPES.items():
        if s["top"] <= top and s["payload"] <= keys:
            return "loaded", r["counts"].get("size"), name, sorted(keys - KNOWN_PAYLOAD)
    return "quarantined", None, None, sorted(keys - KNOWN_PAYLOAD)


def main():
    folder, out = sys.argv[1], sys.argv[2]
    res = {"by_hour": {}, "totals": {}}
    tot = {n: Counter() for n in ("strict", "lenient", "versioned")}
    for p in sorted(glob.glob(os.path.join(folder, "*.jsonl.gz"))):
        hour = os.path.basename(p)[:-9]
        with gzip.open(p, "rt", encoding="utf-8") as f:
            rows = [json.loads(line) for line in f]
        h = {n: Counter() for n in tot}
        shapes, extra = Counter(), Counter()
        for r in rows:
            size = r["counts"].get("size")
            for name, fn in (("strict", strict), ("lenient", lenient)):
                status, n = fn(r)
                if status != "loaded":
                    h[name][status] += 1
                elif n == size:
                    h[name]["right"] += 1
                elif n is None:
                    h[name]["silently_null"] += 1
                else:
                    h[name]["silently_wrong"] += 1
            status, n, shape, unknown = versioned(r)
            shapes[shape or "none"] += 1
            for k in unknown:
                extra[k] += 1
            if status != "loaded":
                h["versioned"][status] += 1
            elif n == size:
                h["versioned"]["right"] += 1
            else:
                h["versioned"]["silently_wrong"] += 1
        for n in tot:
            tot[n].update(h[n])
        res["by_hour"][hour] = {"events": len(rows), "shapes": dict(shapes), "unknown_payload_keys": dict(extra),
                                "has_event_id": sum(r["id"] for r in rows),
                                "commits_list_shorter_than_size": sum(1 for r in rows if "commits" in r["list_len"]
                                                                      and r["list_len"]["commits"] != r["counts"].get("size")),
                                **{n: dict(h[n]) for n in tot}}
    res["totals"] = {n: dict(tot[n]) for n in tot}
    res["events"] = sum(v["events"] for v in res["by_hour"].values())
    with open(out, "w", encoding="utf-8") as f:
        json.dump(res, f, indent=1, sort_keys=True)
        f.write("\n")
    print(json.dumps(res["totals"]))


if __name__ == "__main__":
    main()
