"""Per-meeting streaming state consolidation.

Consolidate 13+ per-meeting dictionaries into a single dataclass for O(1) access
instead of 13+ dict lookups per audio chunk.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from noteflow.infrastructure.asr import Segmenter, StreamingVad
    from noteflow.infrastructure.audio.partial_buffer import PartialAudioBuffer
    from noteflow.infrastructure.diarization import DiarizationSession, SpeakerTurn


@dataclass
class MeetingStreamState:
    """Consolidated per-meeting streaming state.

    Groups all per-meeting state into a single object for efficient access.
    Single dict lookup replaces 13+ separate lookups per audio chunk.
    """

    # Core streaming components
    vad: StreamingVad
    segmenter: Segmenter
    partial_buffer: PartialAudioBuffer

    # Stream format (sample_rate, channels)
    sample_rate: int = 16000
    channels: int = 1

    # Segment tracking
    next_segment_id: int = 0
    was_speaking: bool = False

    # Partial transcription state
    last_partial_time: float = 0.0
    last_partial_text: str = ""

    # Diarization state
    diarization_session: DiarizationSession | None = None
    diarization_turns: list[SpeakerTurn] = field(default_factory=list)
    diarization_stream_time: float = 0.0
    diarization_streaming_failed: bool = False

    # Stream lifecycle flags
    is_active: bool = True
    stop_requested: bool = False
    audio_write_failed: bool = False

    def increment_segment_id(self) -> int:
        """Get current segment ID and increment counter.

        Returns:
            Current segment ID before increment.
        """
        current = self.next_segment_id
        self.next_segment_id += 1
        return current

    def clear_partial_state(self, current_time: float) -> None:
        """Reset partial transcription state.

        Args:
            current_time: Current timestamp to set as last partial time.
        """
        self.partial_buffer.clear()
        self.last_partial_text = ""
        self.last_partial_time = current_time

    def clear_diarization_state(self) -> None:
        """Reset diarization state for new stream or on failure."""
        self.diarization_turns.clear()
        self.diarization_stream_time = 0.0
