"""Custom JSON encoder for Complio data serialization."""

import json
from datetime import datetime, date
from enum import Enum
from typing import Any


class ComplioJSONEncoder(json.JSONEncoder):
    """
    Custom JSON encoder that handles datetime and other non-serializable types.

    This encoder is used throughout Complio to ensure consistent JSON serialization,
    particularly for:
    - datetime objects (converted to ISO format strings)
    - date objects (converted to ISO format strings)
    - Enum values (converted to their value attribute)
    - Objects with __dict__ attribute (converted to dict representation)

    Example:
        >>> import json
        >>> from datetime import datetime
        >>> data = {"timestamp": datetime.now()}
        >>> json.dumps(data, cls=ComplioJSONEncoder)
        '{"timestamp": "2024-01-23T10:30:00.123456"}'
    """

    def default(self, obj: Any) -> Any:
        """
        Convert non-serializable objects to JSON-compatible types.

        Args:
            obj: The object to serialize

        Returns:
            A JSON-serializable representation of the object

        Raises:
            TypeError: If the object cannot be serialized
        """
        if isinstance(obj, datetime):
            return obj.isoformat()
        if isinstance(obj, date):
            return obj.isoformat()
        if isinstance(obj, Enum):
            return obj.value
        if hasattr(obj, '__dict__'):
            return obj.__dict__
        return super().default(obj)
