"""Trigger control converters — domain ↔ proto."""

from __future__ import annotations

from typing import TYPE_CHECKING

from radiens_core._converters._enums import (
    port_from_proto,
    port_to_proto,
    trigger_channel_from_proto,
    trigger_channel_to_proto,
)
from radiens_core.models.status import (
    ManualStimTriggerRequest,
    ManualStimTriggerToggleRequest,
    SetTriggerStateRequest,
    TriggerState,
)

if TYPE_CHECKING:
    from radiens_core._generated import allegoserver_pb2


def set_trigger_state_request_to_proto(
    request: SetTriggerStateRequest,
) -> allegoserver_pb2.SetTriggerRequest:
    """Convert ``SetTriggerStateRequest`` domain model → proto message."""
    from radiens_core._generated import allegoserver_pb2

    return allegoserver_pb2.SetTriggerRequest(
        channel=trigger_channel_to_proto(request.channel),
        enabled=request.enabled,
        port=port_to_proto(request.port),
    )


def trigger_state_from_proto(
    response: allegoserver_pb2.TriggerState,
) -> TriggerState:
    """Convert ``TriggerState`` proto response → domain model."""
    return TriggerState(
        enabled_channels=[
            trigger_channel_from_proto(channel) for channel in response.enabledChannels
        ],
        ports=[port_from_proto(port) for port in response.ports],
    )


def manual_stim_trigger_request_to_proto(
    request: ManualStimTriggerRequest,
) -> allegoserver_pb2.ManualStimTriggerRequest:
    """Convert ``ManualStimTriggerRequest`` domain model → proto message."""
    from radiens_core._generated import allegoserver_pb2

    # StimKeypressIndex is 1-indexed (1-8); proto expects 0-indexed (0-7)
    return allegoserver_pb2.ManualStimTriggerRequest(
        trigger=request.trigger - 1,
        triggerOn=request.trigger_on,
    )


def manual_stim_trigger_toggle_request_to_proto(
    request: ManualStimTriggerToggleRequest,
) -> allegoserver_pb2.ManualStimTriggerToggleRequest:
    """Convert ``ManualStimTriggerToggleRequest`` domain model → proto message."""
    from radiens_core._generated import allegoserver_pb2

    # StimKeypressIndex is 1-indexed (1-8); proto expects 0-indexed (0-7)
    return allegoserver_pb2.ManualStimTriggerToggleRequest(
        trigger=request.trigger - 1,
    )
