"""Run from the directory containing inspect_csv.py. No third-party packages."""
import csv
import hashlib
import io
from pathlib import Path
import subprocess
import sys
import tempfile

script = Path("inspect_csv.py").resolve()
cases = [
    ("semicolon", b'id;note\n001;"alpha,beta"\n', "auto", 0, ";"),
    ("comma", b'id,note\n001,"alpha,beta"\n', "auto", 0, ","),
    ("tab", b'id\tnote\n001\talpha\n', "tab", 0, "\t"),
    ("pipe", b'id|note\n001|alpha\n', "pipe", 0, "|"),
    ("multiline", b'\xef\xbb\xbfid;note\r\n001;"a\nb"\r\n', "semicolon", 0, ";"),
    ("wrong", b'id;note\n001;alpha\n', "comma", 1, None),
    ("ragged", b'id;note\n001;alpha;extra\n', "semicolon", 1, None),
    ("blank", b'id;note\n\n', "semicolon", 1, None),
    ("quotes", b'id;note\n001;"unfinished\n', "semicolon", 1, None),
    ("encoding", b'id;note\n001;\xff\n', "semicolon", 1, None),
    ("empty", b'', "auto", 1, None),
]
with tempfile.TemporaryDirectory() as directory:
    for name, data, mode, expected, delimiter in cases:
        path = Path(directory) / (name + ".csv")
        path.write_bytes(data)
        before = hashlib.sha256(data).hexdigest()
        result = subprocess.run(
            [sys.executable, str(script), str(path), "--delimiter", mode,
             "--columns", "id", "note"], capture_output=True, text=True
        )
        assert result.returncode == expected, (name, result.stderr)
        assert hashlib.sha256(path.read_bytes()).hexdigest() == before
        if expected == 0:
            import json
            report = json.loads(result.stdout)
            assert report["delimiter"] == delimiter
            assert report["records"] == 1 and not result.stderr
        else:
            assert not result.stdout and result.stderr.startswith("ERROR:")
        print(f"PASS {name}: exit={expected}")
# A naive split breaks the quoted comma; csv.reader preserves it.
assert '001,"alpha,beta"'.split(",") != ["001", "alpha,beta"]
assert next(csv.reader(io.StringIO('001,"alpha,beta"'))) == ["001", "alpha,beta"]
print("PASS quoted comma: field values preserved")
