"""Event tracking resource."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from resletter.types import TrackEventResponse

if TYPE_CHECKING:
    from resletter.client import Resletter


class EventsResource:
    """Event tracking resource for triggering automations.

    Example:
        >>> result = client.events.track(
        ...     name="purchase_completed",
        ...     email="user@example.com",
        ...     data={
        ...         "product": "Premium Plan",
        ...         "amount": 99.00,
        ...     },
        ... )
        >>> print(f"Triggered {result['automationsTriggered']} automations")
    """

    def __init__(self, client: Resletter) -> None:
        self._client = client

    def track(
        self,
        *,
        name: str,
        subscriber_id: str | None = None,
        email: str | None = None,
        data: dict[str, Any] | None = None,
    ) -> TrackEventResponse:
        """Track a custom event to trigger automations.

        Either `subscriber_id` or `email` must be provided to identify the subscriber.

        Args:
            name: Event name (e.g., 'purchase_completed', 'signup').
            subscriber_id: Subscriber's unique ID.
            email: Subscriber's email address.
            data: Custom event data to pass to automations.

        Returns:
            Response with event name, subscriber ID, and triggered automation count.

        Raises:
            ValueError: If neither subscriber_id nor email is provided.

        Example:
            >>> result = client.events.track(
            ...     name="purchase_completed",
            ...     email="user@example.com",
            ...     data={
            ...         "product": "Premium Plan",
            ...         "amount": 99.00,
            ...     },
            ... )
            >>> print(f"Triggered {result['automationsTriggered']} automations")
        """
        if not subscriber_id and not email:
            raise ValueError("Either subscriber_id or email is required")

        body: dict[str, Any] = {"name": name}
        if subscriber_id is not None:
            body["subscriberId"] = subscriber_id
        if email is not None:
            body["email"] = email
        if data is not None:
            body["data"] = data

        return self._client._request("POST", "/events", json=body)
