"""
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:
        if hasattr(value, "__dict__"):
            d = dict(value.__dict__)
            d.pop("_sa_instance_state", None)
            return {k: serialize_value(v) for k, v in d.items()}
            
        if not isinstance(value, (int, float, str, bool)):
            return str(value)
            
        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()}
