"""How big a rainwater tank does the school need?  (ninehills Sandbox example)

Reads rainfall.csv: rain in mm for each month from November to April, first
for an average season, then for 29 real dry seasons at Bamenda (1961-62 to
1989-90). For each season it finds the smallest tank that never runs dry.
Then it tries several tank sizes. Run it with:  python3 tank.py
"""
import csv

# --- Inputs: change these for your own school ---------------------------
ROOF_M2 = 300           # roof plan area draining into the tank, m2 (illustrative)
RUNOFF = 0.8            # share of the rain that reaches the tank (assumption)
PUPILS = 200            # (illustrative)
LITRES_PER_PUPIL = 3    # per school day, drinking and handwashing (WHO)
SCHOOL_DAYS = [20, 10, 20, 20, 20, 15]  # Nov..Apr (illustrative calendar)
MONTHS = ["Nov", "Dec", "Jan", "Feb", "Mar", "Apr"]


def tank_needed(rain_mm):
    """Largest running shortfall in litres. The tank is full on 1 November."""
    shortfall = worst = 0
    for rain, days in zip(rain_mm, SCHOOL_DAYS):
        inflow = round(ROOF_M2 * rain * RUNOFF)   # 1 mm on 1 m2 = 1 litre
        use = PUPILS * LITRES_PER_PUPIL * days
        shortfall = max(0, shortfall + use - inflow)  # can't be "more than full"
        worst = max(worst, shortfall)
    return worst


# Simple tests. With no rain the tank must hold everything the school uses;
# with a flood of rain no tank is needed.
assert tank_needed([0] * 6) == PUPILS * LITRES_PER_PUPIL * sum(SCHOOL_DAYS)
assert tank_needed([1000] * 6) == 0

with open("rainfall.csv", newline="") as f:
    rows = [r for r in csv.reader(f) if r and not r[0].startswith("#")][1:]

print(f"{'Season':16}" + "".join(f"{m:>6}" for m in MONTHS) + "  Tank needed (L)")
needed = []
for season, *rain in rows:
    litres = tank_needed([float(x) for x in rain])
    print(f"{season:16}" + "".join(f"{x:>6}" for x in rain) + f"{litres:17,}")
    if not season.startswith("average"):
        needed.append(litres)

print(f"\nHow many of the {len(needed)} real dry seasons would each tank have lasted?")
for size in [10_000, 16_080, 20_000, 25_000, 30_000, 35_520, 42_720]:
    lasted = sum(n <= size for n in needed)
    print(f"{size:7,} L lasts {lasted:2} of {len(needed)} ({lasted / len(needed):4.0%})  " + "#" * lasted)
