from __future__ import annotations
import sys
from importlib.machinery import ModuleSpec, PathFinder
from importlib.machinery import all_suffixes as module_suffixes
from importlib.util import spec_from_file_location
from itertools import chain
from pathlib import Path

MAPPING: dict[str, str] = {'acp_adapter': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/acp_adapter', 'agent': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/agent', 'batch_runner': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/batch_runner', 'cli': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/cli', 'cron': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/cron', 'gateway': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/gateway', 'hermes_agent': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_agent', 'hermes_bootstrap': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_bootstrap', 'hermes_cli': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli', 'hermes_constants': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_constants', 'hermes_constants_scratch': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_constants_scratch', 'hermes_constants_scratch_detach': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_constants_scratch_detach', 'hermes_constants_scratch_stuck': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_constants_scratch_stuck', 'hermes_dir_acl': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_dir_acl', 'hermes_logging': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_logging', 'hermes_platform': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_platform', 'hermes_scope': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_scope', 'hermes_startup_watchdog': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_startup_watchdog', 'hermes_state': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_state', 'hermes_state_common': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_state_common', 'hermes_state_loop_guard': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_state_loop_guard', 'hermes_state_registry': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_state_registry', 'hermes_time': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_time', 'hermes_yaml': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_yaml', 'lineage_adoption': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/lineage_adoption', 'model_tools': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/model_tools', 'persistence': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/persistence', 'persistence_assembly': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/persistence_assembly', 'plugins': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins', 'pm': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/pm', 'process_identity': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/process_identity', 'providers': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/providers', 'registration_lifecycle': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/registration_lifecycle', 'run_agent': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/run_agent', 'session_keys': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/session_keys', 'session_rescue': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/session_rescue', 'session_retention': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/session_retention', 'session_rules': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/session_rules', 'sqlite_support': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/sqlite_support', 'storage_errors': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/storage_errors', 'storage_limits': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/storage_limits', 'storage_user_copy': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/storage_user_copy', 'tools': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/tools', 'toolset_distributions': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/toolset_distributions', 'toolsets': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/toolsets', 'trajectory_compressor': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/trajectory_compressor', 'tui_gateway': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/tui_gateway', 'utils': '/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/utils'}
NAMESPACES: dict[str, list[str]] = {'tools.neutts_samples': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/tools/neutts_samples'], 'tools.wakewords': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/tools/wakewords'], 'hermes_cli.web_dist': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/web_dist'], 'hermes_cli.data': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/data'], 'hermes_cli.tui_dist': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/tui_dist'], 'hermes_cli.web_dist.fonts-terminal': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/web_dist/fonts-terminal'], 'hermes_cli.web_dist.fonts': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/web_dist/fonts'], 'hermes_cli.web_dist.assets': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/web_dist/assets'], 'hermes_cli.observability.schemas': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/observability/schemas'], 'hermes_cli.tui_dist.scripts': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/hermes_cli/tui_dist/scripts'], 'gateway.assets': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/gateway/assets'], 'persistence.sqlite.gateway': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/persistence/sqlite/gateway'], 'persistence.sqlite.authority': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/persistence/sqlite/authority'], 'persistence.sqlite.workers': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/persistence/sqlite/workers'], 'persistence.sqlite.housekeeping': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/persistence/sqlite/housekeeping'], 'plugins.platforms': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/platforms'], 'plugins.model-providers': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/model-providers'], 'plugins.dashboard_auth': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/dashboard_auth'], 'plugins.image_gen': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/image_gen'], 'plugins.delegation': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/delegation'], 'plugins.kanban': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/kanban'], 'plugins.video_gen': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/video_gen'], 'plugins.hermes-achievements': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/hermes-achievements'], 'plugins.browser': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/browser'], 'plugins.platforms.photon.sidecar': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/platforms/photon/sidecar'], 'plugins.kanban.systemd': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/kanban/systemd'], 'plugins.kanban.dashboard': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/kanban/dashboard'], 'plugins.kanban.dashboard.dist': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/kanban/dashboard/dist'], 'plugins.config_backends.remote.vendor': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/config_backends/remote/vendor'], 'plugins.config_backends.remote.vendor.conformance': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/config_backends/remote/vendor/conformance'], 'plugins.config_backends.remote.vendor.conformance.config-resolution': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/config_backends/remote/vendor/conformance/config-resolution'], 'plugins.hermes-achievements.tests': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/hermes-achievements/tests'], 'plugins.hermes-achievements.dashboard': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/hermes-achievements/dashboard'], 'plugins.hermes-achievements.dashboard.dist': ['/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/workspace/plugins/hermes-achievements/dashboard/dist']}
PATH_PLACEHOLDER = '__editable__.hermes_agent-0.0.0.finder' + ".__path_hook__"


class _EditableFinder:  # MetaPathFinder
    @classmethod
    def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None:  # type: ignore
        # Top-level packages and modules (we know these exist in the FS)
        if fullname in MAPPING:
            pkg_path = MAPPING[fullname]
            return cls._find_spec(fullname, Path(pkg_path))

        # Handle immediate children modules (required for namespaces to work)
        # To avoid problems with case sensitivity in the file system we delegate
        # to the importlib.machinery implementation.
        parent, _, child = fullname.rpartition(".")
        if parent and parent in MAPPING:
            return PathFinder.find_spec(fullname, path=[MAPPING[parent]])

        # Other levels of nesting should be handled automatically by importlib
        # using the parent path.
        return None

    @classmethod
    def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
        init = candidate_path / "__init__.py"
        candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
        for candidate in chain([init], candidates):
            if candidate.exists():
                return spec_from_file_location(fullname, candidate)
        return None


class _EditableNamespaceFinder:  # PathEntryFinder
    @classmethod
    def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
        if path == PATH_PLACEHOLDER:
            return cls
        raise ImportError

    @classmethod
    def _paths(cls, fullname: str) -> list[str]:
        paths = NAMESPACES[fullname]
        if not paths and fullname in MAPPING:
            paths = [MAPPING[fullname]]
        # Always add placeholder, for 2 reasons:
        # 1. __path__ cannot be empty for the spec to be considered namespace.
        # 2. In the case of nested namespaces, we need to force
        #    import machinery to query _EditableNamespaceFinder again.
        return [*paths, PATH_PLACEHOLDER]

    @classmethod
    def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None:  # type: ignore
        if fullname in NAMESPACES:
            spec = ModuleSpec(fullname, None, is_package=True)
            spec.submodule_search_locations = cls._paths(fullname)
            return spec
        return None

    @classmethod
    def find_module(cls, _fullname) -> None:
        return None


def install():
    if not any(finder == _EditableFinder for finder in sys.meta_path):
        sys.meta_path.append(_EditableFinder)

    if not NAMESPACES:
        return

    if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
        # PathEntryFinder is needed to create NamespaceSpec without private APIS
        sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
    if PATH_PLACEHOLDER not in sys.path:
        sys.path.append(PATH_PLACEHOLDER)  # Used just to trigger the path hook
