#!/usr/bin/env python3
"""synccheck - dry-run rsync-style diff between two directories (what would change).
Usage: synccheck SOURCE DEST [--delete] [--selftest]
Shows what a sync would copy (new/modified files), what it would skip, and
with --delete what it would remove from DEST. Nothing is ever changed."""
import argparse, os, sys

def human(n):
    for u in ("B", "K", "M", "G", "T"):
        if abs(n) < 1024 or u == "T":
            return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
        n /= 1024.0
    return f"{n:.1f}T"

def inventory(root):
    inv = {}
    for cur, _dirs, files in os.walk(root):
        for name in files:
            p = os.path.join(cur, name)
            rel = os.path.relpath(p, root)
            try:
                st = os.lstat(p)
            except OSError:
                continue
            inv[rel] = (st.st_size, int(st.st_mtime))
    return inv

def diff(src, dst, delete=False):
    s_inv = inventory(src)
    d_inv = inventory(dst)
    to_copy, to_delete, unchanged = [], [], []
    for rel, (sz, mt) in s_inv.items():
        if rel not in d_inv:
            to_copy.append((rel, sz, "new"))
        elif d_inv[rel] != (sz, mt):
            to_copy.append((rel, sz, "modified"))
        else:
            unchanged.append(rel)
    if delete:
        for rel, (sz, _mt) in d_inv.items():
            if rel not in s_inv:
                to_delete.append((rel, sz))
    return to_copy, to_delete, unchanged

def selftest():
    import tempfile
    tmp = tempfile.mkdtemp(prefix="synccheck-test-")
    src, dst = os.path.join(tmp, "src"), os.path.join(tmp, "dst")
    os.makedirs(src); os.makedirs(dst)
    def w(d, name, content):
        with open(os.path.join(d, name), "wb") as f:
            f.write(content)
    w(src, "new.txt", b"brand new")
    w(src, "mod.txt", b"v2")
    w(dst, "mod.txt", b"v1-much-longer-content")
    w(src, "same.txt", b"same")
    w(dst, "same.txt", b"same")
    import time
    # make mtimes match for same.txt by copying timestamps
    st = os.stat(os.path.join(src, "same.txt"))
    os.utime(os.path.join(dst, "same.txt"), (st.st_atime, st.st_mtime))
    w(dst, "stale.txt", b"gone from source")
    to_copy, to_delete, unchanged = diff(src, dst, delete=True)
    ok = True
    kinds = {rel: k for rel, _sz, k in to_copy}
    if kinds.get("new.txt") != "new" or kinds.get("mod.txt") != "modified":
        print(f"FAIL: to_copy wrong: {to_copy}"); ok = False
    if "same.txt" not in unchanged:
        print("FAIL: unchanged file not recognised"); ok = False
    if [rel for rel, _ in to_delete] != ["stale.txt"]:
        print(f"FAIL: to_delete wrong: {to_delete}"); ok = False
    _c, no_del, _u = diff(src, dst, delete=False)
    if no_del:
        print("FAIL: delete listed without --delete"); ok = False
    import shutil; shutil.rmtree(tmp, ignore_errors=True)
    if ok:
        print("selftest: PASS (new + modified to copy, 1 unchanged, stale only with --delete)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="synccheck",
        description="Dry-run rsync-style diff between two directories (what would change).")
    ap.add_argument("source", nargs="?", help="source tree")
    ap.add_argument("dest", nargs="?", help="destination tree")
    ap.add_argument("--delete", action="store_true", help="also report files that would be deleted from DEST")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks on temp trees")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.source or not a.dest:
        ap.error("SOURCE and DEST are required")
    if not os.path.isdir(a.source) or not os.path.isdir(a.dest):
        print("error: both SOURCE and DEST must be directories", file=sys.stderr)
        return 2
    to_copy, to_delete, unchanged = diff(a.source, a.dest, a.delete)
    total = sum(sz for _r, sz, _k in to_copy)
    print(f"sync {a.source} -> {a.dest} (dry run, nothing changed)")
    print(f"to copy: {len(to_copy)} file(s), {human(total)}")
    for rel, sz, kind in sorted(to_copy):
        print(f"  {kind:<9} {human(sz):>10}  {rel}")
    if a.delete:
        print(f"to delete: {len(to_delete)} file(s)")
        for rel, sz in sorted(to_delete):
            print(f"  delete    {human(sz):>10}  {rel}")
    else:
        extra = len(inventory(a.dest)) - len([r for r in inventory(a.dest) if r in inventory(a.source)])
        if extra:
            print(f"note: {extra} file(s) exist only in DEST (re-run with --delete to list them)")
    print(f"unchanged: {len(unchanged)} file(s)")
    return 0

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