#!/usr/bin/env python3
"""Recombine the published tehsil summaries; Python 3, standard library only.

Run: python3 reproduce_summary.py travel_time_tehsils.csv
This does not rebuild the underlying travel-time or population rasters.
"""
import argparse
import csv
import math
from pathlib import Path


def summarise(path):
    with Path(path).open(newline="", encoding="utf-8-sig") as source:
        reader = csv.DictReader(source)
        required = {"tehsil", "n_px", "pop_2020", "mot_mean", "mot_popw_mean", "mot_pct_pop_gt60"}
        if not required.issubset(reader.fieldnames or []):
            raise ValueError("CSV does not contain the required tehsil columns")
        rows = list(reader)

    valid, excluded = [], []
    for row in rows:
        cells, population = float(row["n_px"]), float(row["pop_2020"] or 0)
        if not math.isfinite(cells) or not math.isfinite(population) or cells < 0 or population < 0:
            raise ValueError(f"Invalid cell count or population: {row['tehsil']}")
        if cells == 0 or population == 0 or not row["mot_popw_mean"].strip():
            excluded.append(row["tehsil"])
            continue
        cell_mean = float(row["mot_mean"])
        mean = float(row["mot_popw_mean"])
        share = float(row["mot_pct_pop_gt60"])
        if not all(math.isfinite(v) for v in (cell_mean, mean, share)) or min(cell_mean, mean) < 0 or not 0 <= share <= 100:
            raise ValueError(f"Invalid time or percentage: {row['tehsil']}")
        valid.append((cells, population, cell_mean, mean, share))
    if not valid:
        raise ValueError("No valid rows with positive population")

    cells = math.fsum(r[0] for r in valid)
    people = math.fsum(r[1] for r in valid)
    beyond = math.fsum(r[1] * r[4] / 100 for r in valid)
    return {
        "valid_rows": len(valid), "excluded": excluded,
        "valid_cells": cells, "population_2020": people,
        "population_weighted_minutes": math.fsum(r[1] * r[3] for r in valid) / people,
        "simple_mean_of_tehsil_means": math.fsum(r[3] for r in valid) / len(valid),
        "cell_mean_minutes": math.fsum(r[0] * r[2] for r in valid) / cells,
        "people_gt60": beyond, "percent_gt60": beyond / people * 100,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("csv", type=Path, help="Downloaded travel_time_tehsils.csv")
    args = parser.parse_args()
    try:
        result = summarise(args.csv)
    except (ValueError, OSError) as error:
        parser.error(str(error))
    for key, value in result.items():
        print(f"{key}: {value:,.2f}" if isinstance(value, float) else f"{key}: {value}")
    print("Approximate recombinations of rounded statistics; modelled 2020 population, not observed journeys.")


if __name__ == "__main__":
    main()
