"""Document and certificate inspection tools."""

from __future__ import annotations

from typing import Any

from mcp.types import ToolAnnotations

from mcp_eregistrations_ds.ds_client import (
    DSClient,
    DSClientError,
    translate_error,
)
from mcp_eregistrations_ds.server import mcp


def _summarize_document(item: dict[str, Any]) -> dict[str, Any]:
    """Build a summary dict for a document list item."""
    return {
        "id": item.get("id"),
        "document_name": item.get("document_name"),
        "file_name": item.get("file_name"),
        "file_type": item.get("file_type"),
        "document_id": item.get("document_id"),
        "created_at": item.get("created_at"),
    }


def _summarize_certificate(item: dict[str, Any]) -> dict[str, Any]:
    """Build a summary dict for a certificate list item."""
    return {
        "id": item.get("id"),
        "document_name": item.get("document_name"),
        "file_name": item.get("file_name"),
        "file_type": item.get("file_type"),
        "document_id": item.get("document_id"),
        "created_at": item.get("created_at"),
        "expires_at": item.get("expires_at"),
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def document_list(
    search_phrase: str | None = None,
    order_by: str = "-created_at",
    page: int = 1,
    instance: str | None = None,
) -> dict[str, Any]:
    """List uploaded documents.

    Args:
        search_phrase: Search by document name or ID.
        order_by: Sort field (default: -created_at). Prefix with - for descending.
        page: Page number (default: 1, 8 items per page).
        instance: Instance profile name.

    Returns:
        dict with items (summary fields only), count, page, page_size, has_next.
    """
    params: dict[str, Any] = {"page": page, "order_by": order_by}
    if search_phrase:
        params["search_phrase"] = search_phrase

    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get_paginated("/backend/documents/user", params=params)
    except DSClientError as e:
        raise translate_error(e, resource_type="document") from e

    data["items"] = [_summarize_document(item) for item in data.get("items", [])]
    return data


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def certificate_list(
    search_phrase: str | None = None,
    order_by: str = "-created_at",
    page: int = 1,
    instance: str | None = None,
) -> dict[str, Any]:
    """List issued certificates.

    Args:
        search_phrase: Search by certificate name or ID.
        order_by: Sort field (default: -created_at).
        page: Page number (default: 1, 8 items per page).
        instance: Instance profile name.

    Returns:
        dict with items (summary fields only), count, page, page_size, has_next.
    """
    params: dict[str, Any] = {"page": page, "order_by": order_by}
    if search_phrase:
        params["search_phrase"] = search_phrase

    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get_paginated(
                "/backend/certificates/user", params=params
            )
    except DSClientError as e:
        raise translate_error(e, resource_type="certificate") from e

    data["items"] = [_summarize_certificate(item) for item in data.get("items", [])]
    return data


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def certificate_get(
    file_id: str | None = None,
    process_id: str | None = None,
    instance: str | None = None,
) -> dict[str, Any]:
    """Get certificates for a specific file or process.

    Args:
        file_id: Filter by file UUID.
        process_id: Filter by process ID.
        instance: Instance profile name.

    Returns:
        dict with items (summary fields only), count.
    """
    params: dict[str, Any] = {}
    if file_id:
        params["file_id"] = file_id
    if process_id:
        params["process_id"] = process_id

    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get_paginated("/backend/certificates", params=params)
    except DSClientError as e:
        raise translate_error(e, resource_type="certificate") from e

    data["items"] = [_summarize_certificate(item) for item in data.get("items", [])]
    return data


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def file_document_list(
    file_id: str,
    instance: str | None = None,
) -> dict[str, Any]:
    """List documents uploaded for a specific application file.

    Args:
        file_id: File UUID.
        instance: Instance profile name.

    Returns:
        dict with documents, count, file_id.
    """
    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get(f"/backend/files/{file_id}/document")
    except DSClientError as e:
        raise translate_error(
            e, resource_type="file_document", resource_id=file_id
        ) from e

    docs = data if isinstance(data, list) else []
    return {
        "documents": [_summarize_document(doc) for doc in docs],
        "count": len(docs),
        "file_id": file_id,
    }
