"""Extract the original loading-screen FGM attributes from the pinned local assets."""
from pathlib import Path
import hashlib, importlib.machinery, json, struct, zlib

scan=importlib.machinery.SourceFileLoader('local_resources','artifacts/ship-model-reference/scan-ship-assets.py').load_module()
key='f12f774afc2cf9ffb8edcb5792116b98d37c1195'
source=scan.root/'0f'/key
f=scan.decode(source);b=zlib.decompress(f[13828:])
if len(f)!=33114874 or len(b)!=59263827:raise ValueError('Unexpected source resource version')
pools=[16348+struct.unpack_from('<I',b,12+i*32+12)[0] for i in range(9)]
references={struct.unpack_from('<II',b,o):struct.unpack_from('<II',b,o+8) for o in range(9340,16348,16)}
roots={struct.unpack_from('<I',b,o)[0]:struct.unpack_from('<II',b,o+8) for o in range(6668,9340,16)}
entries={};cursor=133556;buffer_cursor=4940
for i in range(145):
    h=struct.unpack_from('<I',b,300+i*32)[0];count=struct.unpack_from('<H',b,300+i*32+10)[0]
    for j in range(count):
        index,size=struct.unpack_from('<II',b,buffer_cursor);buffer_cursor+=8
        if index==0:entries[h]=(cursor,size);cursor+=size
materials={}
for name in ('edgedetectionplane_m','loadingscreen_m','loadingscreenship_m'):
    n=f.index(name.encode()+b'\0');p=f.index(struct.pack('<I',n-144),6168)
    h=struct.unpack_from('<I',f,p+4)[0];blob,size=entries[h]
    pool,off=roots[h];root=pools[pool]+off;nt,na=struct.unpack_from('<QQ',b,root)
    at,ao=references[(pool,off+24)];vt,vo=references[(pool,off+40)]
    attributes=pools[at]+ao;values=pools[vt]+vo;attrs={}
    for i in range(na):
        n,t,o=struct.unpack_from('<IIQ',b,attributes+i*16)
        if n>=size:raise ValueError('Attribute name exceeds original FGM buffer')
        label=b[blob+n:b.index(b'\0',blob+n)].decode('ascii')
        count=t+1 if t<=3 else 1
        value=struct.unpack_from('<'+('f' if t<=3 else 'I')*count,b,values+o)
        attrs[label]=value[0] if count==1 else value
    materials[name]=dict(shader=b[blob:b.index(b'\0',blob)].decode('ascii'),textures=nt,attributes=attrs)
assert materials['edgedetectionplane_m']['attributes']['pSobelEdgeThickness']==1
result=dict(gameSha256='6891f70a021fa9f3a0e00458c284f48d1226e68ae7fc02ad48081aed47857e93',
            sourceResource=key,sourceSha256=hashlib.sha256(source.read_bytes()).hexdigest(),deflateOffset=13828,
            materials=materials,generator='research/Extract-LoadingHologramProfile.py',gameProcessAccess=False)
out=Path('XFEEDToolBox.Core/Rendering/loading-hologram-reference.json')
out.write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(dict(materials=list(materials),sha256=hashlib.sha256(out.read_bytes()).hexdigest(),gameProcessAccess=False)))
