# tests/test_ledger_lifecycle.py
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"))

S4CELL = {"id": "S4-x", "class": "S4", "file": "kb.ts", "fix_sha": "9b0c485", "canonical_symbol": "listArticlesBySpaceIds", "_dir": "/x", "provenance": {"discovered_by": "harvest"}}
DET = {"id": "baseline", "_dir": "/b", "covers": ["S4"]}
CLASSES = ["S4"]

def _build(solutions):
    return cov.build([S4CELL], [DET], [], CLASSES, solutions)

def test_resolution_none_without_adapter():
    assert _build(())["defects"][0]["resolution"] == "none"

def test_resolution_suggested_for_located_adapter():
    assert _build([{"id": "s", "class": "S4", "rung": "located-suggestion"}])["defects"][0]["resolution"] == "suggested"

def test_resolution_auto_for_syntactic_adapter():
    assert _build([{"id": "s", "class": "S4", "rung": "syntactic-local"}])["defects"][0]["resolution"] == "auto"

def test_resolution_via_applies_to_class():
    assert _build([{"id": "s", "applies_to": {"class": "S4"}, "rung": "located-suggestion"}])["defects"][0]["resolution"] == "suggested"

def test_row_carries_provenance():
    assert _build(())["defects"][0]["provenance"] == {"discovered_by": "harvest"}

def test_md_has_lifecycle_table():
    md = cov._md(_build([{"id": "s", "class": "S4", "rung": "located-suggestion"}]))
    assert "Lifecycle (one row per defect)" in md and "| S4-x | S4 |" in md and "suggested" in md

def test_resolution_graded_not_a_gap():
    assert not any(g["kind"].startswith("resolution") for g in _build(())["gaps"])

def test_declared_solution_without_conformance_is_a_gap():
    # a rung-declaring solution whose exec is missing → structural no-false-coverage gap (NOT a silent 'suggested')
    reg = cov.build([S4CELL], [DET], [], CLASSES,
                    [{"id": "ghost", "class": "S4", "rung": "located-suggestion", "exec": ["python3", "/no/such/solve.py"]}])
    assert any(g["kind"] == "solution-no-conformance" and g["class"] == "S4" for g in reg["gaps"])

def test_real_s4_solution_ships_conformance_no_gap():
    # the real sql-parameterize adapter ships solve.py + cells/ → admission satisfied → NO gap
    sols, _ = cov.manifest.load(ROOT, kind="solution")
    reg = cov.build(cov.bench.load_cells(), cov.manifest.load(ROOT)[0], cov.load_confirmed(), cov.taxonomy_classes(), sols)
    assert not any(g["kind"] == "solution-no-conformance" for g in reg["gaps"])
