"""test_gate_neutral_path.py — deterministic (#6 path-leak fix): --neutral-path blinds the injected
REVIEW TARGET path so a defect-revealing corpus dir (e.g. S4-kb-spaceids-sqli/) cannot prime the LLM.
No LLM: asserts the pure path-construction functions. Default (neutral=False) preserves real paths =
zero production regression. Path-load per convention."""
import importlib.util, os, tempfile

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def _load(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod); return mod


gate = _load("sg_gate", os.path.join(ROOT, "orchestrator", "gate.py"))

LEAKY_DIR = "S4-kb-spaceids-sqli"            # the corpus cell id — the exact priming vector
TARGET_REL = os.path.join("corpus", LEAKY_DIR, "vuln.ts")
BODY = "export const q = sql.raw(`SELECT * FROM kb WHERE space IN (${ids})`)\n"


def _leaky_target(tmp_path):
    d = os.path.join(tmp_path, "corpus", LEAKY_DIR)
    os.makedirs(d, exist_ok=True)
    f = os.path.join(d, "vuln.ts")
    with open(f, "w", encoding="utf-8") as fh:
        fh.write(BODY)
    return f


def test_neutral_label_strips_cell_dir_keeps_ext():
    lbl = gate._neutral_label(TARGET_REL)
    assert lbl == "review_target.ts"
    assert LEAKY_DIR not in lbl and "vuln" not in lbl


def test_bundle_neutral_blinds_target_header(tmp_path):
    target = _leaky_target(str(tmp_path))        # a REAL file (read succeeds) under a leaky cell dir
    deps = []
    leaky = gate.build_bundle(target, deps, neutral=False)
    blind = gate.build_bundle(target, deps, neutral=True)
    # default (production) preserves the real path — no regression
    assert LEAKY_DIR in leaky
    # neutral (measurement) injects no cell-id anywhere in the bundle (header blinded, body is pure code)
    assert LEAKY_DIR not in blind and "vuln" not in blind
    assert "review_target.ts" in blind
    # content itself is unchanged either way (the code under review is identical)
    assert BODY.strip() in blind and BODY.strip() in leaky


def test_write_neutral_file_copies_body_under_generic_name(tmp_path):
    target = _leaky_target(str(tmp_path))
    neutral = gate.write_neutral_file(target)
    try:
        assert os.path.basename(neutral).startswith("review_target_")
        assert neutral.endswith(".ts")
        assert LEAKY_DIR not in neutral            # the temp path carries no cell-id
        with open(neutral, encoding="utf-8") as fh:
            assert fh.read() == BODY               # exact content preserved for review
    finally:
        os.unlink(neutral)
