"""camelCase serialization utilities for JSON output matching TypeScript."""

from __future__ import annotations

import dataclasses
import re
from typing import Any


def to_camel_case(name: str) -> str:
    """Convert snake_case to camelCase."""
    components = name.split("_")
    return components[0] + "".join(x.title() for x in components[1:])


def serialize(obj: Any, *, skip_none: bool = False) -> Any:
    """Serialize a Python object to a JSON-compatible dict with camelCase keys.

    Recursively converts dataclass fields from snake_case to camelCase.
    """
    if obj is None:
        return None

    if isinstance(obj, (str, int, float, bool)):
        return obj

    if isinstance(obj, list):
        return [serialize(item, skip_none=skip_none) for item in obj]

    if isinstance(obj, dict):
        return {to_camel_case(k) if isinstance(k, str) else k: serialize(v, skip_none=skip_none) for k, v in obj.items()}

    if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
        result = {}
        for f in dataclasses.fields(obj):
            value = getattr(obj, f.name)
            if skip_none and value is None:
                continue
            key = to_camel_case(f.name)
            result[key] = serialize(value, skip_none=skip_none)
        return result

    # Fallback for other types
    return obj
