"""Count events in 100 equally likely synthetic two-window rain scenarios."""

import json

THRESHOLD_TENTHS_MM = 10

# Rows are (morning tenths of a millimetre, afternoon tenths, count).
CASES = {
    "same_days": [(10, 10, 30), (0, 0, 70)],
    "independent_events": [(10, 10, 9), (10, 0, 21), (0, 10, 21), (0, 0, 49)],
    "separate_days": [(10, 0, 30), (0, 10, 30), (0, 0, 40)],
    "light_rain_accumulates": [
        (10, 10, 9), (10, 0, 21), (0, 10, 21), (6, 6, 20), (0, 0, 29),
    ],
    "accumulation_in_every_outcome": [(10, 10, 30), (6, 6, 70)],
}


def summarize(rows):
    total = sum(count for _, _, count in rows)
    morning = sum(n for a, _, n in rows if a >= THRESHOLD_TENTHS_MM)
    afternoon = sum(n for _, b, n in rows if b >= THRESHOLD_TENTHS_MM)
    both = sum(n for a, b, n in rows if min(a, b) >= THRESHOLD_TENTHS_MM)
    either = sum(n for a, b, n in rows if max(a, b) >= THRESHOLD_TENTHS_MM)
    accumulated = sum(n for a, b, n in rows if a + b >= THRESHOLD_TENTHS_MM)
    additional = sum(
        n for a, b, n in rows
        if max(a, b) < THRESHOLD_TENTHS_MM <= a + b
    )
    assert either == morning + afternoon - both
    assert accumulated == either + additional
    return {
        "trials": total,
        "morning_reached_threshold": morning,
        "afternoon_reached_threshold": afternoon,
        "both_reached_threshold": both,
        "either_reached_threshold": either,
        "accumulation_only": additional,
        "total_reached_threshold": accumulated,
    }


def main():
    results = {name: summarize(rows) for name, rows in CASES.items()}
    for result in results.values():
        assert result["trials"] == 100
        assert result["morning_reached_threshold"] == 30
        assert result["afternoon_reached_threshold"] == 30
    assert [case["either_reached_threshold"] for case in results.values()] == [30, 51, 60, 51, 30]
    assert [case["total_reached_threshold"] for case in results.values()] == [30, 51, 60, 71, 100]
    independent = results["independent_events"]
    assert independent["both_reached_threshold"] * independent["trials"] == (
        independent["morning_reached_threshold"] * independent["afternoon_reached_threshold"]
    )

    below = summarize([(4, 5, 1)])
    at = summarize([(4, 6, 1)])
    assert below["total_reached_threshold"] == 0
    assert at["either_reached_threshold"] == 0
    assert at["total_reached_threshold"] == 1

    print(json.dumps({
        "units": "tenths of a millimetre",
        "threshold_tenths_mm": THRESHOLD_TENTHS_MM,
        "cases": {
            name: {"rows": CASES[name], "summary": result}
            for name, result in results.items()
        },
        "boundary_checks": {
            "total_0.9_mm": below["total_reached_threshold"],
            "total_1.0_mm": at["total_reached_threshold"],
        },
    }, indent=2))


if __name__ == "__main__":
    main()
