"""
Public types for the Morphe Adapter SDK.

Field names mirror the OpenAPI 3.0 spec and the TypeScript SDK exactly
(event_type, system_id, payload, idempotency_key) to ensure a single
source of truth across both SDK implementations.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, TypedDict


class _EventPayloadRequired(TypedDict):
    """Required fields for an event payload."""

    event_type: str
    """Fully-qualified event type: "namespace.version.event_name" e.g. "dataops.v1.sync_failed"."""
    system_id: str
    """UUID of the system emitting this event."""
    payload: Dict[str, Any]
    """Arbitrary JSON object — validated against the registered schema when validate_schema=True."""


class EventPayload(_EventPayloadRequired, total=False):
    """Event dict sent to POST /api/v1/events.

    ``event_type``, ``system_id``, and ``payload`` are required;
    ``idempotency_key`` is optional.

    Using TypedDict inheritance so required fields are enforced by the type checker
    (``total=False`` on the subclass only applies to fields declared in the subclass).
    """

    idempotency_key: str
    """Idempotency key. Re-submitting with the same value within 90 days returns
    the original event instead of creating a duplicate. Use your upstream request
    ID, job ID, or record ID. If no natural ID exists, generate a UUID v4 —
    but use the same value on retry, not a new one."""


class JsonApiError(TypedDict, total=False):
    """A single error object from a JSON:API errors array."""

    code: str
    title: str
    detail: str
    source: Dict[str, str]


class ValidationFailure(TypedDict):
    """A single field-level schema validation failure."""

    field: str
    """JSON Pointer to the failing field, e.g. "/amount"."""
    message: str


@dataclass
class EmitResult:
    """Successful response from POST /api/v1/events (HTTP 202 Accepted)."""

    id: str
    """Server-assigned event UUID."""
    received_at: str
    """ISO 8601 timestamp of when the event was received."""
    schema_valid: bool
    """Whether the payload matched the registered schema."""
    schema_validation_errors: List[Dict[str, str]] = field(default_factory=list)
    """
    Field-level schema validation errors if schema_valid is False (non-blocking).
    Each entry is a JSONSchemer hash: {data_pointer, type}.
    """
