"""
Practice: score a code reviewer the way Lab 02 does (matching.py, scoring.py, stats.py). You'll
write step 1 of the match, recall and the false-alarm rate, a Wilson interval for a share, and the
run-to-run check that showed how noisy a cheap reviewer is.

Every reviewer in the lab is the stand-in, an AI model; the tests use its recorded numbers.

Fill in the TODOs, then run the tests:
    pytest test_scoring_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import math

WINDOW = 3


def points_at(file, line, bug_lines, window=WINDOW):
    """Step 1 of the match: does a comment at (file, line) point at the bug?

    bug_lines maps a file path to the bug's line numbers in it. A comment points at the bug when it is
    in one of those files and within `window` lines of one of the bug's lines in that file. A comment
    with no line (line is None) covers its whole file; one with no file (file is None) covers every file.
    """
    if file is None:
        return True
    if file not in bug_lines:
        return False
    if line is None or not bug_lines[file]:
        return True
    return any(abs(line - n) <= window for n in bug_lines[file])


def scorecard(prs):
    """Recall and false-alarm rate over a list of scored PRs.

    Each PR is a dict: {"clean": bool, "found": bool, "unmatched_bugs": int}. "found" means a comment
    passed both steps for the PR's planted bug; "unmatched_bugs" counts `bug` comments that matched
    nothing on the answer key.
    Return {"recall": found buggy PRs / buggy PRs,
            "false_alarms": clean PRs with at least one unmatched bug comment / clean PRs}.
    """
    buggy = [p for p in prs if not p["clean"]]
    clean = [p for p in prs if p["clean"]]
    return {
        "recall": sum(p["found"] for p in buggy) / len(buggy),
        "false_alarms": sum(p["unmatched_bugs"] > 0 for p in clean) / len(clean),
    }


def wilson(k, n, z=1.96):
    """95% Wilson interval (low, high) for k successes out of n, as fractions between 0 and 1.

    With p = k / n:  centre = (p + z²/2n) / (1 + z²/n)
                     half   = z · sqrt(p(1 - p)/n + z²/4n²) / (1 + z²/n)
    Return (centre - half, centre + half), kept inside [0, 1]. For n == 0 return (0.0, 1.0)."""
    if n == 0:
        return (0.0, 1.0)
    p = k / n
    denom = 1 + z**2 / n
    centre = (p + z**2 / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
    return (max(0.0, centre - half), min(1.0, centre + half))


def flips(runs):
    """runs: one string per PR, one character per run: "1" if that run wrote at least one bug comment
    on the PR, "0" if it wrote none (e.g. "101"). Return how many PRs the runs disagree on."""
    return sum(len(set(r)) > 1 for r in runs)
