"""MCP Resources for Midjourney image generations."""

from typing import Any

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


async def get_generations(status: str | None = None) -> list[dict[str, Any]]:
    """Fetch all image generations with optional status filter.

    Args:
        status: Filter by status (pending, in-progress, completed, failed).
                If None, returns all generations.

    Returns:
        List of image generation records with fields:
        - id: Image ID
        - prompt: Generation prompt (truncated to 100 chars)
        - status: Current status
        - url: Completed image URL (only when completed)
        - upscaled_urls: List of upscaled URLs (only when completed)
        - date_created: Creation timestamp (if available)

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

    generations = []
    for image in response.data:
        item: dict[str, Any] = {
            "id": image.id,
            "prompt": image.prompt[:100] + "..." if len(image.prompt) > 100 else image.prompt,
            "status": image.status.value,
        }

        if image.status == ImageStatus.COMPLETED:
            item["url"] = image.result or image.url
            if image.upscaled_urls:
                item["upscaled_urls"] = image.upscaled_urls

        if image.date_created:
            item["date_created"] = image.date_created

        generations.append(item)

    return generations


async def get_generation_by_id(image_id: str) -> dict[str, Any]:
    """Fetch detailed information for a specific image generation.

    Args:
        image_id: The ID of the image to retrieve.

    Returns:
        Detailed image generation record with fields:
        - id: Image ID
        - prompt: Full generation prompt
        - status: Current status
        - progress: Progress percentage (only when in-progress)
        - url: Completed image URL (only when completed)
        - upscaled_urls: List of upscaled URLs (only when completed)
        - ref: User reference ID (if provided)
        - error: Error message (only when failed)
        - date_created: Creation timestamp (if available)

    Raises:
        ImagineAPIError: If API call fails or image not found
    """
    async with ImagineAPIClient() as client:
        image = await client.get_image(image_id)

    result: dict[str, Any] = {
        "id": image.id,
        "prompt": image.prompt,
        "status": image.status.value,
    }

    if image.status == ImageStatus.IN_PROGRESS and image.progress is not None:
        result["progress"] = image.progress

    if image.status == ImageStatus.COMPLETED:
        result["url"] = image.result or image.url
        if image.upscaled_urls:
            result["upscaled_urls"] = image.upscaled_urls

    if image.status == ImageStatus.FAILED and image.error:
        result["error"] = image.error

    if image.ref:
        result["ref"] = image.ref

    if image.date_created:
        result["date_created"] = image.date_created

    return result
