"""
Practice: check each AI finding before a person reads it. Lab 04's arithmetic (filtering.py,
proof.py): how often a check drops right and wrong findings, what a policy lets through
(precision, recall, noise per PR), an indentation-tolerant match for a proof's fix, and when a
proof counts.

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

# A finding is a dict: {"pr": "n33-d1", "truth": "defect" | "known" | "none",
#                       "refute": verdict, "reproduce": verdict, "reproduce_v1": verdict}
# where each verdict is "confirmed", "refuted" or "unsure". "Right" means truth != "none".

POLICIES = ("everything", "not refuted", "proven", "proven or unsure", "proven or confirmed",
            "proven, first harness")


def kept(finding, policy):
    """Does `policy` let this finding through to the person?
    - everything: always
    - not refuted: refute isn't "refuted"
    - proven: reproduce is "confirmed"
    - proven or unsure: reproduce isn't "refuted"
    - proven or confirmed: refute or reproduce is "confirmed"
    - proven, first harness: reproduce_v1 is "confirmed"
    """
    if policy == "everything":
        return True
    if policy == "not refuted":
        return finding["refute"] != "refuted"
    if policy == "proven":
        return finding["reproduce"] == "confirmed"
    if policy == "proven or unsure":
        return finding["reproduce"] != "refuted"
    if policy == "proven or confirmed":
        return "confirmed" in (finding["refute"], finding["reproduce"])
    if policy == "proven, first harness":
        return finding["reproduce_v1"] == "confirmed"
    raise ValueError(policy)


def drop_rates(findings, policy):
    """A check is a classifier of findings. Return (right dropped, right total, none dropped,
    none total): how many right findings (defect or known) and how many that match nothing
    the policy drops."""
    right = [f for f in findings if f["truth"] != "none"]
    none = [f for f in findings if f["truth"] == "none"]
    return (sum(not kept(f, policy) for f in right), len(right),
            sum(not kept(f, policy) for f in none), len(none))


def outcome(findings, policy, buggy_prs, n_prs):
    """What reaches the person under `policy`. Return a dict with:
    - kept: findings kept
    - precision: kept right findings / kept findings
    - recall: buggy PRs (from buggy_prs) with at least one kept "defect" finding
    - noise_per_pr: kept findings that match nothing / n_prs
    - dropped_true: right findings dropped
    """
    k = [f for f in findings if kept(f, policy)]
    hit = {f["pr"] for f in k if f["truth"] == "defect"} & set(buggy_prs)
    return {
        "kept": len(k),
        "precision": sum(f["truth"] != "none" for f in k) / len(k) if k else 0.0,
        "recall": len(hit),
        "noise_per_pr": sum(f["truth"] == "none" for f in k) / n_prs,
        "dropped_true": sum(f["truth"] != "none" and not kept(f, policy) for f in findings),
    }


def count_matches(text, find):
    """How many places a fix edit's `find` text matches in a file's `text`.
    Exact matches count first. If there are none, compare line by line ignoring each line's
    leading and trailing whitespace (blank lines in `find` are skipped): a model often copies
    a line with the wrong indentation. An edit is accepted only when this returns 1."""
    exact, start = 0, 0
    while find and (i := text.find(find, start)) != -1:
        exact += 1
        start = i + 1
    if exact:
        return exact
    want = [ln.strip() for ln in find.splitlines() if ln.strip()]
    if not want:
        return 0
    lines = [ln.strip() for ln in text.splitlines()]
    return sum(lines[i:i + len(want)] == want for i in range(len(lines) - len(want) + 1))


def judge_proof(on_pr, with_fix, on_clean=None):
    """Each run's outcome is "passed", "failed" (a test assertion failed) or "error" (the test
    couldn't load or run). Return:
    - "proven": fails on the PR and passes with the fix (and, if on_clean is given, passes on
      the clean twin: the same change without the planted bug)
    - "wrong reason": proven, but also fails or errors on the clean twin
    - "not proven": anything else (passes on the PR, an error instead of a failure, or still
      failing with the fix)
    """
    if not (on_pr == "failed" and with_fix == "passed"):
        return "not proven"
    if on_clean is not None and on_clean != "passed":
        return "wrong reason"
    return "proven"
