"""Converters for impedance measurements."""

from __future__ import annotations

from typing import TYPE_CHECKING, cast

from radiens_core._generated import common_pb2, datasource_pb2
from radiens_core.models.impedance import Impedance, ImpedanceValue

if TYPE_CHECKING:
    from radiens_core._generated.datasource_pb2 import Impedance as ProtoImpedance
    from radiens_core.models.ports import Port


def port_to_proto(port: Port) -> common_pb2.Port.ValueType:
    """Convert domain Port to proto Port value."""
    # models.ports.Port is an IntEnum matching proto values
    return cast("common_pb2.Port.ValueType", int(port))


def impedance_from_proto(proto: ProtoImpedance) -> Impedance:
    """Convert proto Impedance to domain Impedance model."""
    return Impedance(
        measurements=[
            ImpedanceValue(
                ntv_chan_idx=val.ntvChanIdx,
                magnitude_ohm=val.zMag,
                phase_deg=val.zPhase,
            )
            for val in proto.impedances
        ]
    )


def impedance_request_to_proto(port: Port) -> datasource_pb2.ImpedanceRequest:
    """Create proto ImpedanceRequest from domain Port."""
    return datasource_pb2.ImpedanceRequest(port=port_to_proto(port))
