#!/usr/bin/env python3
# zipls — list zip archive contents with sizes, per-file compression ratio and a totals summary, without extracting.
# Usage: zipls [--sort name|size|ratio] [--tree] [--duplicates] archive.zip [archive2.zip ...]
"""zipls: zip listing with compression insight. Unlike `unzip -l` it shows each
member's stored-vs-uncompressed ratio, flags encrypted members, spots duplicate
names/content sizes, and totals the archive's real compression."""
import argparse, os, sys, zipfile
from collections import Counter

METHODS = {0: "stored", 8: "deflate", 9: "deflate64", 12: "bzip2", 14: "lzma"}

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

def list_zip(path, sort="name", show_tree=False, show_dup=False):
    try:
        zf = zipfile.ZipFile(path)
    except Exception as e:
        print(f"zipls: {path}: {e}", file=sys.stderr); return 1
    infos = zf.infolist()
    if sort == "size":
        infos.sort(key=lambda i: -i.file_size)
    elif sort == "ratio":
        infos.sort(key=lambda i: -(1 - i.compress_size / i.file_size) if i.file_size else 0)
    else:
        infos.sort(key=lambda i: i.filename)
    tot_u = tot_c = 0
    print(f"{path}: {len(infos)} entries")
    print(f"{'name':<44} {'uncomp':>10} {'stored':>10} {'ratio':>7} method")
    for i in infos:
        tot_u += i.file_size; tot_c += i.compress_size
        ratio = (1 - i.compress_size / i.file_size) * 100 if i.file_size else 0.0
        enc = " 🔒" if i.flag_bits & 0x1 else ""
        name = i.filename
        if show_tree:
            name = ("  " * (name.rstrip("/").count("/"))) + os.path.basename(name.rstrip("/")) + ("/" if name.endswith("/") else "")
        print(f"{name[:44]:<44} {human(i.file_size):>10} {human(i.compress_size):>10} {ratio:6.1f}% {METHODS.get(i.compress_type, str(i.compress_type))}{enc}")
    overall = (1 - tot_c / tot_u) * 100 if tot_u else 0.0
    print(f"total: {len(infos)} entries, {human(tot_u)} -> {human(tot_c)} ({overall:.1f}% saved, {tot_u/max(tot_c,1):.2f}x)")
    if show_dup:
        names = Counter(i.filename for i in infos)
        dups = {k: v for k, v in names.items() if v > 1}
        print("duplicate names:", dups if dups else "none")
        sizes = Counter(i.file_size for i in infos if i.file_size)
        same = {k: v for k, v in sizes.items() if v > 1}
        print("members sharing an uncompressed size (possible dup content):", len(same))
    return 0

def selftest():
    import tempfile, zipfile
    with tempfile.TemporaryDirectory() as d:
        p = os.path.join(d, "t.zip")
        with zipfile.ZipFile(p, "w", zipfile.ZIP_DEFLATED) as z:
            z.writestr("a.txt", "hello world\n" * 200)
            z.writestr("b.bin", bytes(range(256)) * 4)
        assert list_zip(p) == 0
        assert list_zip(p, sort="ratio", show_dup=True) == 0
    print("zipls selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="List zip contents with per-file compression ratios and totals, without extracting.")
    ap.add_argument("archives", nargs="*", help="zip archive(s) to list")
    ap.add_argument("--sort", choices=["name", "size", "ratio"], default="name")
    ap.add_argument("--tree", action="store_true", help="indent entries by directory depth")
    ap.add_argument("--duplicates", action="store_true", help="report duplicate names/sizes")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.archives: ap.error("need at least one archive")
    return max(list_zip(p, a.sort, a.tree, a.duplicates) for p in a.archives)

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