"""Fictional unit display: deliberately wrong baseline, correction and mutants.

No medical or clinical units, thresholds, performance or intended use are modeled.
The exact teaching contract is in requirements.json.
"""


def unavailable():
    return {"state": "unavailable", "text": "Unavailable", "unit": None}


def invalid(reason):
    return {"state": "invalid", "text": "Invalid input", "unit": None, "reason": reason}


def validate_integer(raw):
    # bool is an int subclass in Python, but is not a valid integer reading here.
    if type(raw) is not int:
        return invalid("TYPE")
    if not 0 <= raw <= 40:
        return invalid("RANGE")
    return None


def baseline(raw):
    # Fault 1: missing data is converted to a plausible numeric zero.
    if raw is None:
        raw = 0
    error = validate_integer(raw)
    if error is not None:
        return error
    # Fault 2: default ties-to-even formatting differs from the declared rule.
    return {"state": "value", "text": f"{raw / 4:.1f}", "unit": "u"}


def corrected(raw):
    if raw is None:
        return unavailable()
    error = validate_integer(raw)
    if error is not None:
        return error
    # Exact rational conversion: 4 ticks = 1 u. Round nonnegative half-tenths up.
    # Negative inputs have already been rejected, rather than rounded.
    tenths = (raw * 10 + 2) // 4
    return {"state": "value", "text": f"{tenths // 10}.{tenths % 10}", "unit": "u"}


def mutant_ties_even(raw):
    """Reintroduce only the rounding fault into the corrected implementation."""
    if raw is None:
        return unavailable()
    error = validate_integer(raw)
    if error is not None:
        return error
    return {"state": "value", "text": f"{raw / 4:.1f}", "unit": "u"}


def mutant_missing_as_zero(raw):
    """Reintroduce only the missing-as-zero fault into the correction."""
    return corrected(0 if raw is None else raw)


IMPLEMENTATIONS = {
    "baseline": baseline,
    "corrected": corrected,
    "mutant_ties_even": mutant_ties_even,
    "mutant_missing_as_zero": mutant_missing_as_zero,
}
