import os, sys
from pathlib import Path

def find_top_package_dir(p: Path) -> Path | None:
    """Walk upward until the topmost __init__.py-containing directory."""
    p = p.resolve()
    if p.is_file():
        p = p.parent
    top = None
    while (p / "__init__.py").exists():
        top = p
        if p.parent == p:
            break
        p = p.parent
    return top

def derive_package_for_file(file: str) -> tuple[str, Path]:
    """Return (pkg_name, sysroot) for the module file."""
    here = Path(file).resolve()
    top_pkg_dir = find_top_package_dir(here)
    if not top_pkg_dir:
        raise RuntimeError(f"No package context above {here}. Add __init__.py up the tree.")
    sysroot = top_pkg_dir.parent
    if str(sysroot) not in sys.path:
        sys.path.insert(0, str(sysroot))
    parts = here.with_suffix("").relative_to(sysroot).parts
    pkg_name = ".".join(parts[:-1])
    return pkg_name, sysroot
