"""MCP Resource for Midjourney generation statistics."""

from typing import Any

from ..client import ImagineAPIClient
from ..models import ImageStatus


async def get_stats() -> dict[str, Any]:
    """Fetch generation statistics.

    Returns aggregated statistics across all image generations including
    counts by status and overall totals.

    Returns:
        Dictionary containing statistics:
        - total: Total number of generations
        - by_status: Count breakdown by status
            - pending: Number of pending generations
            - in_progress: Number of in-progress generations
            - completed: Number of completed generations
            - failed: Number of failed generations
        - completion_rate: Percentage of completed generations (0.0-100.0)

    Raises:
        ImagineAPIError: If API call fails
    """
    async with ImagineAPIClient() as client:
        response = await client.list_images(limit=100)

    status_counts = {
        "pending": 0,
        "in_progress": 0,
        "completed": 0,
        "failed": 0,
    }

    for image in response.data:
        if image.status == ImageStatus.PENDING:
            status_counts["pending"] += 1
        elif image.status == ImageStatus.IN_PROGRESS:
            status_counts["in_progress"] += 1
        elif image.status == ImageStatus.COMPLETED:
            status_counts["completed"] += 1
        elif image.status == ImageStatus.FAILED:
            status_counts["failed"] += 1

    total = len(response.data)
    completion_rate = (status_counts["completed"] / total * 100) if total > 0 else 0.0

    return {
        "total": total,
        "by_status": status_counts,
        "completion_rate": round(completion_rate, 2),
    }
