#!/usr/bin/env python3
"""similar - find near-duplicate filenames (fuzzy match) that may be duplicates under different names.
Usage: similar [dir] [--threshold 0.0-1.0] [--selftest] [--help]
Compares every pair of filenames with difflib's ratio (plus a normalized
form that strips case, punctuation, spaces and common suffixes like
"(1)", "copy", "final", "v2"), and reports pairs above the threshold
(default 0.8). Catches report-final-FINAL.pdf vs report.pdf — the duplicates
a content hash can never find because the names differ.
"""
import argparse, difflib, re, sys, tempfile
from pathlib import Path

STRIP_WORDS = re.compile(r"\b(copy|final|new|v\d+|\(\d+\)|-\d+)\b", re.I)

def normalize(name):
    stem = Path(name).stem
    stem = STRIP_WORDS.sub("", stem)
    stem = re.sub(r"[^a-z0-9]+", "", stem.lower())
    return stem

def find_pairs(names, threshold=0.8):
    pairs = []
    n = len(names)
    for i in range(n):
        for j in range(i + 1, n):
            a, b = names[i], names[j]
            raw = difflib.SequenceMatcher(None, a.lower(), b.lower()).ratio()
            norm = difflib.SequenceMatcher(None, normalize(a), normalize(b)).ratio()
            score = max(raw, norm)
            if score >= threshold:
                pairs.append((score, a, b))
    pairs.sort(key=lambda t: -t[0])
    return pairs

def selftest():
    names = ["report-final.pdf", "report.pdf", "photo (1).jpg", "photo.jpg",
             "notes.txt", "totally-different.docx"]
    pairs = find_pairs(names, 0.8)
    found = {(a, b) for _, a, b in pairs}
    assert ("report-final.pdf", "report.pdf") in found or ("report.pdf", "report-final.pdf") in found, found
    assert any("photo" in a and "photo" in b for _, a, b in pairs), found
    assert not any("totally-different" in a or "totally-different" in b for _, a, b in pairs), found
    print(f"selftest OK: found {len(pairs)} near-duplicate pair(s), unrelated file excluded")
    return 0

def main():
    ap = argparse.ArgumentParser(description="similar - find near-duplicate filenames (fuzzy match)")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--threshold", type=float, default=0.8)
    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"similar: {a.dir}: not a directory", file=sys.stderr); return 2
    names = sorted(p.name for p in root.rglob("*") if p.is_file())
    if len(names) < 2:
        print("need at least 2 files to compare"); return 0
    pairs = find_pairs(names, a.threshold)
    if not pairs:
        print(f"no near-duplicate filenames above {a.threshold}"); return 0
    for score, x, y in pairs:
        print(f"{score:.2f}  {x}  <->  {y}")
    print(f"{len(pairs)} near-duplicate pair(s) (threshold {a.threshold})")
    return 0

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