"""Recreate the Wales community repair explorer CSVs from the pinned source."""

import argparse
from collections import Counter, defaultdict
import csv
from datetime import date
from hashlib import sha256
from pathlib import Path

SOURCE_SHA256 = "e06c3bd161dae48f55d401837c44c25ed48ba46538b6dfd9a8f6b32da27b0008"
OUTCOMES = ("Fixed", "Repairable", "End of life", "Unknown")


def read_attempts(source):
    if sha256(source.read_bytes()).hexdigest() != SOURCE_SHA256:
        raise ValueError("Use the exact October 2026 source file linked in README.txt")

    attempts = []
    counts = defaultdict(Counter)
    with source.open(encoding="utf-8-sig", newline="") as handle:
        for row in csv.DictReader(handle):
            if row["data_provider"] != "Repair Cafe Wales":
                continue
            if date.fromisoformat(row["event_date"]).year != 2025:
                continue
            category = row["product_category"].removeprefix("Unpowered - ")
            outcome = row["repair_status"]
            attempts.append((row["id"], row["event_date"], category, outcome))
            counts[category][outcome] += 1

    if len({attempt[0] for attempt in attempts}) != 4025 or len(attempts) != 4025:
        raise ValueError("Expected 4,025 unique Repair Cafe Wales attempt IDs")
    return attempts, counts


def write_outputs(directory, attempts, counts):
    directory.mkdir(parents=True, exist_ok=True)
    with (directory / "attempts.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow(["AttemptID", "Event Date", "Category", "Outcome"])
        writer.writerows(attempts)

    with (directory / "summary.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow([
            "Category", "Recorded", *OUTCOMES,
            "Fixed of recorded (%)", "Fixed of known (%)",
        ])
        for category, outcomes in sorted(counts.items()):
            recorded = sum(outcomes.values())
            known = recorded - outcomes["Unknown"]
            writer.writerow([
                category, recorded, *(outcomes[outcome] for outcome in OUTCOMES),
                round(100 * outcomes["Fixed"] / recorded, 4),
                round(100 * outcomes["Fixed"] / known, 4),
            ])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path, help="Pinned Open Repair data CSV")
    parser.add_argument("output", type=Path, help="Directory for the two CSVs")
    args = parser.parse_args()
    attempts, counts = read_attempts(args.source)
    write_outputs(args.output, attempts, counts)


if __name__ == "__main__":
    main()
