from .client import NotifiedByClient


def get_email_detail(sqid=None, email=None, client=None):
    """
    Get detailed information about a sent email.

    You can retrieve email details by either the email's unique SQID or by
    the recipient's email address. If searching by email address and multiple
    emails exist, the most recent one is returned.

    Args:
        sqid: Optional email SQID (unique identifier)
        email: Optional recipient email address
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Email details including:
            - recipient: Recipient email address
            - subject: Email subject line
            - body: Email body (HTML or plain text)
            - created_on: When email was sent

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured
        NotifiedByValidationError: If neither sqid nor email provided
        NotifiedByNotFoundError: If email not found

    Example:
        >>> # Get by SQID
        >>> email = get_email_detail(sqid='abc123xyz')
        >>> print(f"Subject: {email['subject']}")

        >>> # Get by recipient email (most recent)
        >>> email = get_email_detail(email='user@example.com')
        >>> print(f"Sent on: {email['created_on']}")
    """
    if client is None:
        client = NotifiedByClient()

    if sqid:
        # Use path parameter
        return client.get(f'/email/detail/{sqid}/')
    elif email:
        # Use query parameter
        return client.get('/email/detail/', params={'email': email})
    else:
        from .exceptions import NotifiedByValidationError
        raise NotifiedByValidationError(
            400,
            "Either 'sqid' or 'email' parameter must be provided",
            endpoint='/email/detail/'
        )


def list_sent_emails(recipient=None, page=1, client=None):
    """
    List sent emails with optional filtering.

    Returns paginated list of all emails sent through NotifiedBy. Can be
    filtered by recipient email address.

    Args:
        recipient: Optional email address to filter by
        page: Page number for pagination (default: 1)
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Paginated response with:
            - count: Total number of emails
            - next: URL to next page (or None)
            - previous: URL to previous page (or None)
            - results: List of email dicts with:
                - recipient: Recipient email address
                - subject: Email subject
                - created_on: When email was sent

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured

    Example:
        >>> # List all sent emails
        >>> result = list_sent_emails(page=1)
        >>> print(f"Total emails sent: {result['count']}")

        >>> # Filter by recipient
        >>> result = list_sent_emails(recipient='user@example.com')
        >>> for email in result['results']:
        ...     print(f"{email['subject']} - {email['created_on']}")
    """
    if client is None:
        client = NotifiedByClient()

    params = {'page': page}
    if recipient:
        params['recipient'] = recipient

    return client.get('/email/list/', params=params)


def get_email_delivery_status(email_id, client=None):
    """
    Get delivery status for a sent email.

    Check whether an email was successfully delivered, bounced, or is still
    being processed. Use the email ID returned from send_email_via_api().

    Args:
        email_id: Email ID/SQID returned from sending the email
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Delivery status information (structure depends on API response)

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured
        NotifiedByNotFoundError: If email ID not found

    Example:
        >>> from notifiedby import send_email_via_api, get_email_delivery_status
        >>> from django.core.mail import EmailMessage
        >>>
        >>> # Send email and get ID
        >>> message = EmailMessage(
        ...     subject='Test',
        ...     body='Hello',
        ...     to=['user@example.com']
        ... )
        >>> email_id = send_email_via_api(message)
        >>>
        >>> # Check delivery status
        >>> if email_id:
        ...     status = get_email_delivery_status(email_id)
        ...     print(f"Delivery status: {status}")
    """
    if client is None:
        client = NotifiedByClient()

    return client.get(f'/email/delivery/{email_id}/')
