from __future__ import annotations

import pytest

from core.agent.multimodal import AttachmentInput, MultimodalProcessor
from core.agent.storage_adapter import StorageAdapter
from core.agent.tools.asr_fun_asr import FunASRTool


def test_multimodal_processes_audio_and_builds_attachment_context() -> None:
    storage = StorageAdapter(bucket="agent-chat-attachments")

    def fake_transcribe(*, audio_bytes: bytes, filename: str) -> dict[str, str]:
        assert audio_bytes == b"audio"
        assert filename == "voice.wav"
        return {"text": "hello world", "request_id": "req-1"}

    processor = MultimodalProcessor(
        storage=storage,
        asr_tool=FunASRTool(transcribe_callable=fake_transcribe),
        max_file_size_mb=1,
    )

    result = processor.process(
        user_id="u1",
        session_id="s1",
        message_seq=4,
        attachments=[
            AttachmentInput(
                filename="voice.wav",
                mime_type="audio/wav",
                content=b"audio",
            )
        ],
    )

    assert len(result.attachments) == 1
    metadata = result.attachments[0]
    assert (
        metadata["object_path"]
        == "agent-chat/u1/s1/4/6ed8919ce20490a5e3ad8630a4fab69475297abd07db73918dd5f36fcfaeb11b.wav"
    )
    assert metadata["mime_type"] == "audio/wav"
    assert result.preview_texts == ["hello world"]


def test_multimodal_rejects_unsupported_mime_type() -> None:
    storage = StorageAdapter(bucket="agent-chat-attachments")
    processor = MultimodalProcessor(
        storage=storage, asr_tool=FunASRTool(lambda **_: {})
    )

    with pytest.raises(ValueError):
        processor.process(
            user_id="u1",
            session_id="s1",
            message_seq=1,
            attachments=[
                AttachmentInput(
                    filename="malware.exe",
                    mime_type="application/octet-stream",
                    content=b"bad",
                )
            ],
        )


def test_multimodal_rejects_attachment_over_max_size() -> None:
    storage = StorageAdapter(bucket="agent-chat-attachments")
    processor = MultimodalProcessor(
        storage=storage,
        asr_tool=FunASRTool(lambda **_: {}),
        max_file_size_mb=1,
    )

    oversized = b"x" * (1024 * 1024 + 1)
    with pytest.raises(ValueError):
        processor.process(
            user_id="u1",
            session_id="s1",
            message_seq=1,
            attachments=[
                AttachmentInput(
                    filename="big.wav",
                    mime_type="audio/wav",
                    content=oversized,
                )
            ],
        )
