"""Data Transfer Objects for ASR.

These DTOs define the data structures used by ASR components.
"""

from dataclasses import dataclass, field
from enum import Enum


def _timing_error(label: str, end: float, start: float) -> str:
    """Format timing validation error message."""
    return f"{label} end ({end}) < start ({start})"


@dataclass(frozen=True)
class WordTiming:
    """Word-level timing information."""

    word: str
    start: float  # Start time in seconds
    end: float  # End time in seconds
    probability: float  # Confidence (0.0-1.0)

    def __post_init__(self) -> None:
        """Validate timing data."""
        if self.end < self.start:
            raise ValueError(_timing_error("Word", self.end, self.start))
        if not 0.0 <= self.probability <= 1.0:
            raise ValueError(f"Probability must be 0.0-1.0, got {self.probability}")


@dataclass(frozen=True)
class AsrResult:
    """ASR transcription result for a segment."""

    text: str
    start: float  # Start time in seconds
    end: float  # End time in seconds
    words: tuple[WordTiming, ...] = field(default_factory=tuple)
    language: str = "en"
    language_probability: float = 1.0
    avg_logprob: float = 0.0
    no_speech_prob: float = 0.0

    def __post_init__(self) -> None:
        """Validate result data."""
        if self.end < self.start:
            raise ValueError(_timing_error("Segment", self.end, self.start))

    @property
    def duration(self) -> float:
        """Duration of the segment in seconds."""
        return self.end - self.start


@dataclass
class PartialUpdate:
    """Unstable partial transcript (may be replaced)."""

    text: str
    start: float
    end: float

    def __post_init__(self) -> None:
        """Validate partial data."""
        if self.end < self.start:
            raise ValueError(_timing_error("Partial", self.end, self.start))


class VadEventType(Enum):
    """Voice Activity Detection event types."""

    SPEECH_START = "speech_start"
    SPEECH_END = "speech_end"


@dataclass(frozen=True)
class VadEvent:
    """Voice Activity Detection event.

    Represents a speech/silence transition detected by VAD.
    """

    event_type: VadEventType
    timestamp: float  # Seconds from stream start
    confidence: float = 1.0  # Detection confidence (0.0-1.0)

    def __post_init__(self) -> None:
        """Validate event data."""
        if self.timestamp < 0:
            raise ValueError(f"Timestamp must be non-negative, got {self.timestamp}")
        if not 0.0 <= self.confidence <= 1.0:
            raise ValueError(f"Confidence must be 0.0-1.0, got {self.confidence}")
