#!/usr/bin/env python3
"""FileFlow: preview, organize, and safely undo one-level file moves."""
import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path

CATEGORIES = {
    "Images": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"},
    "Documents": {".pdf", ".doc", ".docx", ".txt", ".md", ".rtf"},
    "Spreadsheets": {".csv", ".xls", ".xlsx", ".ods"},
    "Audio": {".mp3", ".wav", ".m4a", ".flac"},
    "Video": {".mp4", ".mov", ".mkv", ".webm"},
    "Archives": {".zip", ".tar", ".gz", ".7z"},
    "Code": {".py", ".js", ".ts", ".json", ".html", ".css"},
}


def category(path):
    return next((name for name, extensions in CATEGORIES.items()
                 if path.suffix.lower() in extensions), "Other")


def plan(root):
    root = Path(root).resolve(strict=True)
    if not root.is_dir():
        raise ValueError("Folder is not a directory")
    moves, reserved = [], set()
    for item in sorted(root.iterdir(), key=lambda p: p.name.casefold()):
        if not item.is_file() or item.is_symlink() or item.name.startswith(".fileflow-journal"):
            continue
        folder = root / category(item)
        if folder.is_symlink() or (folder.exists() and not folder.is_dir()):
            raise ValueError(f"Unsafe category destination: {folder}")
        proposed = folder / item.name
        counter = 1
        while proposed.exists() or str(proposed).casefold() in reserved:
            proposed = folder / f"{item.stem}-{counter}{item.suffix}"
            counter += 1
        reserved.add(str(proposed).casefold())
        moves.append((item, proposed))
    return moves


def organize(root, apply=False):
    root = Path(root).resolve(strict=True)
    moves = plan(root)
    if not apply:
        return {"mode": "preview", "moves": [
            {"from": str(a), "to": str(b)} for a, b in moves
        ], "count": len(moves)}
    # One journal per operation; incomplete operations are still recoverable.
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
    journal = root / f".fileflow-journal-{stamp}.json"
    record = {"version": 1, "root": str(root), "moves": []}
    journal.write_text(json.dumps(record, indent=2), encoding="utf-8")
    for source, dest in moves:
        if dest.parent.is_symlink():
            raise ValueError(f"Category folder became a symlink: {dest.parent}")
        dest.parent.mkdir(exist_ok=True)
        # Stop rather than overwrite a file created after preview.
        if dest.exists():
            raise FileExistsError(f"Destination exists: {dest}")
        shutil.move(str(source), str(dest))
        record["moves"].append({"from": str(source), "to": str(dest)})
        journal.write_text(json.dumps(record, indent=2), encoding="utf-8")
    return {"mode": "applied", "journal": str(journal), "count": len(record["moves"])}


def undo(journal):
    journal = Path(journal).resolve(strict=True)
    data = json.loads(journal.read_text(encoding="utf-8"))
    if data.get("version") != 1 or not isinstance(data.get("moves"), list):
        raise ValueError("Invalid FileFlow journal")
    root = Path(data["root"]).resolve(strict=True)
    if journal.parent != root:
        raise ValueError("Journal must be stored in the original folder")
    restored = 0
    # Preflight the entire undo; never restore half the files then discover a collision.
    for move in data["moves"]:
        original = Path(move["from"])
        organized = Path(move["to"])
        if original.parent != root or organized.parent.parent != root:
            raise ValueError("Unsafe journal path")
        if original.is_symlink() or original.exists():
            raise FileExistsError(f"Original path occupied: {original}")
        if not organized.is_file() or organized.is_symlink() or organized.parent.is_symlink():
            raise FileNotFoundError(f"Missing or unsafe organized file: {organized}")
    for move in reversed(list(data["moves"])):
        original = Path(move["from"])
        organized = Path(move["to"])
        if original.parent != root or organized.parent.parent != root:
            raise ValueError("Unsafe journal path")
        if original.exists():
            raise FileExistsError(f"Original path occupied: {original}")
        if not organized.is_file() or organized.is_symlink():
            raise FileNotFoundError(f"Missing or unsafe organized file: {organized}")
        shutil.move(str(organized), str(original))
        restored += 1
        # Checkpoint each successful move so interrupted undo can resume correctly.
        data["moves"].remove(move)
        journal.write_text(json.dumps(data, indent=2), encoding="utf-8")
    journal.unlink()
    return {"mode": "undone", "count": restored}


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("folder", nargs="?", help="Folder to organize")
    parser.add_argument("--apply", action="store_true", help="Perform moves (default: preview)")
    parser.add_argument("--undo", metavar="JOURNAL", help="Undo a previous run")
    args = parser.parse_args(argv)
    if not args.undo and not args.folder:
        parser.error("Provide a folder or --undo JOURNAL")
    try:
        result = undo(args.undo) if args.undo else organize(args.folder, args.apply)
    except (OSError, ValueError, KeyError, json.JSONDecodeError) as exc:
        parser.exit(2, f"Error: {exc}\n")
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()

