#!/usr/bin/env python3
# archratio — compression ratio of every archive in a directory, ranked, with totals.
# Usage: archratio [--min-size MB] [--recursive] [directory]
"""archratio: rank a directory's archives by how well they compress. It opens
each zip/tarball, compares stored size against uncompressed content, and ranks
them — surfacing archives stored uncompressed (ratio ~1.0x) that are wasting
space, and the best-compressed ones."""
import argparse, os, sys, tarfile, zipfile

EXTS = (".zip", ".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz", ".tbz2", ".txz", ".jar", ".whl")

def human(n):
    for u in ("B", "KiB", "MiB", "GiB", "TiB"):
        if abs(n) < 1024 or u == "TiB":
            return f"{n:.1f}{u}" if u != "B" else f"{n}B"
        n /= 1024.0

def ratio_of(path):
    try:
        if path.endswith(".zip") or path.endswith((".jar", ".whl")):
            with zipfile.ZipFile(path) as z:
                u = sum(i.file_size for i in z.infolist()); return u, os.path.getsize(path)
        with tarfile.open(path, "r:*") as t:
            u = sum(m.size for m in t.getmembers() if m.isfile()); return u, os.path.getsize(path)
    except Exception as e:
        return None, str(e)

def scan(directory, recursive=False, min_size=0):
    rows = []
    for root, dirs, files in os.walk(directory):
        for f in files:
            if f.lower().endswith(EXTS):
                p = os.path.join(root, f)
                if os.path.getsize(p) < min_size: continue
                rows.append(p)
        if not recursive: break
    out = []
    for p in rows:
        u, c = ratio_of(p)
        if u is None:
            print(f"{p}: unreadable ({c})", file=sys.stderr); continue
        out.append((p, u, c))
    out.sort(key=lambda r: -(r[1] / max(r[2], 1)))
    print(f"{'ratio':>6} {'saved':>6} {'uncomp':>10} {'stored':>10}  archive")
    tot_u = tot_c = 0
    for p, u, c in out:
        tot_u += u; tot_c += c
        print(f"{u/max(c,1):6.2f}x {(1-c/u)*100 if u else 0:5.1f}% {human(u):>10} {human(c):>10}  {p}")
    if out:
        print(f"total: {len(out)} archives, {human(tot_u)} -> {human(tot_c)} ({tot_u/max(tot_c,1):.2f}x overall)")
        worst = min(out, key=lambda r: r[1] / max(r[2], 1))
        print(f"worst compression: {worst[0]} ({worst[1]/max(worst[2],1):.2f}x) — candidate for recompression")
    else:
        print("no archives found")
    return 0

def selftest():
    import tempfile, zipfile, tarfile, io
    with tempfile.TemporaryDirectory() as d:
        with zipfile.ZipFile(os.path.join(d, "good.zip"), "w", zipfile.ZIP_DEFLATED) as z:
            z.writestr("a.txt", "hello\n" * 1000)
        with zipfile.ZipFile(os.path.join(d, "flat.zip"), "w", zipfile.ZIP_STORED) as z:
            z.writestr("a.txt", "hello\n" * 1000)
        assert scan(d) == 0
    print("archratio selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Rank archives in a directory by compression ratio.")
    ap.add_argument("directory", nargs="?", default=".", help="directory to scan")
    ap.add_argument("--recursive", "-r", action="store_true")
    ap.add_argument("--min-size", type=float, default=0, help="ignore archives smaller than this many MB")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    return scan(a.directory, a.recursive, int(a.min_size * 1024 * 1024))

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