"""test_mapper_kind_of.py — kind_of() must agree with enumerate_surface() per file (no-drift), and infer a
call-registered kind from body content when not file-routed. Deterministic, no LLM. 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


mapper = _load("sg_mapper", os.path.join(ROOT, "orchestrator", "mapper.py"))


def _route_tree():
    """A file-routed tree: a route file under a recognized route location + a non-route helper."""
    d = tempfile.mkdtemp()
    routes = os.path.join(d, "apps/api/src/pages/auth")
    os.makedirs(routes, exist_ok=True)
    open(os.path.join(routes, "refresh.ts"), "w").write(
        "export async function POST(req){ return new Response('ok') }\n")
    helper = os.path.join(d, "packages/util/src")
    os.makedirs(helper, exist_ok=True)
    open(os.path.join(helper, "plain.ts"), "w").write("export const add = (a,b)=>a+b\n")
    return d


def test_kind_of_agrees_with_enumerate_surface_per_file():
    d = _route_tree()
    enr = {e.path: e.kind for e in mapper.enumerate_surface(d)}
    assert enr, "fixture must enumerate at least one entry"
    for path, kind in enr.items():
        rel = os.path.relpath(path, d)
        body = open(path, encoding="utf-8").read()
        assert mapper.kind_of(rel, body=body) == kind, f"kind_of drifted from enumerate on {rel}"


def test_kind_of_file_routed_needs_no_body():
    # a path under a route location resolves by LOCATION alone (body=None ok)
    assert mapper.kind_of("apps/api/src/pages/auth/refresh.ts") is not None


def test_kind_of_returns_none_for_unroutable_without_body():
    assert mapper.kind_of("packages/util/src/plain.ts") is None
