from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class Token:
    source_id: str
    source_order: int
    token_id: str
    raw_text: str
    normalized: str
    start_ms: int
    end_ms: int
    sentence_end: bool


@dataclass(frozen=True)
class Passage:
    passage_id: str
    source_id: str
    source_order: int
    tokens: tuple[Token, ...]

    @property
    def normalized_tokens(self) -> tuple[Token, ...]:
        return tuple(token for token in self.tokens if token.normalized)

    @property
    def normalized(self) -> tuple[str, ...]:
        return tuple(token.normalized for token in self.normalized_tokens)

    def token_for_normalized_index(self, index: int) -> Token:
        normalized_tokens = self.normalized_tokens
        if not normalized_tokens:
            raise IndexError("Passage has no normalized tokens.")
        return normalized_tokens[min(max(index, 0), len(normalized_tokens) - 1)]

    @property
    def start_ms(self) -> int:
        return self.tokens[0].start_ms

    @property
    def end_ms(self) -> int:
        return self.tokens[-1].end_ms

    @property
    def text(self) -> str:
        return " ".join(token.raw_text for token in self.tokens)
