"""DatasetMetadata <-> proto converters."""

from __future__ import annotations

from typing import TYPE_CHECKING

from radiens_core._converters._channels import channel_metadata_from_proto
from radiens_core._converters._enums import file_type_from_proto
from radiens_core.models.dataset import DatasetMetadata
from radiens_core.models.time_range import TimeRange

if TYPE_CHECKING:
    from radiens_core._generated import datasource_pb2


def dataset_metadata_from_proto(
    raw: datasource_pb2.DataSourceSetSaveReply,
) -> DatasetMetadata:
    """Build domain DatasetMetadata from proto DataSourceSetSaveReply."""
    status = raw.status
    sig_group = status.signalGroup
    pb_tr = status.tR

    channel_metadata = channel_metadata_from_proto(sig_group)

    # Build TimeRange from the proto TimeRange message
    sec_list = list(pb_tr.timeRangeSec)
    ts_list = list(pb_tr.timestamp)
    sec_start = sec_list[0] if len(sec_list) > 0 else 0.0
    sec_end = sec_list[1] if len(sec_list) > 1 else 0.0
    ts_start = ts_list[0] if len(ts_list) > 0 else 0
    ts_end = ts_list[1] if len(ts_list) > 1 else 0

    time_range = TimeRange(
        sec=(sec_start, sec_end),
        timestamp=(ts_start, ts_end),
        fs=pb_tr.fs,
        dur_sec=sec_end - sec_start,
        walltime=pb_tr.wallTimeStart,
        n=ts_end - ts_start,
    )

    return DatasetMetadata(
        id=raw.dsourceID,
        base_name=status.baseFileName,
        path=status.path,
        file_type=file_type_from_proto(status.fileType),
        time_range=time_range,
        channel_metadata=channel_metadata,
        parent_dsource_id="",
        probe_uid=sig_group.datasetUID,
    )
