"""Tests for stats resource."""

import httpx
import pytest
from pytest_httpx import HTTPXMock

from midjourney_proxy_mcp.resources import get_stats

pytestmark = pytest.mark.asyncio


class TestGetStats:
    """Tests for get_stats function."""

    async def test_get_stats_mixed_statuses(self, httpx_mock: HTTPXMock) -> None:
        """Calculate statistics from mixed status generations."""
        httpx_mock.add_response(
            method="GET",
            url=httpx.URL(
                "https://cl.imagineapi.dev/items/images",
                params={"limit": "100", "offset": "0"},
            ),
            json={
                "data": [
                    {"id": "1", "prompt": "p1", "status": "pending"},
                    {"id": "2", "prompt": "p2", "status": "pending"},
                    {"id": "3", "prompt": "p3", "status": "in-progress"},
                    {"id": "4", "prompt": "p4", "status": "completed"},
                    {"id": "5", "prompt": "p5", "status": "completed"},
                    {"id": "6", "prompt": "p6", "status": "completed"},
                    {"id": "7", "prompt": "p7", "status": "completed"},
                    {"id": "8", "prompt": "p8", "status": "failed"},
                ],
                "meta": {"total": 8},
            },
        )

        result = await get_stats()

        assert result["total"] == 8
        assert result["by_status"]["pending"] == 2
        assert result["by_status"]["in_progress"] == 1
        assert result["by_status"]["completed"] == 4
        assert result["by_status"]["failed"] == 1
        assert result["completion_rate"] == 50.0  # 4/8 * 100

    async def test_get_stats_all_completed(self, httpx_mock: HTTPXMock) -> None:
        """Calculate statistics when all generations are completed."""
        httpx_mock.add_response(
            method="GET",
            url=httpx.URL(
                "https://cl.imagineapi.dev/items/images",
                params={"limit": "100", "offset": "0"},
            ),
            json={
                "data": [
                    {"id": "1", "prompt": "p1", "status": "completed"},
                    {"id": "2", "prompt": "p2", "status": "completed"},
                    {"id": "3", "prompt": "p3", "status": "completed"},
                ],
                "meta": {"total": 3},
            },
        )

        result = await get_stats()

        assert result["total"] == 3
        assert result["by_status"]["completed"] == 3
        assert result["by_status"]["pending"] == 0
        assert result["by_status"]["in_progress"] == 0
        assert result["by_status"]["failed"] == 0
        assert result["completion_rate"] == 100.0

    async def test_get_stats_all_pending(self, httpx_mock: HTTPXMock) -> None:
        """Calculate statistics when all generations are pending."""
        httpx_mock.add_response(
            method="GET",
            url=httpx.URL(
                "https://cl.imagineapi.dev/items/images",
                params={"limit": "100", "offset": "0"},
            ),
            json={
                "data": [
                    {"id": "1", "prompt": "p1", "status": "pending"},
                    {"id": "2", "prompt": "p2", "status": "pending"},
                ],
                "meta": {"total": 2},
            },
        )

        result = await get_stats()

        assert result["total"] == 2
        assert result["by_status"]["pending"] == 2
        assert result["by_status"]["completed"] == 0
        assert result["completion_rate"] == 0.0

    async def test_get_stats_empty(self, httpx_mock: HTTPXMock) -> None:
        """Calculate statistics when no generations exist."""
        httpx_mock.add_response(
            method="GET",
            url=httpx.URL(
                "https://cl.imagineapi.dev/items/images",
                params={"limit": "100", "offset": "0"},
            ),
            json={"data": [], "meta": {"total": 0}},
        )

        result = await get_stats()

        assert result["total"] == 0
        assert result["by_status"]["pending"] == 0
        assert result["by_status"]["in_progress"] == 0
        assert result["by_status"]["completed"] == 0
        assert result["by_status"]["failed"] == 0
        assert result["completion_rate"] == 0.0

    async def test_get_stats_completion_rate_precision(self, httpx_mock: HTTPXMock) -> None:
        """Completion rate is rounded to 2 decimal places."""
        httpx_mock.add_response(
            method="GET",
            url=httpx.URL(
                "https://cl.imagineapi.dev/items/images",
                params={"limit": "100", "offset": "0"},
            ),
            json={
                "data": [
                    {"id": "1", "prompt": "p1", "status": "completed"},
                    {"id": "2", "prompt": "p2", "status": "pending"},
                    {"id": "3", "prompt": "p3", "status": "pending"},
                ],
                "meta": {"total": 3},
            },
        )

        result = await get_stats()

        # 1/3 = 0.333... -> 33.33%
        assert result["completion_rate"] == 33.33


@pytest.mark.integration
class TestStatsResourceIntegration:
    """Integration tests for stats resource (requires IMAGINEAPI_TOKEN)."""

    async def test_get_stats_real_api(self) -> None:
        """Fetch stats from real API."""
        result = await get_stats()

        assert "total" in result
        assert "by_status" in result
        assert "completion_rate" in result
        assert isinstance(result["total"], int)
        assert isinstance(result["by_status"], dict)
        assert isinstance(result["completion_rate"], float)
