from typing import Any

from fastmcp.exceptions import ToolError
from mcp.types import ToolAnnotations

from mcp_eregistrations_smartlink.server import mcp
from mcp_eregistrations_smartlink.smartlink_client import (
    SmartLinkClient,
    SmartLinkClientError,
    translate_error,
)


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def smartlink_audit_get(
    audit_id: str,
    instance: str | None = None,
) -> dict[str, Any]:
    """Get SmartLink audit record by ID. Entry point for debugging failing requests.

    Returns the full execution timeline: request/response bodies, transforms,
    durations, errors, and child action audit records for FLOW-type audits.

    Args:
        audit_id: Audit record UUID.
        instance: Instance name (e.g. "elsalvador-dev").

    Returns:
        dict with id, type, flowId, actions, errorMessage, durations.
    """
    _validate_uuid(audit_id, "Audit ID")

    try:
        async with SmartLinkClient.for_instance(instance) as client:
            result: dict[str, Any] = await client.get(f"/audits/{audit_id}")
            return result
    except SmartLinkClientError as e:
        raise translate_error(e, resource_type="audit", resource_id=audit_id) from e


def _validate_uuid(value: str, label: str = "ID") -> None:
    """Validate that a string is a valid UUID. Raises ToolError."""
    import uuid

    try:
        uuid.UUID(value)
    except ValueError:
        raise ToolError(f"Invalid UUID '{value}'. {label} must be a valid UUID.")
