"""Segment entity for transcript segments."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING

from noteflow.domain.utils.validation import validate_time_range

if TYPE_CHECKING:
    from noteflow.domain.value_objects import MeetingId


@dataclass
class WordTiming:
    """Word-level timing information within a segment."""

    word: str
    start_time: float
    end_time: float
    probability: float

    def __post_init__(self) -> None:
        """Validate word timing."""
        validate_time_range(self.start_time, self.end_time)
        if not 0.0 <= self.probability <= 1.0:
            raise ValueError(f"probability must be between 0 and 1, got {self.probability}")


@dataclass
class Segment:
    """Transcript segment entity.

    Represents a finalized segment of transcribed speech with optional
    word-level timing information and language detection.
    """

    segment_id: int
    text: str
    start_time: float
    end_time: float
    meeting_id: MeetingId | None = None
    words: list[WordTiming] = field(default_factory=list)
    language: str = "en"
    language_confidence: float = 0.0
    avg_logprob: float = 0.0
    no_speech_prob: float = 0.0
    embedding: list[float] | None = None

    # Speaker diarization (populated by diarization engine)
    speaker_id: str | None = None
    speaker_confidence: float = 0.0

    # Database primary key (set after persistence)
    db_id: int | None = None

    def __post_init__(self) -> None:
        """Validate segment data."""
        validate_time_range(self.start_time, self.end_time)
        if self.segment_id < 0:
            raise ValueError(f"segment_id must be non-negative, got {self.segment_id}")

    @property
    def duration(self) -> float:
        """Segment duration in seconds."""
        return self.end_time - self.start_time

    @property
    def word_count(self) -> int:
        """Number of words in segment."""
        return len(self.words) if self.words else len(self.text.split())

    def has_embedding(self) -> bool:
        """Check if segment has a computed embedding."""
        return self.embedding is not None and len(self.embedding) > 0
