"""Tests on Lab 04's recorded run (October 2026, gpt-5.4-mini at low effort for both checks): the
106 bug findings of Lab 03's agentic reviewer (runs 1-3) on 40 PRs, each with its truth from the
answer key and the verdicts of refute, reproduce, and the first reproduce harness.
Run: pytest test_checks_practice.py"""
from checks_practice import count_matches, drop_rates, judge_proof, kept, outcome

# One finding per entry: the PR, then four letters. Truth: D defect (describes the planted bug),
# K known issue, N matches nothing. Then refute, reproduce, first harness: C confirmed, R refuted,
# U unsure.
RECORDED = """
    n36-d2 NCCU             n36-d2 DCCC             n36-d2 DRCC             n36-d2 NCCU
    n36-d2 KCCU             n36-d2 DCCC             c18-d2 DCCC             c18-d2 DCCU
    c18-d2 DCCC             n17-d2 DCCC             n17-d2 KCCU             n17-d2 KCCC
    n17-d2 DCCC             n17-d2 KCUC             n17-d2 DCCC             n13-clean NCCC
    n13-clean NRCU          n22-d1 DCCC             n22-d1 DCCC             n22-d1 DCCC
    n05-d2 DCCC             n05-d2 NCCU             n05-d2 DCCC             n05-d2 DCCC
    n27-d2 DCCU             n27-d2 DCCC             n27-d2 DCCC             n11-clean NCCC
    n11-clean NCCC          n32-d4 DCCU             n32-d4 DCCC             n32-d4 DCCU
    worker-release-d2 DCCC  worker-release-d2 DCCC  worker-release-d2 DCCC  n31-d3 DCCC
    n31-d3 DCCC             n31-d3 DCCC             c38-d2 DCCC             c38-d2 DCCC
    c38-d2 DCCC             n26-d2 NRCC             c20-d2 DCCC             c20-d2 NCUU
    c20-d2 DCCC             n33-d1 DCCC             n33-d1 DCCC             n33-d1 DRCC
    n29-d3 NCCU             n29-d3 NCCU             n29-d3 NCCU             c23-clean KCCC
    c23-clean NCCC          c23-clean NCCC          c23-clean KCCC          n02-d2 NCUU
    n02-d2 NRCU             n02-d2 DCCC             n09-d2 DCCU             n09-d2 DCCU
    n09-d2 NRCU             c02-d1 DCCU             c02-d1 DCCU             c02-d1 DCCU
    c28-d1 DCUC             c28-d1 NCUC             c28-d1 DCCC             n15-clean NCCC
    n15-clean NCUR          n15-clean NCCC          n24-d2 DCCC             n24-d2 DCCC
    n24-d2 DCCC             n37-clean NCCC          n37-clean NCUU          n30-d2 DCCC
    n18-clean NCCC          n34-d2 NCCC             n34-d2 KCCC             n34-d2 DCCU
    n19-d3 NRRU             n19-d3 DCCC             n19-d3 DCUC             n19-d3 NCCU
    n19-d3 DCCC             n10-d2 DCCC             n10-d2 DCCU             n10-d2 DCCU
    n16-d1 DCCC             n16-d1 DCCC             n16-d1 DCCC             n28-d3 NCRR
    n28-d3 DCCU             n23-d2 DCUU             n23-d2 DCUU             n23-d2 DCCU
    c35-d3 DCCC             c35-d3 NCCC             n25-d2 DCCC             n25-d2 DCCC
    n25-d2 DCCC             c27-d3 DCCC             c27-d3 DCUC             c27-d3 DCCU
    c22-clean NCUR          c22-clean NCRU
"""
TRUTH = {"D": "defect", "K": "known", "N": "none"}
VERDICT = {"C": "confirmed", "R": "refuted", "U": "unsure"}
FINDINGS = [
    {"pr": pr, "truth": TRUTH[c[0]], "refute": VERDICT[c[1]], "reproduce": VERDICT[c[2]],
     "reproduce_v1": VERDICT[c[3]]}
    for pr, c in zip(RECORDED.split()[::2], RECORDED.split()[1::2])
]
# The 40 sampled PRs: 30 with a planted bug and 10 clean. Four got no bug finding at all: c16-d2
# (a planted bug the reviewer never found) and three clean PRs.
N_PRS = 40
BUGGY = sorted({f["pr"] for f in FINDINGS if not f["pr"].endswith("-clean")} | {"c16-d2"})


def test_the_findings():
    assert len(FINDINGS) == 106
    assert [sum(f["truth"] == t for f in FINDINGS) for t in ("defect", "known", "none")] == [68, 7, 31]
    assert len(BUGGY) == 30


def test_kept():
    f = {"pr": "x", "truth": "none", "refute": "refuted", "reproduce": "unsure", "reproduce_v1": "confirmed"}
    assert kept(f, "everything")
    assert not kept(f, "not refuted")
    assert not kept(f, "proven")
    assert kept(f, "proven or unsure")
    assert not kept(f, "proven or confirmed")
    assert kept(f, "proven, first harness")


def test_refute_drop_rates():
    # 2 of 75 right findings refuted (3%), 5 of 31 that match nothing (16%): the right direction,
    # and a small gap. It never said "unsure".
    assert drop_rates(FINDINGS, "not refuted") == (2, 75, 5, 31)
    assert sum(f["refute"] == "unsure" for f in FINDINGS) == 0


def test_reproduce_drop_rates():
    # proven: 69 of 75 right findings (92%), 22 of 31 that match nothing (71%)
    assert drop_rates(FINDINGS, "proven") == (6, 75, 9, 31)


def test_everything():
    o = outcome(FINDINGS, "everything", BUGGY, N_PRS)
    assert (o["kept"], round(100 * o["precision"]), o["recall"]) == (106, 71, 27)
    assert (round(o["noise_per_pr"], 2), o["dropped_true"]) == (0.78, 0)


def test_the_checks():
    o = outcome(FINDINGS, "not refuted", BUGGY, N_PRS)
    assert (o["kept"], round(100 * o["precision"]), o["recall"], round(o["noise_per_pr"], 2), o["dropped_true"]) == (99, 74, 27, 0.65, 2)
    o = outcome(FINDINGS, "proven", BUGGY, N_PRS)
    assert (o["kept"], round(100 * o["precision"]), o["recall"], round(o["noise_per_pr"], 2), o["dropped_true"]) == (91, 76, 27, 0.55, 6)
    o = outcome(FINDINGS, "proven or unsure", BUGGY, N_PRS)
    assert (o["kept"], round(100 * o["precision"]), o["recall"], o["dropped_true"]) == (103, 73, 27, 0)
    o = outcome(FINDINGS, "proven or confirmed", BUGGY, N_PRS)
    assert (o["kept"], round(100 * o["precision"]), o["recall"], o["dropped_true"]) == (105, 71, 27, 0)


def test_the_first_harness_looked_best():
    # 81% precision, the best of all, because fix edits had to match byte for byte. It lost 5
    # planted bugs (22 of 30 found, against 27) and dropped 19 right findings.
    o = outcome(FINDINGS, "proven, first harness", BUGGY, N_PRS)
    assert (o["kept"], round(100 * o["precision"]), o["recall"], round(o["noise_per_pr"], 2), o["dropped_true"]) == (69, 81, 22, 0.33, 19)
    now = {f["pr"] for f in FINDINGS if f["truth"] == "defect" and kept(f, "proven")}
    then = {f["pr"] for f in FINDINGS if f["truth"] == "defect" and kept(f, "proven, first harness")}
    assert sorted(now - then) == ["c02-d1", "n09-d2", "n23-d2", "n28-d3", "n34-d2"]


# Lines 44-55 of c02-d1's api/src/resolvers.ts (line 47 opens deleteSync, 4 spaces deep), and the
# find text of the recorded fix the first harness rejected, twice: every line 2 spaces too deep.
FILE = """      syncs.setSyncEnabled(db, args.id, args.enabled);
      return requireSync(args.id);
    },
    deleteSync: (args: { id: string }) => {
      const sync = requireSync(args.id);
      syncs.deleteSync(db, args.id);
      if (!syncs.listSyncs(db).some((s) => s.destinationId === sync.destinationId)) {
        db.run("DELETE FROM destinations WHERE id = ?", sync.destinationId);
      }
      return true;
    },
    triggerSync: (args: { id: string }) => {
"""
FIND = (
    "      deleteSync: (args: { id: string }) => {\n"
    "        const sync = requireSync(args.id);\n"
    "        syncs.deleteSync(db, args.id);\n"
    "        if (!syncs.listSyncs(db).some((s) => s.destinationId === sync.destinationId)) {\n"
    "          db.run(\"DELETE FROM destinations WHERE id = ?\", sync.destinationId);\n"
    "        }\n"
    "        return true;\n"
    "      },"
)


def test_count_matches():
    assert FIND not in FILE  # what the first harness checked: no exact match, so rejected
    assert count_matches(FILE, FIND) == 1  # same lines apart from indentation: accepted, once
    assert count_matches(FILE, "    deleteSync: (args: { id: string }) => {") == 1  # exact
    assert count_matches(FILE, "      return true;\n") == 1  # exact matches come first
    assert count_matches(FILE, "    },") == 2  # twice: ambiguous, so rejected
    assert count_matches(FILE, "return requireSync(args.id);") == 1
    assert count_matches(FILE, "deleteSync: (args: { id: number }) => {") == 0
    assert count_matches(FILE, "\n\n") == 0


def test_judge_proof():
    # n33-d1, the proof that seeds the mapping with the key "default" and fixes the worker:
    # fails on the PR (assert None == 'free'), passes with its fix, fails on the clean twin.
    assert judge_proof("failed", "passed") == "proven"
    assert judge_proof("failed", "passed", on_clean="failed") == "wrong reason"
    assert judge_proof("failed", "passed", on_clean="passed") == "proven"  # 60 of 63 did this
    assert judge_proof("passed", None) == "not proven"  # the test didn't notice anything
    assert judge_proof("error", None) == "not proven"  # an import error is not a failing assertion
    assert judge_proof("failed", "failed") == "not proven"  # the fix didn't fix what the test sees
