"""ID parsing helpers for gRPC converters."""

from __future__ import annotations

from typing import TYPE_CHECKING
from uuid import UUID

from noteflow.domain.value_objects import AnnotationId, MeetingId

if TYPE_CHECKING:
    from ..errors import AbortableContext as _AbortableContext


def parse_meeting_id(meeting_id_str: str) -> MeetingId:
    """Parse string to MeetingId.

    Consolidates the repeated `MeetingId(UUID(request.meeting_id))` pattern.

    Args:
        meeting_id_str: Meeting ID as string (UUID format).

    Returns:
        MeetingId value object.
    """
    return MeetingId(UUID(meeting_id_str))


async def parse_meeting_id_or_abort(
    meeting_id_str: str,
    context: _AbortableContext,
) -> MeetingId:
    """Parse meeting ID or abort with INVALID_ARGUMENT.

    Consolidates the repeated try/except pattern for meeting ID parsing.

    Args:
        meeting_id_str: Meeting ID as string (UUID format).
        context: gRPC servicer context with abort capability.

    Returns:
        MeetingId value object.

    Raises:
        Aborts RPC with INVALID_ARGUMENT if parsing fails.
    """
    from ..errors import abort_invalid_argument

    try:
        return MeetingId(UUID(meeting_id_str))
    except ValueError:
        await abort_invalid_argument(context, "Invalid meeting_id")


def parse_meeting_id_or_none(meeting_id_str: str) -> MeetingId | None:
    """Parse string to MeetingId, returning None on failure.

    Use this for internal methods that log and return rather than abort.

    Args:
        meeting_id_str: Meeting ID as string (UUID format).

    Returns:
        MeetingId value object, or None if parsing fails.
    """
    try:
        return MeetingId(UUID(meeting_id_str))
    except ValueError:
        return None


def parse_annotation_id(annotation_id_str: str) -> AnnotationId:
    """Parse string to AnnotationId.

    Args:
        annotation_id_str: Annotation ID as string (UUID format).

    Returns:
        AnnotationId value object.
    """
    return AnnotationId(UUID(annotation_id_str))
