#!/usr/bin/env python3
"""moveplan - dry-run planner: given move rules, show what would move where, then apply.
Usage: moveplan <dir> --rule 'PATTERN -> DEST' [--rule ...] [--apply] [--selftest] [--help]
Rules are `glob -> destination` (destination relative to <dir> unless
absolute). Each file matching a rule is listed with its destination; files
matching no rule are listed as unmoved, and files matching several rules hit
the FIRST rule only (reported as a conflict note when a later rule would
also have matched). Default is the plan only; --apply performs the moves.
Rules file: --rules-file with one rule per line, `#` comments allowed.
"""
import argparse, fnmatch, os, sys, tempfile
from pathlib import Path

def parse_rule(text):
    if "->" not in text:
        raise ValueError(f"bad rule (want 'GLOB -> DEST'): {text}")
    pat, dest = text.split("->", 1)
    return pat.strip(), dest.strip()

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        (base / "a.jpg").write_text("x")
        (base / "b.png").write_text("x")
        (base / "c.txt").write_text("x")
        (base / "d.jpg").write_text("x")
        rules = [("*.jpg", "photos"), ("*.png", "photos"), ("*.txt", "docs")]
        files = sorted(p for p in base.iterdir() if p.is_file())
        moves, unmoved = [], []
        for p in files:
            hit = None
            for pat, dest in rules:
                if fnmatch.fnmatchcase(p.name, pat):
                    hit = dest; break
            (moves if hit else unmoved).append((p, hit))
        assert len(moves) == 4 and not unmoved, moves
        assert moves[0][1] == "photos"
        import subprocess
        r = subprocess.run([sys.executable, __file__, str(base),
                            "--rule", "*.jpg -> photos", "--rule", "*.txt -> docs",
                            "--apply"], capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        assert (base / "photos" / "a.jpg").exists() and (base / "photos" / "d.jpg").exists()
        assert (base / "docs" / "c.txt").exists()
        assert (base / "b.png").exists()  # no rule matched: unmoved
        print("selftest OK: jpg->photos, txt->docs applied; unmatched png stayed put")
        return 0

def main():
    ap = argparse.ArgumentParser(description="moveplan - dry-run planner for move rules, then apply")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--rule", action="append", default=[], help="'GLOB -> DEST', repeatable")
    ap.add_argument("--rules-file", metavar="FILE")
    ap.add_argument("--apply", action="store_true", help="actually move the files")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    rules = []
    for r in a.rule:
        rules.append(parse_rule(r))
    if a.rules_file:
        for line in Path(a.rules_file).read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#"):
                rules.append(parse_rule(line))
    if not rules:
        print("moveplan: no rules given (--rule 'GLOB -> DEST')", file=sys.stderr); return 2
    root = Path(a.dir)
    if not root.is_dir():
        print(f"moveplan: {a.dir}: not a directory", file=sys.stderr); return 2
    files = sorted(p for p in root.rglob("*") if p.is_file())
    moves, unmoved = [], []
    for p in files:
        matched = [dest for pat, dest in rules if fnmatch.fnmatchcase(p.name, pat)]
        if matched:
            dest = Path(matched[0])
            if not dest.is_absolute():
                dest = root / dest
            moves.append((p, dest / p.name, len(matched) > 1))
        else:
            unmoved.append(p)
    for src, dst, conflict in moves:
        note = "  (also matched a later rule; first wins)" if conflict else ""
        print(f"{src} -> {dst}{note}")
    for p in unmoved:
        print(f"(unmoved) {p}")
    print(f"\n{len(moves)} move(s), {len(unmoved)} unmoved")
    if not a.apply:
        print("plan only; use --apply to move"); return 0
    for src, dst, _ in moves:
        dst.parent.mkdir(parents=True, exist_ok=True)
        target = dst
        i = 2
        while target.exists():
            target = dst.with_name(f"{dst.stem}_{i}{dst.suffix}"); i += 1
        src.rename(target)
    print(f"moved {len(moves)} file(s)")
    return 0

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