#!/usr/bin/env python3
# gitclean - find and remove stale git branches (merged, or with no upstream) with a preview
# Usage: gitclean [--merged] [--gone] [--older-than DAYS] [--base BRANCH] [--apply|--yes] [--dry-run]
import argparse, datetime, os, subprocess, sys

def run(args, cwd):
    return subprocess.run(args, cwd=cwd, capture_output=True, text=True)

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, check=True):
            return subprocess.run(["git"] + list(a), cwd=d, env=env, check=check,
                                  capture_output=True, text=True)
        g("init", "-q", "-b", "main")
        Path(d, "a.txt").write_text("x\n"); g("add", "."); g("commit", "-qm", "c1")
        g("checkout", "-qb", "feature"); Path(d, "b.txt").write_text("y\n")
        g("add", "."); g("commit", "-qm", "c2"); g("checkout", "-q", "main")
        g("merge", "-q", "--ff-only", "feature")
        me = os.path.abspath(__file__)
        out = subprocess.run([sys.executable, me, "--merged", d], capture_output=True, text=True)
        assert out.returncode == 0 and "feature" in out.stdout, out.stdout + out.stderr
        # preview must NOT delete
        assert g("branch", "--list", "feature").stdout.strip()
        out = subprocess.run([sys.executable, me, "--merged", "--apply", d],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert not g("branch", "--list", "feature").stdout.strip()
        print("gitclean selftest: PASS")
    return 0

def branch_date(cwd, br):
    r = run(["git", "log", "-1", "--format=%ct", br], cwd)
    try:
        return datetime.datetime.fromtimestamp(int(r.stdout.strip()), datetime.timezone.utc)
    except ValueError:
        return None

def main():
    ap = argparse.ArgumentParser(prog="gitclean",
        description="Find stale git branches (merged, or with no upstream) and preview them; deletes only with --apply/--yes.")
    ap.add_argument("path", nargs="?", default=".", help="path to the repo (default: .)")
    ap.add_argument("--merged", action="store_true", help="include branches merged into --base (default: on)")
    ap.add_argument("--gone", action="store_true", help="include branches whose upstream is gone")
    ap.add_argument("--older-than", type=int, default=None, metavar="DAYS",
                    help="only branches whose last commit is older than DAYS")
    ap.add_argument("--base", default=None, help="base branch for --merged (default: current branch)")
    ap.add_argument("--apply", "--yes", dest="apply", action="store_true",
                    help="actually delete the listed branches (default: preview only)")
    ap.add_argument("--dry-run", action="store_true", help="preview only, even with --apply")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if a.merged is False and not a.gone and a.older_than is None:
        a.merged = True
    root = run(["git", "rev-parse", "--show-toplevel"], a.path)
    if root.returncode != 0:
        print("gitclean: not a git repository: %s" % a.path, file=sys.stderr); return 1
    cwd = root.stdout.strip()
    cur = run(["git", "branch", "--show-current"], cwd).stdout.strip()
    base = a.base or cur or "main"
    keep = {cur, "main", "master", base}
    stale = {}  # branch -> reason
    if a.merged:
        r = run(["git", "branch", "--merged", base, "--format=%(refname:short)"], cwd)
        for br in r.stdout.splitlines():
            br = br.strip()
            if br and br not in keep:
                stale[br] = "merged into %s" % base
    if a.gone:
        r = run(["git", "branch", "-vv", "--format=%(refname:short) %(upstream:track)"], cwd)
        for line in r.stdout.splitlines():
            parts = line.split()
            if len(parts) >= 2 and parts[1] == "[gone]":
                stale.setdefault(parts[0], "upstream gone")
    if a.older_than is not None:
        cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=a.older_than)
        r = run(["git", "branch", "--format=%(refname:short)"], cwd)
        for br in r.stdout.splitlines():
            br = br.strip()
            if br in keep or br in stale:
                continue
            d = branch_date(cwd, br)
            if d and d < cutoff:
                stale[br] = "last commit %s" % d.date()
    if not stale:
        print("gitclean: no stale branches found."); return 0
    print("stale branches in %s (base: %s):" % (cwd, base))
    for br in sorted(stale):
        d = branch_date(cwd, br)
        print("  %-30s %-22s %s" % (br, stale[br], ("last commit %s" % d.date()) if d else ""))
    if not a.apply or a.dry_run:
        print("\nPreview only — nothing deleted. Re-run with --apply to delete these %d branch(es)." % len(stale))
        return 0
    deleted = failed = 0
    for br in sorted(stale):
        r = run(["git", "branch", "-d", br], cwd)
        if r.returncode == 0:
            print("deleted: %s" % br); deleted += 1
        else:
            print("FAILED to delete %s: %s" % (br, r.stderr.strip()), file=sys.stderr); failed += 1
    print("gitclean: deleted %d, failed %d." % (deleted, failed))
    return 1 if failed else 0

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