"""Load the server-local scenario configuration without changing ``sys.path``."""

from __future__ import annotations

import importlib.util
from collections.abc import Callable, Iterable
from pathlib import Path
from types import ModuleType


DEFAULT_SCENARIO_CONFIG_DIRS = (
    Path("/etc/contextra"),
    Path("/opt/contextra/configs"),
)


def _load_module(path: Path) -> ModuleType:
    spec = importlib.util.spec_from_file_location(
        "_contextra_server_scenario_config",
        path,
    )
    if spec is None or spec.loader is None:
        raise ImportError("scenario configuration loader is unavailable")

    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def load_scenario_config_api(
    search_dirs: Iterable[Path] = DEFAULT_SCENARIO_CONFIG_DIRS,
) -> tuple[Callable[[], list[str]], Callable[[str], dict]]:
    """Return the two functions consumed by ``ScenarioRunner``."""

    for directory in search_dirs:
        path = Path(directory) / "scenario_config.py"
        if not path.is_file():
            continue

        module = _load_module(path)
        get_active = getattr(module, "get_active_scenarios", None)
        get_runtime = getattr(module, "get_scenario_runtime_cfg", None)
        if not callable(get_active) or not callable(get_runtime):
            raise ImportError("scenario configuration contract is invalid")
        return get_active, get_runtime

    raise ModuleNotFoundError("scenario_config.py was not found in approved locations")
