"""
Solution: the review testbed in code. Lab 01's bookkeeping (review_prs.py, answer_key.py,
01_tour.py): size buckets, the planted batch-size cap from c20-d1, families of changes, the
corpus table, scoring a reviewer against the answer key, and the answer key's checks on one PR.
"""


def size_bucket(changed_lines):
    """Harbor's size buckets, scaled to a 2,000-line app. Tests count: size is what a reviewer reads.
    XS under 30 changed lines, S 30-79, M 80-199, L 200 and up."""
    if changed_lines < 30:
        return "XS"
    if changed_lines < 80:
        return "S"
    if changed_lines < 200:
        return "M"
    return "L"


def send_sizes(n_records, batch_size, default, capped=False):
    """The batch sizes send() uses for n_records records.
    Clean (c20-clean): size = batch_size if it's set (not None), else the destination's default.
    Buggy (c20-d1, capped=True): size = min(batch_size, default) if it's set, else the default.
    Records go out in order: full batches of `size`, then whatever is left."""
    if batch_size:
        size = min(batch_size, default) if capped else batch_size
    else:
        size = default
    return [min(size, n_records - start) for start in range(0, n_records, size)]


def families(changes):
    """Group changes that share a source task, directly or through other changes.
    changes: {change_id: [task ids]}. A change with no tasks is a family of its own.
    Return a list of sets of change ids."""
    parent = {}

    def find(x):
        parent.setdefault(x, x)
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for change, tasks in changes.items():
        find(("change", change))
        for task in tasks:
            parent[find(("task", task))] = find(("change", change))
    groups = {}
    for change in changes:
        groups.setdefault(find(("change", change)), set()).add(change)
    return list(groups.values())


def corpus_table(prs):
    """prs: [(change, clean, changed_lines, test_lines), ...].
    Return {bucket: [clean PRs, buggy PRs]} for XS, S, M and L."""
    table = {b: [0, 0] for b in ("XS", "S", "M", "L")}
    for _, clean, size, _ in prs:
        table[size_bucket(size)][0 if clean else 1] += 1
    return table


def share_of_test_lines(prs):
    """The share of all changed lines, across every PR, that are test lines."""
    return sum(p[3] for p in prs) / sum(p[2] for p in prs)


def score(flagged, buggy):
    """Score a reviewer against the answer key.
    flagged: set of PR ids the reviewer commented on (here, a comment on a buggy PR means it found the bug).
    buggy: {pr_id: True if it has a planted bug, False if clean}.
    Return (recall, clean_flagged): the share of buggy PRs flagged, and the share of clean PRs flagged."""
    bugs = [p for p, b in buggy.items() if b]
    clean = [p for p, b in buggy.items() if not b]
    recall = sum(p in flagged for p in bugs) / len(bugs)
    clean_flagged = sum(p in flagged for p in clean) / len(clean) if clean else 0.0
    return recall, clean_flagged


def answer_key_problems(variant, own_oracles, diff_lines):
    """Which of the per-PR checks fail for one variant (shaped like an entry of results/fairness.json)?
    variant: {"clean": bool, "ci": {check: passed}, "oracles": {file: passed}, "lines": {file: [line numbers]}}.
    own_oracles: the oracle files written for this variant's defect (empty for a clean PR).
    diff_lines: {file: [line numbers the PR adds or changes]}.
    Return a list with any of, in this order:
      "ci"        - some CI check failed
      "oracles"   - clean: some oracle failed; buggy: none of its own oracles failed
      "in_diff"   - buggy: some defect line isn't among the PR's changed lines"""
    problems = []
    if not all(variant["ci"].values()):
        problems.append("ci")
    if variant["clean"]:
        if not all(variant["oracles"].values()):
            problems.append("oracles")
    else:
        if all(variant["oracles"][o] for o in own_oracles):
            problems.append("oracles")
        for file, lines in variant["lines"].items():
            if not set(lines) <= set(diff_lines.get(file, [])):
                problems.append("in_diff")
                break
    return problems
