"""VidereClient — offline file-based analysis client."""

from __future__ import annotations

from radiens_core._constants import ALLEGO_CORE_ADDR, DEFAULT_HUB_ID
from radiens_core._transport._auth import AuthInterceptor
from radiens_core._transport._channel_pool import ChannelPool
from radiens_core.models.dataset import DatasetMetadata
from radiens_core.models.enums import RadiensService


class VidereClient:
    """Client for offline file-based analysis.

    Usage::

        with VidereClient() as client:
            meta = client.link_data_file("/path/to/recording.xdat")
    """

    def __init__(self, address: str = ALLEGO_CORE_ADDR) -> None:
        self._address = address
        self._pool = ChannelPool(
            interceptors=[AuthInterceptor(server_address=address)],
        )
        self._datasets: dict[str, DatasetMetadata] = {}

    # --- Lifecycle ---

    def close(self) -> None:
        """Close all gRPC channels."""
        self._pool.close()

    def __enter__(self) -> VidereClient:
        return self

    def __exit__(self, *args: object) -> None:
        self.close()

    # --- Internal helpers ---

    def _server_address(self, service: RadiensService) -> str:
        """Resolve server address for the given service."""
        return self._address

    def _resolve_dataset(self, ref: str | DatasetMetadata) -> DatasetMetadata:
        """Resolve a dataset reference to DatasetMetadata."""
        if isinstance(ref, DatasetMetadata):
            return ref
        ref_str = str(ref)
        if ref_str in self._datasets:
            return self._datasets[ref_str]
        raise ValueError(f"Unknown dataset: {ref_str}. Link it first with link_data_file().")

    # --- Data file operations ---

    def link_data_file(
        self,
        path: str,
        hub_name: str = DEFAULT_HUB_ID,
    ) -> DatasetMetadata:
        """Link a recording file and return its metadata.

        Parameters
        ----------
        path
            Path to the recording file (e.g., .xdat, .rhd).
        hub_name
            Hub name (default: "default").

        Returns
        -------
        DatasetMetadata
            Metadata for the linked dataset.
        """
        from radiens_core._services._radiens_core import set_datasource

        addr = self._server_address(RadiensService.CORE)
        meta = set_datasource(self._pool, addr, path)
        self._datasets[meta.id] = meta
        return meta
