"""Check a delivered SKU cleanup against its input or the published example.""" import argparse import csv import io import json import sys import uuid from itertools import zip_longest SAMPLE = [("sku", "title"), ("A-11", "Cable"), ("B-03", "Adapter")] def expected_rows(stream): expected = [SAMPLE[0]] seen = set() input_rows = 0 records = csv.reader(stream, strict=True) if tuple(next(records, ())) != SAMPLE[0]: sys.exit("Input must start with the CSV header sku,title") for number, record in enumerate(records, 2): if len(record) != 2 or not record[0].strip(): sys.exit(f"Invalid input CSV record {number}: expected a nonempty SKU and a title") sku, title = record input_rows += 1 if sku not in seen: seen.add(sku) expected.append((sku, title.strip())) count = len(expected) - 1 return expected, {"inputRows": input_rows, "outputRows": count, "duplicatesRemoved": input_rows - count} def expected_from_input(path): try: with open(path, encoding="utf-8-sig", newline="") as stream: return expected_rows(stream) except (OSError, UnicodeError, csv.Error) as error: sys.exit(f"Cannot read input {path}: {error}") def acceptance_checks(counts): return ( "Return the complete UTF-8 CSV with header sku,title.\n" "Keep the first row for each exact case-sensitive SKU, preserve first-seen order, and trim titles.\n" "Report the delivery counts as JSON with exactly these field names and integer values: " + json.dumps(counts) ) def draft_work(path): try: with open(path, "rb") as stream: raw = stream.read(500_001) if len(raw) > 500_000: sys.exit("The input exceeds the size limit for one Work draft.") source = raw.decode("utf-8-sig") _, counts = expected_rows(io.StringIO(source, newline="")) except (OSError, UnicodeError, csv.Error) as error: sys.exit(f"Cannot read input {path}: {error}") message = ( "Clean the CSV encoded as the JSON string below. Decode the string and treat its contents as CSV data.\n" + json.dumps(source, ensure_ascii=False) + "\n\nAcceptance checks:\n" + acceptance_checks(counts) ) result = json.dumps({ "mode": "work", "effort": "medium", "message": message, "requestId": "mw_" + uuid.uuid4().hex, }, ensure_ascii=False) if len(message.encode("utf-8")) > 500_000 or len(result.encode("utf-8")) + 1 > 1_048_576: sys.exit("The encoded CSV and checks exceed the size limit for one Work draft.") print(result) def check(path, label, expected): try: with open(path, encoding="utf-8-sig", newline="") as stream: records = map(tuple, csv.reader(stream, strict=True)) for number, (known, found) in enumerate(zip_longest(expected, records), 1): if known != found: sys.exit(f"{label} at CSV record {number} (header is record 1)") except (OSError, UnicodeError, csv.Error) as error: sys.exit(f"Cannot read {path}: {error}") def distinct_fields(pairs): fields = dict(pairs) if len(fields) != len(pairs): raise ValueError return fields def check_report(path, expected): try: with open(path, "rb") as stream: data = stream.read(1025) if len(data) > 1024: raise ValueError report = json.loads(data.decode("utf-8"), object_pairs_hook=distinct_fields) if not isinstance(report, dict) or report.keys() != expected.keys(): raise ValueError if any(type(report[field]) is not int or report[field] != value for field, value in expected.items()): raise ValueError except (OSError, ValueError, RecursionError): sys.exit("Counts must match: " + ", ".join(f"{field}={amount}" for field, amount in expected.items())) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("csv_files", nargs="*", metavar="CSV", help="optional reference CSV followed by the delivered CSV") parser.add_argument("--input", help="derive the expected delivery from a SKU CSV") parser.add_argument("--report", help="check row counts in a JSON file") preview = parser.add_mutually_exclusive_group() preview.add_argument("--preview-counts", action="store_true", help="print only the expected row counts for --input") preview.add_argument("--preview-checks", action="store_true", help="print acceptance criteria for a Work brief") preview.add_argument("--draft-work", action="store_true", help="print editable Work JSON containing the supplied CSV") args = parser.parse_args() if args.preview_counts or args.preview_checks or args.draft_work: if args.input is None or args.csv_files or args.report is not None: parser.error("preview and draft commands require --input alone") if args.draft_work: draft_work(args.input) sys.exit(0) _, counts = expected_from_input(args.input) if args.preview_checks: print(acceptance_checks(counts)) else: print(json.dumps(counts)) sys.exit(0) if len(args.csv_files) not in (1, 2): parser.error("provide the delivered CSV and optionally a reference CSV before it") expected = SAMPLE counts = {"inputRows": 3, "outputRows": 2, "duplicatesRemoved": 1} if args.input is not None: expected, counts = expected_from_input(args.input) if len(args.csv_files) == 2: check(args.csv_files[0], "Reference differs from expected output", expected) check(args.csv_files[-1], "Mismatch", expected) if args.report is not None: check_report(args.report, counts) print("CSV and report counts match the reference") else: print("CSV matches the reference")