KG_PER_LB = 0.45359237
LB_PER_KG = 1.0 / KG_PER_LB

METRIC = "metric"
IMPERIAL = "imperial"


def lbs_to_kg(lbs: float) -> float:
    return round(float(lbs) * KG_PER_LB, 2)


def kg_to_lbs(kg: float) -> float:
    return round(float(kg) * LB_PER_KG, 1)


def normalize_weight(value, units: str = METRIC):
    """Convert a user-provided weight into canonical kg for storage."""
    if value is None or value == "":
        return None
    try:
        value = float(value)
    except (ValueError, TypeError):
        return None
    if units == IMPERIAL:
        return lbs_to_kg(value)
    return round(value, 2)


def display_value(kg, units: str = METRIC):
    """Return the weight value to present to a user in their preferred units."""
    if kg is None or kg == "":
        return None
    try:
        kg = float(kg)
    except (ValueError, TypeError):
        return None
    if units == IMPERIAL:
        return kg_to_lbs(kg)
    return round(kg, 1)


def weight_label(units: str = METRIC) -> str:
    return "lbs" if units == IMPERIAL else "kg"


def display_weight(kg, units: str = METRIC) -> str:
    value = display_value(kg, units)
    if value is None:
        return ""
    return f"{value} {weight_label(units)}"
