"""Tests for CLI commands."""

from __future__ import annotations

import pytest
import respx
from click.testing import CliRunner
from httpx import Response

from melogenai.cli.main import cli

from conftest import TEST_API_KEY, TEST_BASE_URL


@pytest.fixture
def runner():
    return CliRunner()


class TestCLI:
    def test_version(self, runner: CliRunner) -> None:
        result = runner.invoke(cli, ["--version"])
        assert result.exit_code == 0
        assert "melogen" in result.output

    def test_sheet2midi_command(self, runner: CliRunner, mock_api: respx.MockRouter) -> None:
        mock_api.post("/api/sheet2midi/convert").respond(
            json={"task_id": "task_001", "status": "pending"}
        )
        mock_api.get("/api/sheet2midi/tasks/task_001").mock(
            side_effect=[
                Response(
                    200,
                    json={
                        "task": {"status": "completed"},
                        "download_urls": {"midi": "https://dl.example.com/out.midi"},
                    },
                ),
            ]
        )

        result = runner.invoke(
            cli,
            ["--api-key", TEST_API_KEY, "--base-url", TEST_BASE_URL, "sheet2midi", "https://example.com/score.pdf"],
        )

        assert result.exit_code == 0
        assert "completed" in result.output.lower() or "midi" in result.output.lower()

    def test_music2midi_command(self, runner: CliRunner, mock_api: respx.MockRouter) -> None:
        mock_api.post("/api/music2midi/convert").respond(
            json={"task_id": "task_101", "status": "pending"}
        )
        mock_api.get("/api/music2midi/tasks/task_101").mock(
            side_effect=[
                Response(
                    200,
                    json={
                        "task": {"status": "completed"},
                        "download_urls": {"midi": "https://dl.example.com/out.midi"},
                    },
                ),
            ]
        )

        result = runner.invoke(
            cli,
            ["--api-key", TEST_API_KEY, "--base-url", TEST_BASE_URL, "music2midi", "https://example.com/song.mp3"],
        )

        assert result.exit_code == 0

    def test_analysis_requires_input(self, runner: CliRunner) -> None:
        result = runner.invoke(
            cli,
            ["--api-key", TEST_API_KEY, "--base-url", TEST_BASE_URL, "analysis"],
        )

        assert result.exit_code != 0
        assert "provide at least one" in result.output.lower()

    def test_auth_verify(self, runner: CliRunner, mock_api: respx.MockRouter) -> None:
        result = runner.invoke(
            cli,
            ["--api-key", TEST_API_KEY, "--base-url", TEST_BASE_URL, "auth", "verify"],
        )

        assert result.exit_code == 0
        assert "valid" in result.output.lower()
