#!/usr/bin/env python3
"""archage - find archives older than X days and report their compression ratios.
Usage: archage [dir] [--days N] [--selftest] [--help]
Finds .zip/.tar.gz/.tgz/.tar.bz2/.tar.xz/.7z/.rar archives older than N days
(default 365), and for each reports the archive size, the uncompressed size
(read from the container's own index — zip central directory, tar listing,
gzip ISIZE — no full extraction), and the compression ratio. Old archives
with a ratio near 1.0 are barely compressed and are prime candidates for
re-packing or deletion.
"""
import argparse, gzip, io, os, struct, sys, tarfile, tempfile, time, zipfile
from pathlib import Path

ARCH_EXTS = {".zip", ".tgz", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar"}

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

def uncompressed_size(p):
    suf = p.suffix.lower()
    name = p.name.lower()
    try:
        if suf == ".zip":
            with zipfile.ZipFile(p) as z:
                return sum(i.file_size for i in z.infolist())
        if name.endswith((".tar.gz", ".tgz")):
            with tarfile.open(p, "r:gz") as t:
                return sum(m.size for m in t.getmembers() if m.isfile())
        if name.endswith((".tar.bz2", ".tbz2")):
            with tarfile.open(p, "r:bz2") as t:
                return sum(m.size for m in t.getmembers() if m.isfile())
        if name.endswith((".tar.xz", ".txz")):
            with tarfile.open(p, "r:xz") as t:
                return sum(m.size for m in t.getmembers() if m.isfile())
        if suf == ".tar":
            with tarfile.open(p, "r:") as t:
                return sum(m.size for m in t.getmembers() if m.isfile())
        if suf == ".gz":
            # ISIZE: last 4 bytes of a gzip member, little-endian
            with open(p, "rb") as f:
                f.seek(-4, os.SEEK_END)
                return struct.unpack("<I", f.read(4))[0]
    except Exception:
        return None
    return None

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        z = base / "old.zip"
        with zipfile.ZipFile(z, "w", zipfile.ZIP_DEFLATED) as f:
            f.writestr("data.txt", b"A" * 10000)
        old = time.time() - 400 * 86400
        os.utime(z, (old, old))
        (base / "fresh.zip").write_bytes(b"PK\x03\x04" + b"\x00" * 20)
        u = uncompressed_size(z)
        assert u == 10000, u
        ratio = z.stat().st_size / u
        assert ratio < 0.1, ratio
        print(f"selftest OK: old.zip uncompressed 10000 B, ratio {ratio:.3f} (highly compressible)")
        return 0

def main():
    ap = argparse.ArgumentParser(description="archage - old archives and their compression ratios")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--days", type=int, default=365)
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    root = Path(a.dir)
    if not root.is_dir():
        print(f"archage: {a.dir}: not a directory", file=sys.stderr); return 2
    cutoff = time.time() - a.days * 86400
    rows = []
    for p in sorted(root.rglob("*")):
        if not p.is_file():
            continue
        name = p.name.lower()
        if not (p.suffix.lower() in ARCH_EXTS or name.endswith((".tar.gz", ".tar.bz2", ".tar.xz"))):
            continue
        st = p.stat()
        if st.st_mtime >= cutoff:
            continue
        u = uncompressed_size(p)
        ratio = (st.st_size / u) if u else None
        rows.append((p, st, u, ratio))
    if not rows:
        print(f"no archives older than {a.days} days under {root}"); return 0
    print(f"{'ARCHIVE':<40} {'AGE':>6} {'SIZE':>10} {'UNPACKED':>10} {'RATIO':>6}")
    for p, st, u, ratio in sorted(rows, key=lambda r: -r[1].st_size):
        age_d = int((time.time() - st.st_mtime) / 86400)
        us = human(u) if u is not None else "?"
        rs = f"{ratio:.2f}" if ratio is not None else "?"
        flag = "  <-- barely compressed" if ratio is not None and ratio > 0.9 else ""
        print(f"{p.name:<40} {age_d:>5}d {human(st.st_size):>10} {us:>10} {rs:>6}{flag}")
    total = sum(r[1].st_size for r in rows)
    print(f"\n{len(rows)} old archive(s), {human(total)} on disk")
    return 0

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