"""test_detect_dispatch.py — dispatch_one parses a contract emit on success; a failed/garbled gate → synthetic
degraded dict, NEVER an empty-findings clean. We stub the gate by pointing detect.GATE at a tiny fake script
that writes a known --emit file (or exits non-zero), so no real gate.py/LLM runs."""
import importlib.util, os, tempfile, json, textwrap

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


detect = _load("sg_detect", os.path.join(ROOT, "orchestrator", "detect.py"))

DET = {"id": "baseline", "kind": "llm"}


def _fake_gate(body):
    fd, p = tempfile.mkstemp(suffix=".py")
    with os.fdopen(fd, "w") as fh:
        fh.write(textwrap.dedent(body))
    return p


def test_dispatch_one_parses_contract_emit(monkeypatch):
    # fake gate: find the --emit path in argv, write a contract dict there, exit 0
    fake = _fake_gate("""
        import sys, json
        a = sys.argv
        emit = a[a.index("--emit") + 1]
        json.dump({"detector": "baseline", "status": "ok",
                   "findings": [{"ruleId": "baseline", "level": "error", "class": "S1",
                                 "message": "reset token single-use not enforced", "file": "t.ts",
                                 "line": 0, "symbol": "", "sev": "high", "rolls": 1, "of": 1}],
                   "coverage": {"scanned": ["t.ts"], "unresolved": []}}, open(emit, "w"))
    """)
    monkeypatch.setattr(detect, "GATE", fake)
    out = tempfile.mkdtemp()
    r = detect.dispatch_one("/abs/t.ts", DET, 1, None, "sonnet", "medium", out)
    assert r["status"] == "ok"
    assert r["findings"][0]["sev"] == "high"


def test_dispatch_one_gate_failure_is_degraded_not_clean(monkeypatch):
    fake = _fake_gate("import sys\nsys.exit(3)\n")  # non-zero, no emit written
    monkeypatch.setattr(detect, "GATE", fake)
    out = tempfile.mkdtemp()
    r = detect.dispatch_one("/abs/t.ts", DET, 1, None, "sonnet", "medium", out)
    assert r["status"] == "error"
    assert r["findings"] == []
    assert r["coverage"]["unresolved"]  # surfaced, never silent


def test_dispatch_one_unparseable_emit_is_degraded(monkeypatch):
    fake = _fake_gate("""
        import sys
        a = sys.argv
        open(a[a.index("--emit") + 1], "w").write("{not json")
    """)
    monkeypatch.setattr(detect, "GATE", fake)
    out = tempfile.mkdtemp()
    r = detect.dispatch_one("/abs/t.ts", DET, 1, None, "sonnet", "medium", out)
    assert r["status"] == "error" and r["findings"] == []
