#!/usr/bin/env python3
# gitstat - one-page git repo summary: branch, status counts, recent commits, stashes
# Usage: gitstat [path] [-n N] [--json]
import argparse, json, os, subprocess, sys

def run(args, cwd):
    r = subprocess.run(args, cwd=cwd, capture_output=True, text=True)
    return r.stdout.strip(), r.returncode

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("hello\n")
        g("add", "."); g("commit", "-qm", "first commit")
        Path(d, "b.txt").write_text("untracked\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), d],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "main" in out.stdout and "first commit" in out.stdout
        assert "Untracked" in out.stdout or "untracked" in out.stdout.lower()
        print("gitstat selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="gitstat",
        description="One-page git repo summary: branch, status counts, recent commits, stashes.")
    ap.add_argument("path", nargs="?", default=".", help="path to the repo (default: .)")
    ap.add_argument("-n", "--commits", type=int, default=5, help="recent commits to show (default 5)")
    ap.add_argument("--json", action="store_true", help="emit JSON instead of text")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    root, rc = run(["git", "rev-parse", "--show-toplevel"], a.path)
    if rc != 0:
        print("gitstat: not a git repository: %s" % a.path, file=sys.stderr)
        return 1
    branch, _ = run(["git", "branch", "--show-current"], root)
    head, _ = run(["git", "rev-parse", "--short", "HEAD"], root)
    status, _ = run(["git", "status", "--porcelain"], root)
    counts = {"staged": 0, "modified": 0, "deleted": 0, "untracked": 0, "renamed": 0}
    for line in status.splitlines():
        x, y = line[0], line[1]
        if line.startswith("??"):
            counts["untracked"] += 1
        else:
            if x not in (" ", "?"): counts["staged"] += 1
            if y == "M": counts["modified"] += 1
            if y == "D": counts["deleted"] += 1
            if x == "R" or y == "R": counts["renamed"] += 1
    upstream, urc = run(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], root)
    ahead = behind = None
    if urc == 0:
        ab, _ = run(["git", "rev-list", "--left-right", "--count", "HEAD...@{u}"], root)
        try:
            ahead, behind = (int(x) for x in ab.split())
        except ValueError:
            pass
    stash, _ = run(["git", "stash", "list"], root)
    nstash = len([l for l in stash.splitlines() if l.strip()])
    log, _ = run(["git", "log", "--oneline", "--decorate", "-n", str(a.commits)], root)
    remotes, _ = run(["git", "remote", "-v"], root)
    data = {"repo": root, "branch": branch or "(detached)", "head": head,
            "status": counts, "ahead": ahead, "behind": behind,
            "upstream": upstream if urc == 0 else None,
            "stashes": nstash, "recent_commits": log.splitlines(),
            "remotes": sorted(set(l.split()[0] for l in remotes.splitlines()))}
    if a.json:
        print(json.dumps(data, indent=2)); return 0
    print("repo     : %s" % root)
    print("branch   : %s  (%s)%s" % (data["branch"], head,
          ("  upstream: %s  ahead %s / behind %s" % (upstream, ahead, behind)) if urc == 0 else "  (no upstream)"))
    print("status   : staged %d, modified %d, deleted %d, renamed %d, untracked %d" % (
        counts["staged"], counts["modified"], counts["deleted"], counts["renamed"], counts["untracked"]))
    print("stashes  : %d" % nstash)
    print("remotes  : %s" % (", ".join(data["remotes"]) or "none"))
    print("recent commits:")
    for line in data["recent_commits"] or ["(none)"]:
        print("  %s" % line)
    return 0

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