from app.errors import UnknownEndpointError


class AudioRouter:
    def __init__(self, inputs, outputs):
        self.inputs = inputs
        self.outputs = outputs

    async def list_inputs(self):
        return [await endpoint.capabilities() for endpoint in self.inputs]

    async def list_outputs(self):
        return [await endpoint.capabilities() for endpoint in self.outputs]

    async def select_input(self, preferred: str | None = None):
        return await self._select(self.inputs, preferred, direction="input")

    async def select_output(self, preferred: str | None = None):
        return await self._select(self.outputs, preferred, direction="output")

    async def _select(self, endpoints, preferred: str | None, direction: str):
        # Capabilities einmal sammeln (Basis fuer spaetere capability-basierte Auswahl).
        pairs = [(endpoint, await endpoint.capabilities()) for endpoint in endpoints]

        if preferred:
            for endpoint, caps in pairs:
                if caps.id == preferred or caps.kind == preferred:
                    return endpoint
            # Angefragter Endpunkt existiert nicht -> KEIN stiller Default-Fallback.
            available = sorted({caps.id for _, caps in pairs} | {caps.kind for _, caps in pairs})
            raise UnknownEndpointError(
                f"Unbekannter {direction}-Endpunkt {preferred!r}. Verfuegbar: {available}"
            )

        for endpoint, caps in pairs:
            if caps.default:
                return endpoint
        raise RuntimeError(f"Kein {direction}-Standardendpunkt verfuegbar")
