"""Tests for analysis service client."""

from __future__ import annotations

import pytest
import respx

from melogenai.analysis.client import SUPPORTED_LANGUAGES
from melogenai.client import Melogen

from conftest import TEST_API_KEY, TEST_BASE_URL


class TestAnalysisSync:
    def test_analyze_with_image(self, mock_api: respx.MockRouter) -> None:
        sse_body = (
            "data: {\"content\": \"Key: C major. \"}\n\n"
            "data: {\"content\": \"Time: 4/4.\"}\n\n"
            "data: [DONE]\n\n"
        )
        mock_api.post("/api/analysis/analyze").respond(
            content=sse_body,
            content_type="text/event-stream",
        )

        client = Melogen(api_key=TEST_API_KEY, base_url=TEST_BASE_URL)
        result = client.analysis.analyze(image_url="https://example.com/score.png")

        assert result.status == "completed"
        assert "Key: C major" in result.analysis
        assert "Time: 4/4" in result.analysis

    def test_analyze_stream(self, mock_api: respx.MockRouter) -> None:
        sse_body = (
            "data: {\"content\": \"Part 1. \"}\n\n"
            "data: {\"content\": \"Part 2.\"}\n\n"
            "data: [DONE]\n\n"
        )
        mock_api.post("/api/analysis/analyze").respond(
            content=sse_body,
            content_type="text/event-stream",
        )

        client = Melogen(api_key=TEST_API_KEY, base_url=TEST_BASE_URL)
        chunks = list(client.analysis.analyze_stream(image_url="https://example.com/score.png"))

        assert len(chunks) == 2
        assert chunks[0] == "Part 1. "
        assert chunks[1] == "Part 2."

    def test_analyze_requires_input(self) -> None:
        client = Melogen(api_key=TEST_API_KEY, base_url=TEST_BASE_URL)
        with pytest.raises(ValueError, match="At least one of"):
            client.analysis.analyze()

    def test_analyze_rejects_bad_language(self) -> None:
        client = Melogen(api_key=TEST_API_KEY, base_url=TEST_BASE_URL)
        with pytest.raises(ValueError, match="Unsupported language"):
            client.analysis.analyze(image_url="https://example.com/score.png", language="xx")

    def test_supported_languages(self) -> None:
        assert "en" in SUPPORTED_LANGUAGES
        assert "zh" in SUPPORTED_LANGUAGES
        assert "ja" in SUPPORTED_LANGUAGES
