# tests/test_oracle_emit.py
"""oracle_emit.py — the oracle's contract entry. Wraps the validated gate.run_oracle_set and maps the
FLAGS prose to contract JSON. RED service_vuln.ts → owner|referee finding (warning, imprecise oracle);
GREEN service_safe.ts → no owner|referee finding (mediated → not in FLAGS). Skips where bun is absent."""
import json, os, shutil, subprocess
import pytest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EMIT = os.path.join(ROOT, "domains", "security", "detectors", "oracle", "oracle_emit.py")
CELLS = os.path.join(ROOT, "domains", "security", "detectors", "oracle", "cells")
pytestmark = pytest.mark.skipif(shutil.which("bun") is None, reason="oracle runtime `bun` not installed")

def _emit(*files):
    p = subprocess.run(["python3", EMIT, *files], capture_output=True, text=True, timeout=180)
    return json.loads(p.stdout)

def test_red_helper_emits_owner_referee_warning():
    out = _emit(os.path.join(CELLS, "service_vuln.ts"))
    assert out["detector"] == "oracle"
    hits = [f for f in out["findings"] if f["symbol"].lower() == "owner|referee"]
    assert hits, f"expected owner|referee finding; got {out}"
    assert hits[0]["level"] == "warning" and hits[0]["class"] == "S9"
    assert out["coverage"]["scanned"] == [os.path.join(CELLS, "service_vuln.ts")]

def test_green_helper_no_owner_referee_finding():
    out = _emit(os.path.join(CELLS, "service_safe.ts"))
    assert not any(f["symbol"].lower() == "owner|referee" for f in out["findings"]), \
        f"safe helper must not flag owner|referee (mediated → EXTRACTED, not FLAGS); got {out}"
