#!/usr/bin/env python3
"""Recalculate the hypothetical speed–accuracy worked examples.

Uses only the Python standard library. No participant or customer data.
"""

from __future__ import annotations

import csv
import statistics
from pathlib import Path


HERE = Path(__file__).resolve().parent
SOURCE = HERE / "worked-examples.csv"


def main() -> None:
    with SOURCE.open(newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))

    response_times = [float(row["mean_correct_rt_ms"]) for row in rows]
    proportions = [float(row["proportion_correct"]) for row in rows]
    mean_rt = statistics.fmean(response_times)
    mean_pc = statistics.fmean(proportions)
    sd_rt = statistics.pstdev(response_times)
    sd_pc = statistics.pstdev(proportions)

    print("session\taccuracy_pct\tmean_correct_rt_ms\tIES_ms\tRCS_per_s\tBIS")
    for row, rt_ms, pc in zip(rows, response_times, proportions):
        if not 0 < pc <= 1:
            raise ValueError(f"proportion_correct must be in (0, 1]: {pc}")
        ies = rt_ms / pc
        rcs = pc / (rt_ms / 1000)
        bis = ((pc - mean_pc) / sd_pc) - ((rt_ms - mean_rt) / sd_rt)
        print(
            f"{row['session']}\t{pc * 100:.1f}\t{rt_ms:.0f}\t"
            f"{ies:.3f}\t{rcs:.6f}\t{bis:.6f}"
        )


if __name__ == "__main__":
    main()
