#!/usr/bin/env python3
"""Move textures/tb/<family>/ into textures/tb/<role>/<family>/ and rewrite path refs.

Run with Godot editor closed. Operates in place. Reversible by reading the
final report and inverting the mapping.
"""

from pathlib import Path

ROOT = Path.home() / "godot_projects/trench/textures/tb"

ROLE_MAP = {
    # walls
    "brick": "wall", "concrete": "wall", "stucco": "wall", "steel": "wall",
    "wood": "wall", "panel": "wall", "tech": "wall", "lab": "wall",
    "rivet": "wall", "tile": "wall", "hedge": "wall", "fence": "wall",
    # floors
    "floor": "floor", "cobbles": "floor", "dirt": "floor", "grass": "floor",
    "sand": "floor", "tarmac": "floor", "sidewalk": "floor", "grid": "floor",
    # doors
    "door": "door", "bigdoor": "door", "ldoor": "door", "rdoor": "door",
    # trim
    "doortrim": "trim", "ledge": "trim", "step": "trim", "support": "trim",
    "pipes": "trim", "vent": "trim",
    # light
    "light": "light",
    # decal / liquid / prop
    "blood": "decal", "warn": "decal", "paper": "decal",
    "slime": "liquid", "sludge": "liquid",
    "crate": "prop", "console": "prop", "switch": "prop",
}

ROLES = set(ROLE_MAP.values())

# Step 1: families whose name matches a role (floor, door, light) need a temp
# rename so they don't collide with the role folder we're about to create.
conflicts = {fam for fam in ROLE_MAP if fam in ROLES}
for fam in conflicts:
    src = ROOT / fam
    if src.is_dir():
        src.rename(ROOT / f"__tmp_{fam}")

# Step 2: move each family into its role folder, rewriting path refs.
moved = 0
updated = 0

for fam, role in ROLE_MAP.items():
    src = ROOT / (f"__tmp_{fam}" if fam in conflicts else fam)
    if not src.is_dir():
        continue

    role_dir = ROOT / role
    role_dir.mkdir(exist_ok=True)

    dst = role_dir / fam
    if dst.exists():
        print(f"COLLISION: {dst} already exists, skipping {fam}")
        continue

    src.rename(dst)
    moved += 1

    old_prefix = f"res://textures/tb/{fam}/"
    new_prefix = f"res://textures/tb/{role}/{fam}/"
    for f in dst.iterdir():
        if not f.is_file():
            continue
        if f.name.endswith(".png.import") or f.suffix == ".tres":
            text = f.read_text()
            new_text = text.replace(old_prefix, new_prefix)
            if new_text != text:
                f.write_text(new_text)
                updated += 1

# Check for unknown families left at the top level
unknown = [
    d.name for d in ROOT.iterdir()
    if d.is_dir() and d.name not in ROLES and not d.name.startswith("__tmp_")
]

print(f"\nMoved {moved} families into {len(ROLES)} role folders")
print(f"Updated {updated} ref files (.png.import + .tres)")
if unknown:
    print(f"\nWARNING: unknown families left at top level: {unknown}")
