#!/usr/bin/env python3
# repocheck - health check for a git repo: uncommitted, untracked, ahead/behind, large files
# Usage: repocheck [path] [--max-size MB] [--fail]
import argparse, 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):
            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")
        import tempfile as _tf
        with _tf.TemporaryDirectory() as _bd:
            bare = os.path.join(_bd, "bare.git")
            subprocess.run(["git", "init", "-q", "--bare", bare], check=True, capture_output=True)
            g("remote", "add", "origin", bare); g("push", "-q", "-u", "origin", "main")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), d],
                             capture_output=True, text=True)
        assert out.returncode == 0 and "CLEAN" in out.stdout, out.stdout
        Path(d, "big.bin").write_bytes(b"\0" * (2 * 1024 * 1024))
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "--max-size", "1", d],
                             capture_output=True, text=True)
        assert "large file" in out.stdout.lower() or "big.bin" in out.stdout, out.stdout
        print("repocheck selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="repocheck",
        description="Health check for a git repo: uncommitted, untracked, ahead/behind, large files.")
    ap.add_argument("path", nargs="?", default=".", help="path to the repo (default: .)")
    ap.add_argument("--max-size", type=float, default=5, metavar="MB",
                    help="flag tracked files larger than this (MB, default 5)")
    ap.add_argument("--fail", action="store_true", help="exit 1 if any warning is found")
    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 = run(["git", "rev-parse", "--show-toplevel"], a.path)
    if r.returncode != 0:
        print("repocheck: not a git repository: %s" % a.path, file=sys.stderr); return 1
    cwd = r.stdout.strip()
    ok, warn = [], []

    def check(name, is_bad, detail):
        (warn if is_bad else ok).append("%s: %s" % (name, detail))

    st = run(["git", "status", "--porcelain"], cwd).stdout.splitlines()
    staged = sum(1 for l in st if l and l[0] not in (" ", "?"))
    modified = sum(1 for l in st if len(l) > 1 and l[1] == "M")
    untracked = sum(1 for l in st if l.startswith("??"))
    check("uncommitted", bool(staged or modified),
          "%d staged, %d modified" % (staged, modified) if (staged or modified) else "working tree clean")
    check("untracked", untracked > 0,
          "%d untracked file(s)" % untracked if untracked else "no untracked files")
    up = run(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], cwd)
    if up.returncode != 0:
        warn.append("upstream: no upstream branch configured")
    else:
        ab = run(["git", "rev-list", "--left-right", "--count", "HEAD...@{u}"], cwd).stdout.split()
        ahead, behind = (int(x) for x in ab) if len(ab) == 2 else (0, 0)
        check("sync", bool(ahead or behind),
              "ahead %d, behind %d" % (ahead, behind) if (ahead or behind) else "in sync with %s" % up.stdout.strip())
    stash = run(["git", "stash", "list"], cwd).stdout.splitlines()
    check("stashes", len(stash) > 2, "%d stash(es)" % len(stash) if stash else "no stashes")
    br = run(["git", "branch", "--show-current"], cwd).stdout.strip()
    check("branch", not br, "detached HEAD" if not br else "on branch %s" % br)
    big = []
    ls = run(["git", "ls-files", "-s"], cwd).stdout.splitlines()
    for line in ls:
        parts = line.split()
        if len(parts) >= 4:
            blob = parts[1]
            size = run(["git", "cat-file", "-s", blob], cwd).stdout.strip()
            try:
                sz = int(size)
            except ValueError:
                continue
            if sz > a.max_size * 1024 * 1024:
                big.append((parts[3], sz))
    check("large files", bool(big),
          ", ".join("%s (%.1f MB)" % (f, s / 1048576) for f, s in big) if big
          else "no tracked file over %.1f MB" % a.max_size)
    print("repocheck: %s" % cwd)
    for item in ok:
        print("  OK    %s" % item)
    for item in warn:
        print("  WARN  %s" % item)
    if not warn:
        print("repocheck: CLEAN — no issues found.")
    else:
        print("repocheck: %d warning(s)." % len(warn))
    return 1 if (warn and a.fail) else 0

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