"""
Type conversion and unit formatting utilities for schema-driven event processing.
"""

from typing import Any
from hil_testbench.data_structs.parameters import ParameterField


def convert_event_types(
    event: dict[str, Any], fields: list[ParameterField]
) -> dict[str, Any]:
    """Convert event values to types specified in schema fields."""
    converted = {}
    field_map = {f.name: f for f in fields}
    for k, v in event.items():
        if k in field_map:
            try:
                converted[k] = field_map[k].type(v)
            except (TypeError, ValueError):
                converted[k] = v  # fallback to original if conversion fails
        else:
            converted[k] = v
    return converted


def format_with_units(
    event: dict[str, Any], fields: list[ParameterField]
) -> dict[str, str]:
    """Format event values with units from schema fields."""
    formatted = {}
    field_map = {f.name: f for f in fields}
    for k, v in event.items():
        unit = field_map[k].unit if k in field_map and field_map[k].unit else ""
        formatted[k] = f"{v} {unit}".strip() if unit else str(v)
    return formatted
