"""test_detect_cli.py — main(argv) wiring, deterministic. --bench against a detectors-root with NO baseline must
exit COVERAGE-INCOMPLETE (returncode 2). No-args (no root, no --bench) must error. No LLM."""
import importlib.util, os, tempfile, subprocess, sys, json

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DETECT = os.path.join(ROOT, "orchestrator", "detect.py")


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", DETECT)


def _empty_detectors_root():
    """A detectors-root whose domains/*/detectors/* has a single NON-baseline manifest → baseline-absent."""
    d = tempfile.mkdtemp()
    md = os.path.join(d, "domains", "security", "detectors", "auth")
    os.makedirs(md, exist_ok=True)
    json.dump({"id": "auth", "kind": "llm", "applies_to": {"always": False}},
              open(os.path.join(md, "detector.json"), "w"))
    return d


def test_bench_baseline_absent_exits_coverage_incomplete():
    droot = _empty_detectors_root()
    fo = os.path.join(tempfile.mkdtemp(), "f.json")
    r = subprocess.run([sys.executable, DETECT, "--bench", "--detectors-root", droot, "--findings-out", fo],
                       capture_output=True, text=True)
    assert r.returncode == 2, r.stderr
    assert "COVERAGE-INCOMPLETE" in r.stdout


def test_no_root_no_bench_errors():
    r = subprocess.run([sys.executable, DETECT], capture_output=True, text=True)
    assert r.returncode != 0  # argparse error


def test_main_returns_int():
    assert detect.main(["--bench", "--detectors-root", _empty_detectors_root()]) == 2
