"""Tests for _streaming module."""

from __future__ import annotations

import base64

from murmr._audio import WAV_HEADER_SIZE
from murmr._streaming import _parse_sse_line
from murmr._types import AudioStreamChunk


class TestParseSSELine:
    def test_valid_data_line(self) -> None:
        audio_b64 = base64.b64encode(b"\x00\x01\x02\x03").decode()
        line = f'data: {{"audio": "{audio_b64}", "chunk_index": 0}}'
        chunk = _parse_sse_line(line)
        assert chunk is not None
        assert isinstance(chunk, AudioStreamChunk)
        assert chunk.chunk_index == 0
        assert chunk.audio == audio_b64

    def test_done_event(self) -> None:
        line = 'data: {"done": true, "total_chunks": 5, "total_time_ms": 1234.5}'
        chunk = _parse_sse_line(line)
        assert chunk is not None
        assert chunk.done is True
        assert chunk.total_chunks == 5

    def test_empty_line(self) -> None:
        assert _parse_sse_line("") is None

    def test_comment_line(self) -> None:
        assert _parse_sse_line(": keepalive") is None

    def test_non_data_line(self) -> None:
        assert _parse_sse_line("event: message") is None

    def test_malformed_json(self) -> None:
        assert _parse_sse_line("data: {not json}") is None

    def test_audio_bytes_decoding(self) -> None:
        pcm = b"\x00\x01" * 100
        b64 = base64.b64encode(pcm).decode()
        line = f'data: {{"audio": "{b64}"}}'
        chunk = _parse_sse_line(line)
        assert chunk is not None
        assert chunk.audio_bytes == pcm

    def test_chunk_field_alias(self) -> None:
        pcm = b"\xff\xfe" * 50
        b64 = base64.b64encode(pcm).decode()
        line = f'data: {{"chunk": "{b64}"}}'
        chunk = _parse_sse_line(line)
        assert chunk is not None
        assert chunk.audio_bytes == pcm

    def test_error_event(self) -> None:
        line = 'data: {"error": "server overloaded"}'
        chunk = _parse_sse_line(line)
        assert chunk is not None
        assert chunk.error == "server overloaded"

    def test_empty_audio_bytes(self) -> None:
        line = 'data: {"done": true}'
        chunk = _parse_sse_line(line)
        assert chunk is not None
        assert chunk.audio_bytes == b""


class TestCollectStreamAsWav:
    """Integration tests that verify WAV collection from mock SSE lines.

    The actual httpx response mocking is covered in resource tests (test_voices.py).
    Here we test the WAV output structure.
    """

    def test_wav_header_present(self) -> None:
        """Verify that collected WAV data starts with a valid RIFF header."""
        from murmr._audio import create_wav_header

        pcm = b"\x00\x01" * 500
        wav = create_wav_header(len(pcm)) + pcm
        assert wav[:4] == b"RIFF"
        assert wav[8:12] == b"WAVE"
        assert len(wav) == WAV_HEADER_SIZE + len(pcm)
