"""Convert an already checked two-field TSV into a new Memly CSV file."""
import argparse
import csv
import hashlib
import io
import json
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input_tsv", type=Path)
parser.add_argument("output_csv", type=Path)
args = parser.parse_args()
raw = args.input_tsv.read_bytes()
rows = list(csv.reader(io.StringIO(raw.decode("utf-8-sig")), delimiter="\t"))
if len(rows) != 3 or any(len(row) != 2 or not all(value.strip() for value in row) for row in rows):
    raise SystemExit("Expected exactly three nonempty two-field TSV rows without a heading row.")
if any("\n" in value or "\r" in value or "\t" in value for row in rows for value in row):
    raise SystemExit("This simple fixture does not allow embedded line breaks or tabs.")
with args.output_csv.open("x", encoding="utf-8", newline="") as output:
    writer = csv.writer(output, lineterminator="\n")
    writer.writerow(["front", "back"])
    writer.writerows(rows)
result = args.output_csv.read_bytes()
print(json.dumps({"rows": len(rows), "inputSha256": hashlib.sha256(raw).hexdigest(), "outputSha256": hashlib.sha256(result).hexdigest()}))
