#!/usr/bin/env python3
# gitdiffstat - diff stats between two refs with a per-file table
# Usage: gitdiffstat [REF1] [REF2] [--stat-width N] (defaults: REF1=HEAD, REF2=working tree)
import argparse, os, subprocess, sys

def selftest():
    import tempfile
    from pathlib import Path
    with tempfile.TemporaryDirectory() as d:
        env = dict(os.environ, GIT_AUTHOR_NAME="T", GIT_AUTHOR_EMAIL="t@t",
                   GIT_COMMITTER_NAME="T", GIT_COMMITTER_EMAIL="t@t")
        def g(*a):
            subprocess.run(["git"] + list(a), cwd=d, env=env, check=True, capture_output=True)
        g("init", "-q", "-b", "main")
        Path(d, "a.txt").write_text("one\ntwo\n"); g("add", "."); g("commit", "-qm", "c1")
        Path(d, "a.txt").write_text("one\ntwo\nthree\n"); g("add", "."); g("commit", "-qm", "c2")
        me = os.path.abspath(__file__)
        out = subprocess.run([sys.executable, me, "HEAD~1", "HEAD", d],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "a.txt" in out.stdout and "1" in out.stdout, out.stdout
        out = subprocess.run([sys.executable, me, "HEAD~1", d], capture_output=True, text=True)
        assert out.returncode == 0 and "a.txt" in out.stdout
        print("gitdiffstat selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="gitdiffstat",
        description="Diff stats between two refs with a per-file table.")
    ap.add_argument("ref1", nargs="?", default="HEAD", help="first ref (default HEAD)")
    ap.add_argument("ref2", nargs="?", default=None, help="second ref (default: working tree)")
    ap.add_argument("path", nargs="?", default=".", help="path to the repo (default: .)")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    # disambiguate: if ref2 looks like a path, treat as path
    if a.ref2 and os.path.exists(a.ref2):
        a.path, a.ref2 = a.ref2, None
    r = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=a.path,
                       capture_output=True, text=True)
    if r.returncode != 0:
        print("gitdiffstat: not a git repository: %s" % a.path, file=sys.stderr); return 1
    cwd = r.stdout.strip()
    cmd = ["git", "diff", "--numstat", a.ref1]
    if a.ref2:
        cmd.append(a.ref2)
    out = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
    if out.returncode != 0:
        print("gitdiffstat: %s" % out.stderr.strip(), file=sys.stderr); return 1
    rows, add, dele = [], 0, 0
    for line in out.stdout.splitlines():
        parts = line.split("\t")
        if len(parts) == 3:
            a_n = 0 if parts[0] == "-" else int(parts[0])
            d_n = 0 if parts[1] == "-" else int(parts[1])
            rows.append((parts[2], a_n, d_n))
            add += a_n; dele += d_n
    label = "%s..%s" % (a.ref1, a.ref2 or "working tree")
    if not rows:
        print("gitdiffstat: no differences between %s." % label); return 0
    print("diff %s: %d file(s), +%d / -%d" % (label, len(rows), add, dele))
    print("  %-50s %6s %6s" % ("file", "added", "removed"))
    for f, an, dn in sorted(rows, key=lambda x: -(x[1] + x[2])):
        bar = "+" * min(an, 20) + "-" * min(dn, 20)
        print("  %-50s %6d %6d  %s" % (f[:50], an, dn, bar))
    return 0

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