"""Reproduce synthetic CSV observations; this is not a production importer."""
import csv
import io
import json
import sys
from pathlib import Path


def observe(text, expected_header):
    reader = csv.reader(io.StringIO(text, newline=""), delimiter=",", quotechar='"',
                        doublequote=True, strict=True, skipinitialspace=False)
    header = None
    rows = []
    parse_error = False
    try:
        header = next(reader)
        for row in reader:
            rows.append(row)
    except (csv.Error, StopIteration):
        parse_error = True
    header_matches = header == expected_header
    widths = [len(row) for row in rows]
    hold = parse_error or not header_matches or any(n != len(expected_header) for n in widths)
    return {
        "physicalLines": len(text.splitlines()),
        "parsedDataRecords": len(rows),
        "rowWidths": widths,
        "headerMatches": header_matches,
        "parseError": parse_error,
        "decision": "hold-file" if hold else "candidate",
    }


def main():
    source = Path(__file__).with_name("scm-csv-record-fixtures.json")
    data = json.loads(source.read_text(encoding="utf-8"))
    observations = []
    for sample in data["samples"]:
        actual = observe(sample["input"], data["expectedHeader"])
        assert actual == sample["expected"], (sample["name"], actual, sample["expected"])
        observations.append({"name": sample["name"], **actual})
    print(json.dumps({"python": sys.version.split()[0], "scope": data["scope"],
                      "observations": observations, "pass": True}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
