# SKCombat token "color packs" (skins like Armor (light), Bloody, Moss): which overlay meshes hang from which bone.
# Reads the Unity token prefabs; writes annexes.json: {token: {pack name: [[fbx file, mesh name, bone name], ...]}}.
# Run: python -I annexes.py <Unity project dir> <out dir>
import os, re, sys, json
root, out_dir = sys.argv[1], sys.argv[2]
guid = {}
for d, _, fs in os.walk(os.path.join(root, 'Assets')):
    for f in fs:
        if f.endswith('.meta'):
            t = open(os.path.join(d, f), encoding='utf-8', errors='ignore').read(3000)
            m = re.search(r'guid: ([0-9a-f]{32})', t)
            if m: guid[m.group(1)] = os.path.join(d, f[:-5])
def docs(path):
    """Unity YAML → {fileID: (type, text)}"""
    out = {}
    for part in re.split(r'^--- ', open(path, encoding='utf-8', errors='ignore').read(), flags=re.M)[1:]:
        h = re.match(r'!u!(\d+) &(\d+)', part)
        if h: out[h.group(2)] = (h.group(1), part)
    return out
def recycle_names(fbx):
    t = open(fbx + '.meta', encoding='utf-8', errors='ignore').read()
    return dict(re.findall(r'(\d+): (\S+)', t.split('fileIDToRecycleName:')[1].split('materials:')[0])) if 'fileIDToRecycleName:' in t else {}
res = {}
for token in ('[06]Skeleton/T01050-Skeleton.prefab', '[07]Spider/T01100-Spider.prefab'):
    path = os.path.join(root, 'Assets', 'References', 'Tokens', token)
    D = docs(path)
    def bone(tid):
        go = re.search(r'm_GameObject: \{fileID: (\d+)\}', D[tid][1]).group(1)
        return re.search(r'm_Name: (.*)', D[go][1]).group(1).strip()
    text = open(path, encoding='utf-8', errors='ignore').read()
    packs = {}
    for blk in re.split(r'\n  - isEnabled: ', text.split('myColorPacks:')[1])[1:]:
        name = re.search(r'myName: (.*)', blk).group(1).strip()
        items = []
        for anchor, src in re.findall(r'myAnchor: \{fileID: (\d+)\}\s+mySource: \{fileID: \d+, guid: ([0-9a-f]{32})', blk):
            pre = guid.get(src)
            if not pre: continue
            P = docs(pre)
            for typ, body in P.values():
                if typ != '33': continue  # MeshFilter
                mm = re.search(r'm_Mesh: \{fileID: (\d+), guid: ([0-9a-f]{32})', body)
                fbx = guid.get(mm.group(2))
                if not fbx: continue
                items.append([os.path.basename(fbx), recycle_names(fbx).get(mm.group(1), '?'), bone(anchor)])
        packs[name] = items
    res[token.split('/')[0][4:]] = packs
json.dump(res, open(os.path.join(out_dir, 'annexes.json'), 'w'), indent=1)
for t, ps in res.items():
    print(t)
    for n, it in ps.items(): print('  ', n, it)
