#!/usr/bin/env python3
# branchage - age of git branches, sorted, with last commit
# Usage: branchage [path] [--all] [--days N]
import argparse, datetime, os, subprocess, sys

def human_age(ts):
    now = datetime.datetime.now(datetime.timezone.utc)
    then = datetime.datetime.fromtimestamp(ts, datetime.timezone.utc)
    delta = now - then
    days = delta.days
    if days == 0:
        hours = delta.seconds // 3600
        return "%d hour(s) ago" % hours if hours else "just now"
    if days < 30:
        return "%d day(s) ago" % days
    if days < 365:
        return "%d month(s) ago" % (days // 30)
    return "%d year(s) ago" % (days // 365)

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("x\n"); g("add", "."); g("commit", "-qm", "c1")
        g("checkout", "-qb", "old-branch"); g("checkout", "-q", "main")
        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 "old-branch" in out.stdout, out.stdout
        print("branchage selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="branchage",
        description="Age of git branches, sorted oldest first, with last commit.")
    ap.add_argument("path", nargs="?", default=".", help="path to the repo (default: .)")
    ap.add_argument("--all", action="store_true", help="include remote branches")
    ap.add_argument("--days", type=int, default=None, metavar="N",
                    help="only branches older than N days")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    r = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=a.path,
                       capture_output=True, text=True)
    if r.returncode != 0:
        print("branchage: not a git repository: %s" % a.path, file=sys.stderr); return 1
    cwd = r.stdout.strip()
    fmt = "%(refname:short)%09%(committerdate:unix)%09%(objectname:short)%09%(subject)"
    cmd = ["git", "for-each-ref", "--format=" + fmt, "--sort=committerdate",
           "refs/remotes" if a.all else "refs/heads"]
    out = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
    rows = []
    now = datetime.datetime.now(datetime.timezone.utc)
    for line in out.stdout.splitlines():
        parts = line.split("\t")
        if len(parts) == 4:
            try:
                ts = int(parts[1])
            except ValueError:
                continue
            age_days = (now - datetime.datetime.fromtimestamp(ts, datetime.timezone.utc)).days
            if a.days is not None and age_days < a.days:
                continue
            rows.append((ts, parts[0], parts[2], parts[3]))
    if not rows:
        print("branchage: no branches found."); return 0
    cur = subprocess.run(["git", "branch", "--show-current"], cwd=cwd,
                         capture_output=True, text=True).stdout.strip()
    print("branches by age (oldest first), %d:" % len(rows))
    for ts, name, short, subj in rows:
        mark = "*" if name == cur else " "
        print("  %s %-28s %-14s %-7s %s" % (mark, name, human_age(ts), short, subj[:60]))
    return 0

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