"""Locate and expose the sibling or configured LingoLOGOS codex kernel. This module allows datasets/codex-python to remain an external package without copying or modifying datasets/codex. When lingologos_codex is already importable, nothing is changed; otherwise the bridge searches LINGOLOGOS_CODEX_ROOT and ancestor datasets/codex directories and inserts the matching root on sys.path. """ from __future__ import annotations import importlib import os import sys from pathlib import Path from typing import Optional def find_codex_root(start: Optional[Path] = None) -> Optional[Path]: """Return the path to the codex package root if found on disk.""" env_root = os.environ.get("LINGOLOGOS_CODEX_ROOT", "").strip() if env_root: candidate = Path(env_root).expanduser().resolve() if (candidate / "lingologos_codex").is_dir(): return candidate anchor = (start or Path(__file__)).resolve() for parent in [anchor, *anchor.parents]: direct = parent / "lingologos_codex" if direct.is_dir(): return parent sibling_codex = parent / "codex" if (sibling_codex / "lingologos_codex").is_dir(): return sibling_codex datasets_codex = parent / "datasets" / "codex" if (datasets_codex / "lingologos_codex").is_dir(): return datasets_codex return None def ensure_codex_on_path(start: Optional[Path] = None) -> Path: """Ensure lingologos_codex is importable and return the resolved codex root.""" try: mod = importlib.import_module("lingologos_codex") mod_file = getattr(mod, "__file__", None) if mod_file: return Path(mod_file).resolve().parent.parent except ImportError: pass codex_root = find_codex_root(start=start) if codex_root is None: raise ImportError( "Unable to locate lingologos_codex. Install lingologos-codex or set LINGOLOGOS_CODEX_ROOT." ) codex_str = str(codex_root) if codex_str not in sys.path: sys.path.insert(0, codex_str) importlib.import_module("lingologos_codex") return codex_root