from __future__ import annotations

import os
from unittest import mock
import unittest

from livekit import rtc

from app.providers.stt_fake import FakeSTT


def _audio_frame(samples_per_channel: int) -> rtc.AudioFrame:
    return rtc.AudioFrame(
        data=b"\x00\x00" * samples_per_channel,
        sample_rate=16000,
        num_channels=1,
        samples_per_channel=samples_per_channel,
    )


class FakeSTTTests(unittest.IsolatedAsyncioTestCase):
    async def test_fake_stt_returns_configured_transcripts_in_order(self) -> None:
        with mock.patch.dict(
            os.environ,
            {
                "FAKE_STT_TRANSCRIPTS": "primeira|segunda",
                "FAKE_STT_MODE": "repeat_last",
                "FAKE_STT_MIN_AUDIO_MS": "0",
            },
            clear=True,
        ):
            stt = FakeSTT(language="pt-BR")
            first = await stt.recognize([_audio_frame(3200)])
            second = await stt.recognize([_audio_frame(3200)])
            third = await stt.recognize([_audio_frame(3200)])

        self.assertEqual(first.alternatives[0].text, "primeira")
        self.assertEqual(second.alternatives[0].text, "segunda")
        self.assertEqual(third.alternatives[0].text, "segunda")

    async def test_fake_stt_skips_too_short_audio(self) -> None:
        with mock.patch.dict(
            os.environ,
            {
                "FAKE_STT_TRANSCRIPTS": "fala",
                "FAKE_STT_MIN_AUDIO_MS": "200",
            },
            clear=True,
        ):
            stt = FakeSTT(language="pt-BR")
            event = await stt.recognize([_audio_frame(800)])

        self.assertEqual(event.alternatives[0].text, "")


if __name__ == "__main__":
    unittest.main()
