#!/usr/bin/env python3
"""Reproduce CSV record/line/field examples with synthetic input only.

Usage: python3 csv-record-boundaries.py [output-directory]
Python 3.9+; standard library only. Writes sample.csv and results.json.
"""

import csv
from datetime import datetime
import hashlib
import io
import json
from pathlib import Path
import platform
import sys


HEADER = ["id", "name", "note"]
SAMPLE = [HEADER,
          ["00123", "谷米", "逗号,保留"],
          ["00456", '道具 "A"', "第一行\r\n第二行"],
          ["00789", "東京", ""],
          ["01000", "大阪", "独立CR\rとLF\n"],
          ["01001", "スペース", " 前後の空白 "]]


def write_rows(stream, rows):
    csv.writer(stream, delimiter=",", quotechar='"', doublequote=True,
               quoting=csv.QUOTE_MINIMAL, lineterminator="\r\n").writerows(rows)


def read_rows(stream):
    reader = csv.reader(stream, delimiter=",", quotechar='"', doublequote=True,
                        quoting=csv.QUOTE_MINIMAL, skipinitialspace=False, strict=True)
    rows, end_lines = [], []
    for row in reader:
        rows.append(row)
        end_lines.append(reader.line_num)
    return rows, end_lines


def contract_issues(rows):
    """Only this example's header and three-field contract, not all CSV rules."""
    issues = []
    if not rows or rows[0] != HEADER:
        issues.append("Expected the exact header id,name,note")
    for record_no, row in enumerate(rows[1:], 2):
        if len(row) != 3:
            issues.append(f"Record {record_no}: expected 3 fields, got {len(row)}")
    return issues


def main():
    output = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("csv-record-output")
    output.mkdir(parents=True, exist_ok=True)
    sample = output / "sample.csv"
    with sample.open("w", encoding="utf-8", newline="") as stream:
        write_rows(stream, SAMPLE)
    raw = sample.read_bytes()
    text = raw.decode("utf-8")
    with sample.open(encoding="utf-8", newline="") as stream:
        rows, end_lines = read_rows(stream)
    assert rows == SAMPLE and not contract_issues(rows)
    buffer = io.StringIO(newline="")
    write_rows(buffer, rows)
    same_bytes = buffer.getvalue().encode("utf-8") == raw
    assert same_bytes
    naive = [line.split(",") for line in text.splitlines()]
    assert naive != SAMPLE
    with sample.open(encoding="utf-8") as stream:
        normalized, _ = read_rows(stream)
    changed = [{"record": i + 1, "field": j + 1, "before": before, "after": after}
               for i, (old_row, new_row) in enumerate(zip(rows, normalized))
               for j, (before, after) in enumerate(zip(old_row, new_row)) if before != after]
    assert len(normalized) == len(rows) and len(changed) == 2
    cases = []
    for label, data in (
            ("unterminated_quoted_field", 'id,name,note\r\n1,甲,"unterminated\r\n'),
            ("character_after_closing_quote", 'id,name,note\r\n1,甲,"closed"x\r\n'),
            ("short_record", 'id,name,note\r\n1,甲\r\n'),
            ("long_record", 'id,name,note\r\n1,甲,备注,extra\r\n'),
            ("duplicate_header", 'id,id,note\r\n1,2,x\r\n'),
            ("quote_in_unquoted_field", 'id,name,note\r\n1,甲,bare"quote\r\n'),
            ("empty_file", "")):
        try:
            parsed, lines = read_rows(io.StringIO(data, newline=""))
        except csv.Error as error:
            cases.append({"case": label, "input": data, "parser": "csv.Error",
                          "error": str(error)})
        else:
            cases.append({"case": label, "input": data, "parser": "accepted",
                          "rows": parsed, "record_end_source_lines": lines,
                          "contract_issues": contract_issues(parsed)})
    assert [x["case"] for x in cases if x["parser"] == "csv.Error"] == [
        "unterminated_quoted_field", "character_after_closing_quote"]
    bare_quote = next(x for x in cases if x["case"] == "quote_in_unquoted_field")
    assert bare_quote["rows"][1][2] == 'bare"quote' and not bare_quote["contract_issues"]
    nullable = io.StringIO(newline="")
    write_rows(nullable, [["", None]])
    restored, _ = read_rows(io.StringIO(nullable.getvalue(), newline=""))
    assert restored == [["", ""]]
    report = {
        "recorded_at": datetime.now().astimezone().isoformat(),
        "environment": {"implementation": platform.python_implementation(),
                        "python": platform.python_version(), "system": platform.system(),
                        "macos": platform.mac_ver()[0], "machine": platform.machine()},
        "input_kind": "synthetic teaching data; no personal or production records",
        "format": {"encoding": "utf-8", "delimiter": ",", "quotechar": '"',
                   "doublequote": True, "quoting": "QUOTE_MINIMAL", "strict_reader": True,
                   "skipinitialspace": False, "writer_record_terminator": "\r\n"},
        "baseline": {"sample_file": "sample.csv", "sha256": hashlib.sha256(raw).hexdigest(),
                     "sample_text": text, "rows": rows, "record_count_including_header": len(rows),
                     "record_end_source_lines": end_lines, "cells_equal_input": rows == SAMPLE,
                     "same_writer_rewrite_bytes_equal": same_bytes,
                     "naive_split_rows": naive, "naive_row_count": len(naive),
                     "naive_field_counts": [len(row) for row in naive]},
        "default_newline_none": {"record_count_including_header": len(normalized),
                                 "changed_cells": changed},
        "boundary_cases": cases,
        "empty_string_and_none": {"input": ["", None], "serialized_csv": nullable.getvalue(),
                                  "restored": restored[0], "roundtrip_equal": False},
        "scope": "Only the stated Python csv/IO settings and small synthetic cases. Not an RFC conformance suite, Excel/Numbers/database integration, dialect detector, performance test or full application schema validator.",
    }
    (output / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n",
                                         encoding="utf-8")
    print(json.dumps({"environment": report["environment"], "records": len(rows),
                      "record_end_source_lines": end_lines, "naive_rows": len(naive),
                      "naive_field_counts": report["baseline"]["naive_field_counts"],
                      "newline_changed_cells": changed,
                      "boundaries": [{k: v for k, v in x.items() if k in
                                      ("case", "parser", "error", "contract_issues")} for x in cases],
                      "empty_string_and_none": report["empty_string_and_none"]},
                     ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
