"""Chapter 2: synthetic classroom estimands; run with Python 3."""
import csv
from pathlib import Path

DATA = Path(__file__).with_name("classrooms.csv")


def read_rooms(path=DATA):
    with path.open(newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    assert rows and len({row["room"] for row in rows}) == len(rows)
    for row in rows:
        for key in ("hot_intervals", "intervals", "hot_seat_hours", "seat_hours"):
            row[key] = int(row[key])
        assert 0 <= row["hot_intervals"] <= row["intervals"]
        assert 0 <= row["hot_seat_hours"] <= row["seat_hours"]
    return rows


def describe(rows):
    room_mean = sum(row["hot_intervals"] / row["intervals"] for row in rows) / len(rows)
    seat_rate = sum(row["hot_seat_hours"] for row in rows) / sum(row["seat_hours"] for row in rows)
    return room_mean, seat_rate


def main():
    rows = read_rooms()
    room_mean, seat_rate = describe(rows)
    print(f"Room mean: {room_mean:.1%}")
    print(f"Student-seat-hour rate: {seat_rate:.1%}")
    without_d = [row for row in rows if row["room"] != "D"]
    mean_without_d, seat_without_d = describe(without_d)
    print(f"Without D — room mean: {mean_without_d:.1%}; seat-hour rate: {seat_without_d:.1%}")
    doubled_a = [dict(row) for row in without_d]
    doubled_a[0]["hot_seat_hours"] *= 2
    doubled_a[0]["seat_hours"] *= 2
    print(f"Without D, A doubled — seat-hour rate: {describe(doubled_a)[1]:.1%}")
    assert (room_mean, seat_rate) == (0.5, 0.6)
    assert abs(seat_without_d - 280 / 600) < 1e-12
    assert abs(describe(doubled_a)[1] - 300 / 700) < 1e-12


if __name__ == "__main__":
    main()
