"""test_resolver.py — the cross-file resolver at its real home (refactor 1). Loads resolver.py by PATH
(project convention — no package import, no __init__.py)."""
import importlib.util, os, subprocess, sys, 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

resolver = _load("sg_resolver", os.path.join(ROOT, "orchestrator", "resolver.py"))

def test_resolver_exposes_public_surface_and_resolves_a_local_relative_import():
    for name in ("build_workspace_aliases", "find_repo_root", "resolve",
                 "resolve_through_barrel", "first_party_value_imports", "collect_deps"):
        assert hasattr(resolver, name), f"resolver missing {name}"
    d = tempfile.mkdtemp()
    open(os.path.join(d, "dep.ts"), "w").write("export function helper() { return 1 }\n")
    open(os.path.join(d, "main.ts"), "w").write("import { helper } from './dep'\nhelper()\n")
    got = resolver.first_party_value_imports(os.path.join(d, "main.ts"), [])
    assert (os.path.join(d, "dep.ts"), "helper") in got


def test_gate_cli_dry_run_drives_moved_resolver_symbols():
    """Locks gate.py main()'s CLI wiring to the moved resolver fns: find_repo_root ->
    build_workspace_aliases -> collect_deps. --dry-run returns before oracle/LLM, so this
    runs without `claude`. An empty .git/ anchors find_repo_root at the tmpdir; resolve()
    handles the './dep' relative import with no alias."""
    d = tempfile.mkdtemp()
    os.mkdir(os.path.join(d, ".git"))  # anchor find_repo_root at d (deterministic root)
    open(os.path.join(d, "dep.ts"), "w").write("export function helper() { return 1 }\n")
    open(os.path.join(d, "main.ts"), "w").write("import { helper } from './dep'\nhelper()\n")
    tmpl = os.path.join(d, "t.prompt.txt")
    open(tmpl, "w").write("review {{MODULE_PATH}}\n")
    r = subprocess.run(
        [sys.executable, os.path.join(ROOT, "orchestrator", "gate.py"),
         os.path.join(d, "main.ts"), "--dry-run", "--template", tmpl],
        capture_output=True, text=True, timeout=60,
    )
    assert r.returncode == 0, f"gate.py --dry-run crashed (main() wiring broke):\n{r.stderr}"
    assert "dep.ts" in r.stdout, f"dep.ts not pulled into scope by collect_deps:\n{r.stdout}"
