"""Point a kit's shelf at its family kit's identical texture files ('../<family>/materials/x.ktx2') and delete the copies.
The loader (render.mjs) caches textures by resolved URL, so a village loads each texture once across all its kits.
usage: python3 tools/dedupe_shelf.py <kit_dir> <family_kit_dir>"""
import filecmp, json, os, sys
kit, fam = sys.argv[1].rstrip('/'), sys.argv[2].rstrip('/')
rel = '../' + os.path.basename(fam) + '/'
p = f'{kit}/materials.json'; shelf = json.load(open(p)); mats = shelf.get('materials', shelf); n = 0
for m in mats.values():
    for k, v in list(m.items()):
        if isinstance(v, str) and v.startswith('materials/') and os.path.exists(f'{fam}/{v}') and filecmp.cmp(f'{kit}/{v}', f'{fam}/{v}', shallow=False):
            os.remove(f'{kit}/{v}'); m[k] = rel + v; n += 1
json.dump(shelf, open(p, 'w'), indent=1)
print(n, 'files now shared from', fam)
