"""Summarise one category in an Open Repair Alliance EEE CSV for a calendar year."""
import argparse
import csv
import sys
from collections import Counter
from datetime import date


def summarize(path, category, year):
    counts = Counter()
    with open(path, newline="", encoding="utf-8-sig") as source:
        rows = csv.DictReader(source)
        columns = {"event_date", "product_category", "repair_status"}
        if not columns.issubset(rows.fieldnames or []):
            raise ValueError("The EEE dataset must contain event_date, product_category and repair_status.")
        for row in rows:
            if row["product_category"] != category or not row["event_date"].startswith(f"{year}-"):
                continue
            if date.fromisoformat(row["event_date"]).year != year:
                raise ValueError("Unexpected event date.")
            status = row["repair_status"].strip()
            if status not in {"Fixed", "Repairable", "End of life", "Unknown"}:
                raise ValueError(f"Unexpected repair_status {status!r}; check the input codebook.")
            counts[status] += 1
    if not counts:
        raise ValueError("No matching repair attempts. Check product_category and year.")
    return counts


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", help="Path to the official aggregate EEE CSV")
    parser.add_argument("category", help="Exact ORA product_category")
    parser.add_argument("year", type=int, help="Four-digit event year")
    args = parser.parse_args()
    writer = csv.writer(sys.stdout, lineterminator="\n")
    try:
        cohort = summarize(args.source, args.category, args.year)
    except (ValueError, OSError) as error:
        parser.exit(1, f"{error}\n")
    writer.writerow(["repair_status", "attempts"])
    for value in ("Fixed", "Repairable", "End of life", "Unknown"):
        writer.writerow([value, cohort[value]])
