#!/usr/bin/env python3
"""Fix stale res://textures/td_sliced/<UPPER>.png references in .tres files
under textures/tb/ — rewrites them to the new tb/<role>/<family>/<variant>.png
location. Cosmetic only; Godot already resolves these via UID."""

import re
from pathlib import Path

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

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

basename_re = re.compile(r"^([a-z]+)_(\d+[a-z](?:_[a-z]+)?)\.png$")
ref_re = re.compile(r'res://textures/td_sliced/([^"]+\.png)')

fixed = 0

for tres in TB_ROOT.rglob("*.tres"):
    text = tres.read_text()

    def replace(m):
        old = m.group(1).lower()
        bm = basename_re.match(old)
        if not bm:
            return m.group(0)
        family, variant = bm.group(1), bm.group(2)
        role = ROLE_MAP.get(family)
        if not role:
            return m.group(0)
        return f"res://textures/tb/{role}/{family}/{variant}.png"

    new_text = ref_re.sub(replace, text)
    if new_text != text:
        tres.write_text(new_text)
        fixed += 1

print(f"Fixed {fixed} .tres files")
