"""test_detect_target.py — detect_target status invariants (no-false-clean). dispatch_one + merge stubbed so no
gate/LLM runs. clean is reachable ONLY when every selected detector ran ok with zero findings."""
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


detect = _load("sg_detect", os.path.join(ROOT, "orchestrator", "detect.py"))
BASELINE = {"id": "baseline", "kind": "llm", "applies_to": {"always": True}}


def _tmp_target():
    fd, p = tempfile.mkstemp(suffix=".ts")
    os.close(fd)
    return p


def _stub_dispatch(results):
    it = iter(results)
    return lambda *a, **k: next(it)


def test_all_ok_zero_findings_is_clean(monkeypatch):
    monkeypatch.setattr(detect, "dispatch_one",
                        _stub_dispatch([{"detector": "baseline", "status": "ok", "findings": [],
                                         "coverage": {"scanned": ["t"], "unresolved": []}}]))
    r = detect.detect_target(_tmp_target(), "x", [BASELINE], out_dir=tempfile.mkdtemp())
    assert r["status"] == "clean"


def test_detector_error_is_degraded_not_clean(monkeypatch):
    monkeypatch.setattr(detect, "dispatch_one",
                        _stub_dispatch([{"detector": "baseline", "status": "error", "findings": [],
                                         "coverage": {"scanned": [], "unresolved": ["gate failed"]}}]))
    r = detect.detect_target(_tmp_target(), "x", [BASELINE], out_dir=tempfile.mkdtemp())
    assert r["status"] == "degraded"


def test_findings_present_is_findings(monkeypatch):
    monkeypatch.setattr(detect, "dispatch_one",
                        _stub_dispatch([{"detector": "baseline", "status": "ok",
                                         "findings": [{"message": "bug", "sev": "high", "rolls": 1, "of": 1}],
                                         "coverage": {"scanned": ["t"], "unresolved": []}}]))
    r = detect.detect_target(_tmp_target(), "x", [BASELINE], out_dir=tempfile.mkdtemp())
    assert r["status"] == "findings"
    assert r["findings"][0]["title"] == "bug"


def test_merge_degraded_is_degraded(monkeypatch):
    monkeypatch.setattr(detect, "dispatch_one",
                        _stub_dispatch([{"detector": "baseline", "status": "ok",
                                         "findings": [{"message": "a", "sev": "high", "rolls": 1, "of": 1},
                                                      {"message": "b", "sev": "low", "rolls": 1, "of": 1}],
                                         "coverage": {"scanned": ["t"], "unresolved": []}}]))
    monkeypatch.setattr(detect.semantic_merge, "merge_groups", lambda g, **k: (list(g), True))
    r = detect.detect_target(_tmp_target(), "x", [BASELINE], out_dir=tempfile.mkdtemp())
    assert r["status"] == "degraded"
