from __future__ import annotations

from dataclasses import dataclass
from typing import Sequence

from gateway_core.application.ports.NodesPort import NodesPort
from gateway_core.domain.node.NodeInfo import NodeInfo
from gateway_core.domain.node.NodeSelector import NodeSelector


@dataclass(frozen=True, slots=True)
class Nodes(NodesPort):
    """
    In-memory implementation of NodesPort.

    Provides query helpers (selectors, lookup by id / tag)
    over a static list of NodeInfo.
    """
    _nodes: list[NodeInfo]

    def listNodes(self, selector: NodeSelector) -> Sequence[NodeInfo]:
        if selector.kind == "all":
            return self._nodes

        if selector.kind == "one":
            return [self.getNodeById(selector.nodeId)]

        if selector.kind == "subset":
            ids = selector.nodeIds or set()
            return [n for n in self._nodes if n.nodeId in ids]

        if selector.kind == "tag":
            if selector.tag is None:
                return []
            return [n for n in self._nodes if selector.tag in n.tags]

        return self._nodes

    def getNodeById(self, nodeId: str) -> NodeInfo:
        for n in self._nodes:
            if n.nodeId == nodeId:
                return n
        raise RuntimeError(f"Unknown nodeId: {nodeId}")

    def findNodesByTag(self, tag: str) -> Sequence[NodeInfo]:
        return [n for n in self._nodes if tag in n.tags]
