#!/usr/bin/env python3
"""
Reorganizes /mnt/18tb/downloads/roms by converting directories with the
Unicode 'fraction slash' character (U+2044 \u2044) into real subdirectory structures.

Example:
  "Visual_Pinball_2020-06-20\u2044Visual Pinball [VPXx] PinMame Tables"
  -> "Visual_Pinball_2020-06-20/Visual Pinball [VPXx]/PinMame Tables"

  "vpinmame\u2044roms"
  -> "vpinmame/roms"

Usage:
  python3 reorganize_roms.py [--dry-run]
"""

import os
import sys
import shutil

BASE = '/mnt/18tb/downloads/roms'
FAKE_SLASH = '\u2044'
DRY_RUN = '--dry-run' in sys.argv

def log(msg):
    print(msg, flush=True)

def makedirs_safe(path):
    if not DRY_RUN:
        os.makedirs(path, exist_ok=True)

def move_safe(src, dst):
    if not DRY_RUN:
        shutil.move(src, dst)

entries = sorted(os.listdir(BASE))
fake_dirs = [e for e in entries if FAKE_SLASH in e]

log(f"{'[DRY RUN] ' if DRY_RUN else ''}Found {len(fake_dirs)} fake-slash directories to reorganize.")
log("")

moves = []
for entry in fake_dirs:
    parts = entry.split(FAKE_SLASH)
    src_path = os.path.join(BASE, entry)
    root = parts[0]
    sub_parts = parts[1:]
    
    final_sub_parts = []
    for sp in sub_parts:
        # Split "Visual Pinball [VPXx] PinMame Tables" -> "Visual Pinball [VPXx]" + "PinMame Tables"
        if '] ' in sp:
            idx = sp.index('] ')
            final_sub_parts.append(sp[:idx+1])
            final_sub_parts.append(sp[idx+2:])
        else:
            final_sub_parts.append(sp)
    
    dst_path = os.path.join(BASE, root, *final_sub_parts)
    moves.append((src_path, dst_path))

log("=== REORGANIZATION PLAN ===")
for src, dst in moves:
    src_rel = src.replace(BASE + '/', '')
    dst_rel = dst.replace(BASE + '/', '')
    log(f"  MOVE: {src_rel}")
    log(f"    TO: {dst_rel}")

log(f"\nTotal moves: {len(moves)}")

if DRY_RUN:
    log("\n[DRY RUN] No changes made. Remove --dry-run to execute.")
    sys.exit(0)

log("\n=== EXECUTING ===")
errors = []
for i, (src, dst) in enumerate(moves, 1):
    try:
        log(f"[{i}/{len(moves)}] {os.path.basename(src)}")
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        shutil.move(src, dst)
        log("  OK")
    except Exception as e:
        log(f"  ERROR: {e}")
        errors.append((src, dst, str(e)))

log("")
if errors:
    log(f"=== COMPLETED WITH {len(errors)} ERRORS ===")
    for src, dst, err in errors:
        log(f"  {src} -> {dst}: {err}")
else:
    log("=== COMPLETED SUCCESSFULLY ===")
    log(f"Reorganized {len(moves)} directories.")
