from __future__ import annotations

import dataclasses
import json
from typing import Any


def to_jsonable(value: Any) -> Any:
    """Convert common Python objects into JSON-serializable structures."""
    if dataclasses.is_dataclass(value):
        return dataclasses.asdict(value)
    if hasattr(value, "model_dump") and callable(getattr(value, "model_dump")):
        # Pydantic v2 models
        return value.model_dump()
    if isinstance(value, (set, frozenset)):
        return list(value)
    return value


def json_dumps(value: Any, *, ensure_ascii: bool = False) -> str:
    """Safe JSON stringify with a reasonable fallback."""
    try:
        return json.dumps(to_jsonable(value), ensure_ascii=ensure_ascii)
    except TypeError:
        return json.dumps({"repr": repr(value)}, ensure_ascii=ensure_ascii)
