"""
Serialization utilities for audit logs
"""

from datetime import date, datetime, time
from decimal import Decimal
from uuid import UUID
from typing import Any, Dict


def serialize_value(value: Any) -> Any:
    """
    Convert a Python value to a JSON-serializable type
    """
    if value is None:
        return None
    elif isinstance(value, (date, datetime)):
        return value.isoformat()
    elif isinstance(value, time):
        return value.isoformat()
    elif isinstance(value, Decimal):
        return float(value)
    elif isinstance(value, UUID):
        return str(value)
    elif isinstance(value, bytes):
        return value.decode("utf-8", errors="replace")
    elif isinstance(value, (list, tuple)):
        return [serialize_value(item) for item in value]
    elif isinstance(value, dict):
        return {key: serialize_value(val) for key, val in value.items()}
    else:
        # For any other type, try to return as-is (str, int, float, bool, None)
        # If it fails JSON serialization later, at least we tried
        return value


def serialize_for_json(data: Dict[str, Any]) -> Dict[str, Any]:
    """
    Recursively serialize a dictionary for JSON storage
    """
    if not data:
        return data

    return {key: serialize_value(value) for key, value in data.items()}
