#!/usr/bin/env python3
"""Summarize a populated, de-identified response-time template; no fake rows."""
import csv
import math
import statistics
import sys
from collections import defaultdict
from datetime import date, datetime
from pathlib import Path

MIN_OPERATORS = 5  # protocol privacy threshold, not a result or industry norm
REQUIRED = {
    "record_id", "operator_code", "source_or_release", "reference_period_start",
    "reference_period_end", "population_definition", "property_sector",
    "portfolio_size_band", "inquiry_type", "inquiry_channel", "inquiry_received_at",
    "first_meaningful_reply_at", "operator_timezone", "business_hours_rule_id",
    "received_during_business_hours", "eligibility_status", "exclusion_reason",
    "missing_data_flag", "collection_date",
}
OUTPUT_FIELDS = [
    "dataset_version", "source_or_release", "reference_period_start", "reference_period_end",
    "population_definition", "property_sector", "portfolio_size_band", "inquiry_type",
    "received_during_business_hours", "metric_name", "metric_definition", "unit",
    "numerator", "denominator", "metric_value", "operator_count", "eligible_inquiries",
    "answered_inquiries", "unanswered_inquiries", "excluded_inquiries",
    "records_with_missing_data", "release_status", "missing_data_flag", "collection_date",
]

def parse_time(value):
    parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
    if parsed.tzinfo is None or parsed.utcoffset() is None:
        raise ValueError("timestamp must include a UTC offset")
    return parsed

def p90_nearest_rank(values):
    ordered = sorted(values)
    return ordered[math.ceil(0.90 * len(ordered)) - 1]

def main(source):
    with open(source, newline="", encoding="utf-8-sig") as handle:
        reader = csv.DictReader(handle)
        missing_columns = REQUIRED - set(reader.fieldnames or [])
        if missing_columns:
            raise SystemExit("Missing required columns: " + ", ".join(sorted(missing_columns)))
        rows = list(reader)
    if not rows:
        raise SystemExit("No observations: the protocol template is intentionally empty; no benchmark is produced.")

    groups = defaultdict(lambda: {
        "operators": set(), "eligible": 0, "answered": [], "unanswered": 0,
        "excluded": 0, "missing_records": 0, "missing_fields": set(), "rows": [],
    })
    for row in rows:
        key = tuple((row.get(field) or "").strip() or "unknown" for field in (
            "property_sector", "portfolio_size_band", "inquiry_type", "received_during_business_hours"
        ))
        group = groups[key]
        group["rows"].append(row)
        status = (row.get("eligibility_status") or "").strip().lower()
        if status != "include":
            group["excluded"] += 1
            continue

        group["eligible"] += 1
        operator = (row.get("operator_code") or "").strip()
        if operator:
            group["operators"].add(operator)
        flags = {part.strip() for part in (row.get("missing_data_flag") or "").split(";") if part.strip() and part.strip().lower() != "none"}
        group["missing_fields"].update(flags)
        received = (row.get("inquiry_received_at") or "").strip()
        replied = (row.get("first_meaningful_reply_at") or "").strip()
        if flags or not received:
            group["missing_records"] += 1
        if not replied:
            if "first_meaningful_reply_at" in flags or "inquiry_received_at" in flags or not received:
                continue
            group["unanswered"] += 1
            continue
        if not received or "inquiry_received_at" in flags:
            continue
        try:
            elapsed = (parse_time(replied) - parse_time(received)).total_seconds() / 60
        except ValueError:
            group["missing_records"] += 1
            group["missing_fields"].update({"inquiry_received_at", "first_meaningful_reply_at"})
            continue
        if elapsed < 0:
            raise SystemExit("Reply precedes receipt for record " + ((row.get("record_id") or "").strip() or "[unknown]"))
        group["answered"].append((elapsed, row))

    writer = csv.DictWriter(sys.stdout, fieldnames=OUTPUT_FIELDS)
    writer.writeheader()
    for key, group in sorted(groups.items()):
        sector, portfolio_band, inquiry_type, business_hours = key
        source_labels = sorted({(r.get("source_or_release") or "").strip() for r in group["rows"] if (r.get("source_or_release") or "").strip()})
        populations = sorted({(r.get("population_definition") or "").strip() for r in group["rows"] if (r.get("population_definition") or "").strip()})
        starts = sorted((r.get("reference_period_start") or "").strip() for r in group["rows"] if (r.get("reference_period_start") or "").strip())
        ends = sorted((r.get("reference_period_end") or "").strip() for r in group["rows"] if (r.get("reference_period_end") or "").strip())
        dates = sorted((r.get("collection_date") or "").strip() for r in group["rows"] if (r.get("collection_date") or "").strip())
        shared = {
            "dataset_version": "protocol-1.0",
            "source_or_release": "; ".join(source_labels),
            "reference_period_start": starts[0] if starts else "",
            "reference_period_end": ends[-1] if ends else "",
            "population_definition": "; ".join(populations),
            "property_sector": sector,
            "portfolio_size_band": portfolio_band,
            "inquiry_type": inquiry_type,
            "received_during_business_hours": business_hours,
            "operator_count": len(group["operators"]),
            "eligible_inquiries": group["eligible"],
            "answered_inquiries": len(group["answered"]),
            "unanswered_inquiries": group["unanswered"],
            "excluded_inquiries": group["excluded"],
            "records_with_missing_data": group["missing_records"],
            "release_status": "reported",
            "missing_data_flag": "; ".join(sorted(group["missing_fields"])) or "none",
            "collection_date": dates[-1] if dates else date.today().isoformat(),
        }
        if len(group["operators"]) < MIN_OPERATORS:
            writer.writerow({**shared, "metric_name": "group_suppression", "metric_definition": f"Group results and counts are suppressed below {MIN_OPERATORS} contributing operators.", "unit": "", "numerator": "", "denominator": "", "metric_value": "", "operator_count": "", "eligible_inquiries": "", "answered_inquiries": "", "unanswered_inquiries": "", "excluded_inquiries": "", "records_with_missing_data": "", "release_status": "suppressed", "missing_data_flag": "", "collection_date": ""})
            continue

        values = [value for value, _ in group["answered"]]
        if values:
            denominator = len(values)
            definition = "Elapsed wall-clock minutes from inquiry_received_at to first_meaningful_reply_at among answered eligible inquiries with valid timezone-aware timestamps."
            for name, result in (("median_elapsed_minutes", statistics.median(values)), ("p90_nearest_rank_elapsed_minutes", p90_nearest_rank(values))):
                writer.writerow({**shared, "metric_name": name, "metric_definition": definition, "unit": "minutes", "numerator": "not applicable for quantile", "denominator": denominator, "metric_value": round(result, 1)})
        if group["eligible"]:
            writer.writerow({**shared, "metric_name": "unanswered_share_by_cutoff", "metric_definition": "Eligible inquiries with no meaningful reply by the participant's export cutoff divided by all eligible inquiries in the group.", "unit": "percent", "numerator": group["unanswered"], "denominator": group["eligible"], "metric_value": round(100 * group["unanswered"] / group["eligible"], 1)})

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: analyze-property-management-lead-response.py <deidentified-template.csv>")
    main(Path(sys.argv[1]))
