# Map each FBX to the textures its prefabs use: guid → path from .meta files; prefab → mesh guid + material guids; .mat → texture guid.
import os, re, sys, json, collections
root = sys.argv[1]
guid = {}
for d, _, fs in os.walk(os.path.join(root, 'Assets')):
    for f in fs:
        if f.endswith('.meta'):
            try:
                t = open(os.path.join(d, f), encoding='utf-8', errors='ignore').read(4000)
            except Exception: continue
            m = re.search(r'guid: ([0-9a-f]{32})', t)
            if m: guid[m.group(1)] = os.path.relpath(os.path.join(d, f[:-5]), root).replace(os.sep, '/')
def text(p):
    b = open(os.path.join(root, p), 'rb').read()
    return b.decode('utf-8', 'ignore') if b[:5] == b'%YAML' else None
mat_tex = {}
for g, p in guid.items():
    if p.endswith('.mat'):
        t = text(p)
        if t is None: mat_tex[p] = 'binary'; continue
        texs = [guid.get(x, '?' + x) for x in re.findall(r'm_Texture: \{fileID: \d+, guid: ([0-9a-f]{32})', t)]
        sh = re.search(r'm_Shader: \{fileID: (\d+)(?:, guid: ([0-9a-f]{32}))?', t)
        mat_tex[p] = {'tex': texs, 'shader': (guid.get(sh.group(2), sh.group(1)) if sh else None)}
fbx_mats = collections.defaultdict(set)
binary_prefabs = 0
for g, p in guid.items():
    if p.endswith('.prefab'):
        t = text(p)
        if t is None: binary_prefabs += 1; continue
        meshes = [guid.get(x) for x in re.findall(r'm_Mesh: \{fileID: \d+, guid: ([0-9a-f]{32})', t)]
        mats = [guid.get(x) for x in re.findall(r'- \{fileID: \d+, guid: ([0-9a-f]{32}), type: 2\}', t)]
        for m in meshes:
            if m and m.lower().endswith('.fbx'): fbx_mats[m].update(x for x in mats if x and x.endswith('.mat'))
print('guids', len(guid), 'binary prefabs', binary_prefabs, 'fbx with mats', len(fbx_mats))
used = collections.Counter(m for s in fbx_mats.values() for m in s)
for m, n in used.most_common(40): print(n, m, json.dumps(mat_tex.get(m))[:200])
json.dump({k: sorted(v) for k, v in fbx_mats.items()}, open(sys.argv[2], 'w'), indent=0)
json.dump(mat_tex, open(sys.argv[3], 'w'), indent=0)
