#!/usr/bin/env python3
"""Summarize approved, de-identified response-time records; no data is bundled."""
import csv, math, statistics, sys
from collections import defaultdict
from pathlib import Path

REQUIRED = {"sector_code", "response_minutes", "inclusion_status", "consent_status"}

def nearest_rank(values, p):
    ordered = sorted(values)
    return ordered[max(0, math.ceil(p * len(ordered)) - 1)]

def main(path):
    with Path(path).open(newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        missing = REQUIRED - set(reader.fieldnames or [])
        if missing:
            raise SystemExit("Missing required columns: " + ", ".join(sorted(missing)))
        groups = defaultdict(list)
        for row in reader:
            if row.get("consent_status") != "confirmed" or row.get("inclusion_status") != "included":
                continue
            try:
                value = float(row["response_minutes"])
            except (TypeError, ValueError):
                continue
            if value >= 0:
                groups[row["sector_code"]].append(value)
    if not groups:
        print("No approved observations: no benchmark statistics generated.")
        return 0
    print("sector_code,n,median_business_minutes,p90_nearest_rank")
    for sector, values in sorted(groups.items()):
        print(f"{sector},{len(values)},{statistics.median(values):.2f},{nearest_rank(values, 0.90):.2f}")
    return 0

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: analyze-response-times.py <approved-csv>")
    raise SystemExit(main(sys.argv[1]))
