"""Stream UTF-8 CSV to JSONL without overwriting output. Python 3.10+, Linux."""
import argparse
import csv
import json
import os
from pathlib import Path
import sys
import tempfile


def convert(source, output):
    with source.open(encoding="utf-8-sig", newline="") as incoming:
        reader = csv.reader(incoming, strict=True)
        header = next(reader, None)
        if not header or any(not name.strip() for name in header):
            raise ValueError("missing or empty column name")
        if len(set(header)) != len(header):
            raise ValueError("duplicate column name")
        count = 0
        with tempfile.TemporaryDirectory(prefix=".csv-jsonl-", dir=output.parent) as work:
            staged = Path(work) / "result.jsonl"
            with staged.open("x", encoding="utf-8", newline="\n") as outgoing:
                for number, row in enumerate(reader, 1):
                    if len(row) != len(header):
                        raise ValueError(
                            f"record {number}, ending at CSV line {reader.line_num}: "
                            f"expected {len(header)} fields, got {len(row)}"
                        )
                    record = dict(zip(header, row))
                    outgoing.write(json.dumps(record, ensure_ascii=False) + "\n")
                    count += 1
            os.link(staged, output)
    return count


def main():
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    parser.add_argument("source", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    try:
        count = convert(args.source, args.output)
    except (OSError, UnicodeError, csv.Error, ValueError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    print(f"OK: {count} records -> {args.output}")
    return 0


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