"""Safe loader for a provider adapter factory declared in a manifest."""
from __future__ import annotations

import hashlib
import importlib.util
from collections.abc import Callable
from pathlib import Path


class FactoryLoadError(ValueError):
    """Raised when an adapter factory reference cannot be safely loaded."""


def load_relative_factory(manifest_path: Path, factory_ref: str) -> Callable[..., object]:
    """Load a callable factory without allowing its file to leave the adapter."""
    file_name, separator, symbol = factory_ref.partition(":")
    if not separator or not file_name or not symbol:
        raise FactoryLoadError(f"invalid factory reference: {factory_ref!r}")
    adapter_root = manifest_path.parent.resolve()
    module_path = (adapter_root / file_name).resolve()
    if adapter_root not in module_path.parents or not module_path.is_file():
        raise FactoryLoadError(f"factory escapes adapter root: {factory_ref!r}")
    module_name = f"okstra_adapter_{hashlib.sha256(str(module_path).encode()).hexdigest()}"
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    if spec is None or spec.loader is None:
        raise FactoryLoadError(f"cannot load factory module: {module_path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    factory = getattr(module, symbol, None)
    if not callable(factory):
        raise FactoryLoadError(f"factory symbol is not callable: {factory_ref!r}")
    return factory
