# tests/test_ledger_precision.py — anti-canary (precision) coverage grade (goal-item #7).
# Negative-polarity twin of test_ledger_lifecycle.py: discriminator_tested upgraded from the ships_safe
# boolean to a tri-state MEASUREMENT grade consuming recall_gate's rate_validated set. GRADED, never a gap.
import importlib.util, os
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _load(name, path):
    s = importlib.util.spec_from_file_location(name, path); m = importlib.util.module_from_spec(s); s.loader.exec_module(m); return m
cov = _load("sg_ledger", os.path.join(ROOT, "ledger.py"))

def _det(tmp, did, **kw):
    d = {"id": did, "_dir": str(tmp / did)}; d.update(kw); (tmp / did).mkdir(exist_ok=True); return d

def _det_with_safe(tmp, did, covers):
    d = _det(tmp, did, covers=covers)
    cdir = tmp / did / "cells"; cdir.mkdir(parents=True, exist_ok=True)
    (cdir / "safe.ts").write_text("// safe conformance cell\n")
    return d

def _cell(cls, cid):
    return {"class": cls, "canonical_symbol": cls + "sym", "fix_sha": "h" + cid, "id": cid,
            "file": cid + ".ts", "_dir": "/nowhere/" + cid}

def test_precision_measured_present_none(tmp_path):
    classes = ["S1", "S2", "S3"]
    cells = [_cell("S1", "c1"), _cell("S2", "c2"), _cell("S3", "c3")]
    # baseline covers+ships-safe S1,S2; d_s3 covers S3 but ships NO safe cell (avoids an incidental uncovered gap)
    dets = [_det_with_safe(tmp_path, "baseline", ["S1", "S2"]), _det(tmp_path, "d_s3", covers=["S3"])]
    # only c1 (class S1) has a measured anti-canary record
    precision_validated = [{"cell_id": "c1", "rate": 1.0, "k": 3, "metric": "anti-canary-green-rate",
                            "status": "OK", "waived": False}]
    reg = cov.build(cells, dets, [], classes, (), precision_validated)
    by = {g["class"]: g for g in reg["classes"]}
    assert by["S1"]["discriminator_tested"] == "measured" and by["S1"]["discriminator_rate"] == "3/3"
    assert by["S2"]["discriminator_tested"] == "present" and by["S2"]["discriminator_rate"] is None
    assert by["S3"]["discriminator_tested"] == "none" and by["S3"]["discriminator_rate"] is None

def test_precision_below_floor_rate_not_masked(tmp_path):
    classes = ["S1"]
    cells = [_cell("S1", "c1")]
    dets = [_det_with_safe(tmp_path, "baseline", ["S1"])]
    # a sub-floor anti-canary rate (1/3) must still render the rate, NOT a bare green 'measured'
    precision_validated = [{"cell_id": "c1", "rate": 1 / 3, "k": 3, "metric": "anti-canary-green-rate",
                            "status": "BELOW_FLOOR", "waived": False}]
    reg = cov.build(cells, dets, [], classes, (), precision_validated)
    g = reg["classes"][0]
    assert g["discriminator_tested"] == "measured" and g["discriminator_rate"] == "1/3"

def test_precision_graded_not_a_gap(tmp_path):
    classes = ["S1"]
    cells = [_cell("S1", "c1")]
    dets = [_det_with_safe(tmp_path, "baseline", ["S1"])]
    reg = cov.build(cells, dets, [], classes, (), [])
    assert not any(("precision" in g["kind"]) or ("discriminator" in g["kind"]) for g in reg["gaps"])

def test_md_renders_rate_and_mutant_note(tmp_path):
    classes = ["S1"]
    cells = [_cell("S1", "c1")]
    dets = [_det_with_safe(tmp_path, "baseline", ["S1"])]
    precision_validated = [{"cell_id": "c1", "rate": 1.0, "k": 3, "metric": "anti-canary-green-rate",
                            "status": "OK", "waived": False}]
    md = cov._md(cov.build(cells, dets, [], classes, (), precision_validated))
    assert "measured 3/3" in md
    assert "discriminator-mutant" in md

def test_precision_multi_cell_surfaces_worst(tmp_path):
    # a class with TWO measured anti-canary cells must surface the WORST (min-rate) one, not the first/best —
    # guards the masking invariant for multi-cell classes (precision_grade's min-over-cells selection).
    classes = ["S1"]
    cells = [_cell("S1", "c1"), _cell("S1", "c2")]
    dets = [_det_with_safe(tmp_path, "baseline", ["S1"])]
    precision_validated = [
        {"cell_id": "c1", "rate": 1.0, "k": 3, "metric": "anti-canary-green-rate", "status": "OK", "waived": False},
        {"cell_id": "c2", "rate": 1 / 3, "k": 3, "metric": "anti-canary-green-rate", "status": "BELOW_FLOOR", "waived": False},
    ]
    reg = cov.build(cells, dets, [], classes, (), precision_validated)
    g = reg["classes"][0]
    assert g["discriminator_tested"] == "measured" and g["discriminator_rate"] == "1/3"
