"""TimeRange <-> proto converters."""

from __future__ import annotations

from radiens_core._generated import common_pb2
from radiens_core.models.dataset import TrsMode
from radiens_core.models.time_range import TimeRange

# --- TrsMode enum conversion ---

_TRS_MODE_TO_PROTO: dict[TrsMode, common_pb2.TimeRangeSelMode.ValueType] = {
    TrsMode.SUBSET: common_pb2.TRS_SUBSET,
    TrsMode.TO_HEAD: common_pb2.TRS_TO_HEAD,
    TrsMode.FROM_HEAD: common_pb2.TRS_FROM_HEAD,
}

_TRS_MODE_FROM_PROTO: dict[int, TrsMode] = {
    int(common_pb2.TRS_SUBSET): TrsMode.SUBSET,
    int(common_pb2.TRS_TO_HEAD): TrsMode.TO_HEAD,
    int(common_pb2.TRS_FROM_HEAD): TrsMode.FROM_HEAD,
}


def trs_mode_to_proto(mode: TrsMode) -> common_pb2.TimeRangeSelMode.ValueType:
    """Convert domain TrsMode to proto TimeRangeSelMode."""
    return _TRS_MODE_TO_PROTO[mode]


def trs_mode_from_proto(pb: int) -> TrsMode:
    """Convert proto TimeRangeSelMode int to domain TrsMode."""
    return _TRS_MODE_FROM_PROTO[pb]


def time_range_from_proto(
    sec_start: float,
    sec_end: float,
    ts_start: int,
    ts_end: int,
    fs: float,
    dur_sec: float,
    walltime: str,
    n: int,
) -> TimeRange:
    """Build a domain TimeRange from proto fields."""
    return TimeRange(
        sec=(sec_start, sec_end),
        timestamp=(ts_start, ts_end),
        fs=fs,
        dur_sec=dur_sec,
        walltime_str=walltime,
        n=n,
    )


def time_range_to_proto(tr: TimeRange) -> common_pb2.TimeRange:
    """Convert domain TimeRange to proto TimeRange."""
    return common_pb2.TimeRange(
        timestamp=list(tr.timestamp),
        fs=tr.fs,
    )
