#!/usr/bin/env python3
"""csvstat — per-column CSV statistics: distinct values, nulls, min/max.
Usage: csvstat [--delimiter C] FILE
A column-by-column profile: type, distinct count, null count, min/max, and the
most common value. The fastest way to spot a column that is all nulls, all one
value, or full of junk before you feed the file to anything else.
"""
import argparse, collections, csv, sys


def parse_num(v):
    try:
        return float(v)
    except (TypeError, ValueError):
        return None


def main(argv=None):
    ap = argparse.ArgumentParser(prog="csvstat",
        description="Per-column CSV statistics: distinct values, nulls, min/max.")
    ap.add_argument("file", help="CSV file")
    ap.add_argument("--delimiter", help="column delimiter (auto-detected by default)")
    ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    argv_list = list(argv) if argv is not None else sys.argv[1:]
    if "--selftest" in argv_list:
        return selftest()
    a = ap.parse_args(argv)
    if a.selftest:
        return selftest()
    try:
        with open(a.file, newline="", encoding="utf-8-sig", errors="replace") as fh:
            if a.delimiter is None:
                head = fh.read(4096)
                fh.seek(0)
                try:
                    a.delimiter = csv.Sniffer().sniff(head, delimiters=",;\t|").delimiter
                except csv.Error:
                    a.delimiter = ","
            reader = csv.reader(fh, delimiter=a.delimiter)
            try:
                header = next(reader)
            except StopIteration:
                print("csvstat: empty file", file=sys.stderr)
                return 1
            stats = [{"nulls": 0, "distinct": collections.Counter(), "nums": [],
                      "min_s": None, "max_s": None} for _ in header]
            rows = 0
            for row in reader:
                rows += 1
                for i, st in enumerate(stats):
                    v = row[i] if i < len(row) else ""
                    if v == "":
                        st["nulls"] += 1
                        continue
                    st["distinct"][v] += 1
                    num = parse_num(v)
                    if num is not None:
                        st["nums"].append(num)
                    if st["min_s"] is None or v < st["min_s"]:
                        st["min_s"] = v
                    if st["max_s"] is None or v > st["max_s"]:
                        st["max_s"] = v
    except OSError as e:
        print(f"csvstat: {e}", file=sys.stderr)
        return 1
    print(f"csvstat: {a.file} — {rows} rows, {len(header)} columns")
    print(f"{'column':<20} {'type':<8} {'distinct':>8} {'nulls':>6}  {'min':<14} {'max':<14}  most common")
    for name, st in zip(header, stats):
        nonnull = rows - st["nulls"]
        if nonnull == 0:
            typ = "all-null"
        elif len(st["nums"]) == nonnull:
            typ = "numeric"
        else:
            typ = "text"
        if typ == "numeric":
            lo, hi = f"{min(st['nums']):g}", f"{max(st['nums']):g}"
        else:
            lo, hi = (st["min_s"] or "-")[:14], (st["max_s"] or "-")[:14]
        common = st["distinct"].most_common(1)
        common_s = f"{common[0][0][:18]} ({common[0][1]}x)" if common else "-"
        print(f"{name:<20} {typ:<8} {len(st['distinct']):>8} {st['nulls']:>6}  {lo:<14} {hi:<14}  {common_s}")
    return 0


def selftest():
    import tempfile, os, io
    from contextlib import redirect_stdout
    data = "city,amount,note\nreno,10,hi\nreno,20,hi\nvegas,5,lo\n"
    with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as fh:
        fh.write(data)
        path = fh.name
    try:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = main([path])
        out = buf.getvalue()
        assert rc == 0, out
        assert "numeric" in out and "10" in out and "20" in out, out
        assert "reno (2x)" in out, out
    finally:
        os.unlink(path)
    print("csvstat selftest: PASS")
    return 0


if __name__ == "__main__":
    sys.exit(main())
