"""Meeting operations mixin for NoteFlowClient."""

from __future__ import annotations

from typing import TYPE_CHECKING

import grpc

from noteflow.grpc._client_mixins.converters import proto_to_meeting_info
from noteflow.grpc._types import MeetingInfo, TranscriptSegment
from noteflow.grpc.proto import noteflow_pb2
from noteflow.infrastructure.logging import get_logger

if TYPE_CHECKING:
    from noteflow.grpc._client_mixins.protocols import ClientHost

logger = get_logger(__name__)


class MeetingClientMixin:
    """Mixin providing meeting operations for NoteFlowClient."""

    def create_meeting(self: ClientHost, title: str = "") -> MeetingInfo | None:
        """Create a new meeting.

        Args:
            title: Optional meeting title.

        Returns:
            MeetingInfo or None if request fails.
        """
        if not self.stub:
            return None

        try:
            request = noteflow_pb2.CreateMeetingRequest(title=title)
            response = self.stub.CreateMeeting(request)
            return proto_to_meeting_info(response)
        except grpc.RpcError as e:
            logger.error("Failed to create meeting: %s", e)
            return None

    def stop_meeting(self: ClientHost, meeting_id: str) -> MeetingInfo | None:
        """Stop a meeting.

        Args:
            meeting_id: Meeting ID.

        Returns:
            Updated MeetingInfo or None if request fails.
        """
        if not self.stub:
            return None

        try:
            request = noteflow_pb2.StopMeetingRequest(meeting_id=meeting_id)
            response = self.stub.StopMeeting(request)
            return proto_to_meeting_info(response)
        except grpc.RpcError as e:
            logger.error("Failed to stop meeting: %s", e)
            return None

    def get_meeting(self: ClientHost, meeting_id: str) -> MeetingInfo | None:
        """Get meeting details.

        Args:
            meeting_id: Meeting ID.

        Returns:
            MeetingInfo or None if not found.
        """
        if not self.stub:
            return None

        try:
            request = noteflow_pb2.GetMeetingRequest(
                meeting_id=meeting_id,
                include_segments=False,
                include_summary=False,
            )
            response = self.stub.GetMeeting(request)
            return proto_to_meeting_info(response)
        except grpc.RpcError as e:
            logger.error("Failed to get meeting: %s", e)
            return None

    def get_meeting_segments(self: ClientHost, meeting_id: str) -> list[TranscriptSegment]:
        """Retrieve transcript segments for a meeting.

        Args:
            meeting_id: Meeting ID.

        Returns:
            List of TranscriptSegment or empty list if not found.
        """
        if not self.stub:
            return []

        try:
            request = noteflow_pb2.GetMeetingRequest(
                meeting_id=meeting_id,
                include_segments=True,
                include_summary=False,
            )
            response = self.stub.GetMeeting(request)
            segments = response.segments
            return [
                TranscriptSegment(
                    segment_id=seg.segment_id,
                    text=seg.text,
                    start_time=seg.start_time,
                    end_time=seg.end_time,
                    language=seg.language,
                    is_final=True,
                    speaker_id=seg.speaker_id,
                    speaker_confidence=seg.speaker_confidence,
                )
                for seg in segments
            ]
        except grpc.RpcError as e:
            logger.error("Failed to get meeting segments: %s", e)
            return []

    def list_meetings(self: ClientHost, limit: int = 20) -> list[MeetingInfo]:
        """List recent meetings.

        Args:
            limit: Maximum number to return.

        Returns:
            List of MeetingInfo.
        """
        if not self.stub:
            return []

        try:
            request = noteflow_pb2.ListMeetingsRequest(
                limit=limit,
                sort_order=noteflow_pb2.SORT_ORDER_CREATED_DESC,
            )
            response = self.stub.ListMeetings(request)
            meetings = response.meetings
            return [proto_to_meeting_info(m) for m in meetings]
        except grpc.RpcError as e:
            logger.error("Failed to list meetings: %s", e)
            return []
