"""Utilities for working with JSON schema mappings in TransformStep."""

from __future__ import annotations

from typing import Any


def extract_primary_type_from_schema(schema: dict[str, Any]) -> str | None:
    type_value = schema.get("type")
    if isinstance(type_value, list) and type_value:
        return type_value[0]
    if isinstance(type_value, str):
        return type_value
    return None


def get_python_type_from_json_schema_type(type_value: str | None) -> type[Any]:
    mapping: dict[str | None, type[Any]] = {
        "string": str,
        "integer": int,
        "number": float,
        "boolean": bool,
        "object": dict,
        "array": list,
        None: str,
    }
    return mapping.get(type_value, str)


def coerce_value_to_schema_type(value: Any, schema: dict[str, Any]) -> Any:
    target = get_python_type_from_json_schema_type(extract_primary_type_from_schema(schema))
    try:
        return target(value)
    except Exception:
        return value
