"""Validate a small catalog CSV and write one JSON object per record."""
import argparse
import csv
import json
import re
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
records = {}
with args.source.open(encoding="utf-8-sig", newline="") as stream:
    rows = csv.DictReader(stream, strict=True)
    if rows.fieldnames != ["sku", "title", "quantity"]:
        parser.error("Expected sku,title,quantity headers in that order")
    for row in rows:
        sku, title, qty = row["sku"], row["title"], row["quantity"]
        if None in row or not sku or not title or qty is None or sku in records:
            parser.error(f"Invalid or duplicate record ending on line {rows.line_num}")
        if qty and not re.fullmatch("[0-9]+", qty):
            parser.error(f"Invalid quantity ending on line {rows.line_num}")
        records[sku] = {"sku": sku, "title": title, "quantity": int(qty) if qty else None}
with args.output.open("x", encoding="utf-8") as stream:
    for record in records.values():
        stream.write(json.dumps(record, ensure_ascii=False) + "\n")
print(f"Wrote {len(records)} records.")
