#!/usr/bin/env python3
"""namefix - rename files to a safe portable scheme (strip weird chars, optional lowercase) with an undo log.
Usage: namefix [dir] [--lower] [--dry-run] [--undo LOG] [--selftest] [--help]
Rewrites names to [A-Za-z0-9._-]+ (spaces -> _, other runs -> _), collapses
repeated underscores, keeps the extension. Every rename is appended to an
undo log (JSON, default <dir>/.namefix-undo.json); `namefix --undo LOG`
reverses a previous run. --dry-run prints the plan and writes no log.
"""
import argparse, json, os, re, sys, tempfile
from pathlib import Path

def safe_name(name, lower=False):
    stem, dot, ext = name.rpartition(".")
    if not dot:
        stem, ext = name, ""
    else:
        ext = "." + ext
    s = re.sub(r"[^A-Za-z0-9._-]+", "_", stem)
    s = re.sub(r"_+", "_", s).strip("._")
    if not s:
        s = "file"
    if lower:
        s = s.lower(); ext = ext.lower()
    return s + ext

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        (base / "My  File (1).TXT").write_text("x")
        (base / "caf\u00e9 & tea!.md").write_text("y")
        (base / "already_ok.txt").write_text("z")
        log = base / "undo.json"
        import subprocess
        r = subprocess.run([sys.executable, __file__, str(base), "--undo-log", str(log)],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        names = sorted(p.name for p in base.iterdir() if p.is_file() and p.name != "undo.json")
        assert "My_File_1.TXT" in names, names
        assert "already_ok.txt" in names
        assert log.exists()
        r = subprocess.run([sys.executable, __file__, "--undo", str(log)],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        names = sorted(p.name for p in base.iterdir() if p.is_file() and p.name != "undo.json")
        assert "My  File (1).TXT" in names, names
        print("selftest OK: renamed to safe names and undid them from the log")
        return 0

def main():
    ap = argparse.ArgumentParser(description="namefix - rename files to a safe portable scheme, with undo")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--lower", action="store_true", help="also lowercase names")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--undo-log", metavar="FILE", help="undo log path (default <dir>/.namefix-undo.json)")
    ap.add_argument("--undo", metavar="FILE", help="reverse the renames recorded in LOG")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if a.undo:
        with open(a.undo) as f:
            entries = json.load(f)
        n = 0
        for e in reversed(entries):
            src, dst = Path(e["to"]), Path(e["from"])
            if src.exists() and not dst.exists():
                src.rename(dst); n += 1
                print(f"restored {src} -> {dst}")
            else:
                print(f"skip {src}: missing or target exists", file=sys.stderr)
        print(f"undid {n} rename(s)")
        return 0
    root = Path(a.dir)
    if not root.is_dir():
        print(f"namefix: {a.dir}: not a directory", file=sys.stderr); return 2
    logpath = Path(a.undo_log) if a.undo_log else root / ".namefix-undo.json"
    entries, taken = [], set()
    for p in sorted(root.rglob("*")):
        if not p.is_file() or p.resolve() == logpath.resolve():
            continue
        new = safe_name(p.name, a.lower)
        if new == p.name:
            continue
        target = p.with_name(new)
        i = 1
        while target.exists() or str(target) in taken:
            stem, dot, ext = new.rpartition(".")
            target = p.with_name(f"{stem}_{i}{dot}{ext}" if dot else f"{new}_{i}")
            i += 1
        taken.add(str(target))
        entries.append({"from": str(p), "to": str(target)})
    if not entries:
        print("nothing to rename"); return 0
    for e in entries:
        print(f"{e['from']} -> {e['to']}")
    if a.dry_run:
        print(f"dry-run: {len(entries)} rename(s), nothing changed"); return 0
    for e in entries:
        Path(e["from"]).rename(e["to"])
    with open(logpath, "w") as f:
        json.dump(entries, f, indent=2)
    print(f"renamed {len(entries)} file(s); undo log {logpath} (namefix --undo {logpath})")
    return 0

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