#!/usr/bin/env python3
"""Recompute the reaction-time summaries in the accompanying CSV.

Standard library only. The lists are deterministic teaching examples and do
not contain participant, customer, account or telemetry data.
"""

from __future__ import annotations

from statistics import fmean, median


SCENARIOS = {
    "baseline": [310, 320, 330, 340, 350, 360, 370, 390, 420],
    "one_delayed_trial": [310, 320, 330, 340, 350, 360, 370, 390, 1800],
    "broad_shift_plus_40_ms": [350, 360, 370, 380, 390, 400, 410, 430, 460],
}


def trimmed_mean(values: list[int], proportion_each_tail: float = 0.20) -> float:
    """Return a symmetric trimmed mean using floor(n * proportion) per tail."""
    ordered = sorted(values)
    k = int(len(ordered) * proportion_each_tail)
    kept = ordered[k : len(ordered) - k] if k else ordered
    if not kept:
        raise ValueError("trim rule removed every value")
    return fmean(kept)


def summaries(values: list[int]) -> dict[str, float]:
    return {
        "mean_ms": fmean(values),
        "median_ms": float(median(values)),
        "trim_20_each_tail_ms": trimmed_mean(values),
        "fastest_ms": float(min(values)),
    }


EXPECTED = {
    "baseline": (354.444, 350.000, 351.429, 310.000),
    "one_delayed_trial": (507.778, 350.000, 351.429, 310.000),
    "broad_shift_plus_40_ms": (394.444, 390.000, 391.429, 350.000),
}


if __name__ == "__main__":
    for name, values in SCENARIOS.items():
        result = summaries(values)
        observed = tuple(round(value, 3) for value in result.values())
        assert observed == EXPECTED[name], (name, observed, EXPECTED[name])
        print(name, ", ".join(f"{key}={value:.3f}" for key, value in result.items()))
