"""Internal reporter for simulation results collection."""

from voiceground.events import VoicegroundEvent
from voiceground.reporters.base import BaseReporter
from voiceground.simulation.results import VoicegroundTranscriptEntry


class TranscriptCollector:
    """Collects transcript entries from events."""

    def __init__(self):
        self.entries: list[VoicegroundTranscriptEntry] = []
        self._start_time: float | None = None

    def on_event(self, event: VoicegroundEvent) -> None:
        """Process an event and extract transcript if available.

        Note: This runs on the SIMULATOR pipeline, so roles are inverted:
        - STT processes what the BOT says (bot's audio → simulator's ears)
        - LLM generates what the simulated USER says
        """
        if self._start_time is None:
            self._start_time = event.timestamp

        # STT end = bot's speech transcribed by simulator
        if event.category.value == "stt" and event.type.value == "end":
            text = event.data.get("text", "")
            if text:
                self.entries.append(
                    VoicegroundTranscriptEntry(
                        role="bot",  # Bot's speech heard by simulator
                        text=text,
                        timestamp=event.timestamp - (self._start_time or 0),
                    )
                )

        # LLM end = simulated user's response
        if event.category.value == "llm" and event.type.value == "end":
            text = event.data.get("text", "")
            if text:
                self.entries.append(
                    VoicegroundTranscriptEntry(
                        role="user",  # Simulated user's speech
                        text=text,
                        timestamp=event.timestamp - (self._start_time or 0),
                    )
                )


class SimulationReporter(BaseReporter):
    """Reporter that collects events and transcript for simulation results."""

    def __init__(self):
        self.events: list[VoicegroundEvent] = []
        self.transcript_collector = TranscriptCollector()
        self._conversation_id: str = ""

    async def on_start(self, conversation_id: str) -> None:
        """Handle simulation start."""
        self._conversation_id = conversation_id

    async def on_event(self, event: VoicegroundEvent) -> None:
        """Collect events and build transcript."""
        self.events.append(event)
        self.transcript_collector.on_event(event)

    async def on_end(self) -> None:
        """Handle simulation end."""
        pass
