"""Summarize reading-log pages by category, then print a total."""
from argparse import ArgumentParser
import csv
import sys


def summarize(path):
    totals = {}
    with open(path, encoding="utf-8-sig", newline="") as file:
        reader = csv.DictReader(file)
        if not {"category", "pages"}.issubset(reader.fieldnames or ()):
            raise ValueError("The CSV needs category and pages columns.")
        for line, entry in enumerate(reader, start=2):
            category = (entry["category"] or "").strip()
            try:
                pages = int(entry["pages"])
            except (TypeError, ValueError) as error:
                raise ValueError(f"Line {line} needs a whole number for pages.") from error
            if not category or pages < 0:
                raise ValueError(f"Line {line} needs a category and zero or more pages.")
            totals[category] = totals.get(category, 0) + pages
    return totals


def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("path", help="Path to the reading log CSV")
    args = parser.parse_args()
    try:
        totals = summarize(args.path)
    except (OSError, ValueError) as error:
        print(error, file=sys.stderr)
        return 1
    for category in sorted(totals):
        print(f"{category}: {totals[category]}")
    print(f"Total: {sum(totals.values())}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
