"""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


@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, 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:
            return await client.get_paginated("/backend/documents/user", params=params)
    except DSClientError as e:
        raise translate_error(e, resource_type="document") from e


@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, 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:
            return await client.get_paginated(
                "/backend/certificates/user", params=params
            )
    except DSClientError as e:
        raise translate_error(e, resource_type="certificate") from e


@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 (certificates), 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:
            return await client.get_paginated("/backend/certificates", params=params)
    except DSClientError as e:
        raise translate_error(e, resource_type="certificate") from e


@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 (list of document_name, file_type, file_name),
        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": docs,
        "count": len(docs),
        "file_id": file_id,
    }
