"""Choose an execution surface from an injected port chain."""
from __future__ import annotations

from collections.abc import Callable, Sequence

from ..domain.worker_runtime import (
    EnvironmentBlocked,
    RuntimeHandle,
    SurfaceUnavailable,
    WorkerSpawnRequest,
)
from ..ports.worker_runtime import WorkerRuntimePort


def open_worker(
    chain: Sequence[WorkerRuntimePort],
    request_for: Callable[[str], WorkerSpawnRequest],
) -> RuntimeHandle:
    last_unavailable: SurfaceUnavailable | None = None
    for port in chain:
        try:
            return port.spawn(request_for(port.surface))
        except EnvironmentBlocked:
            raise
        except SurfaceUnavailable as exc:
            last_unavailable = exc
    if last_unavailable is None:
        raise SurfaceUnavailable("runtime chain is empty")
    raise last_unavailable
