"""Copy and inspect original galaxy sprites. Does not synthesize image pixels."""
import gzip,hashlib,io,json,struct
from pathlib import Path
from PIL import Image,ImageDraw

source=Path('artifacts/galaxy-query-research/power-outer-sources/material')
metadata=json.loads((source/'original-materials.json').read_text())
body=(source/(metadata['resource']+'.stream0')).read_bytes()
if hashlib.sha256(body).hexdigest()!=metadata['frozenSha256']:raise ValueError('Original bundle changed')
texture=next(t for t in metadata['textures'] if t['name']=='spectralclassvismodeinnebula_nodepth.pdiffusetexture')
physical=next(t for t in metadata['textures'] if t['name']=='spectralclassinnebula_nodepth.pdiffusetexture')
def payload(t):return body[t['gpuOffset']:t['gpuOffset']+t['gpuBytes']]
gpu=payload(texture)
if gpu!=payload(physical):raise ValueError('Physical and map diffuse arrays differ')
if (texture['width'],texture['height'],texture['depth'],texture['array'],texture['mips'],len(gpu))!=(512,512,1,28,10,5074944):raise ValueError('Original sprite dimensions changed')
frames=[]
for i in range(texture['array']):
    mip=texture['mipLayout'][0];start=mip['offset']+i*mip['sliceBytes'];data=gpu[start:start+mip['sliceBytes']]
    # The source's internal format95 is not DXGI95. Its 512x512 first mip
    # has 1024-byte block rows and 131072 bytes per layer: BC1/DXT1 blocks.
    dds=(b'DDS '+struct.pack('<7I',124,0x81007,512,512,len(data),0,1)+bytes(44)
        +struct.pack('<8I',32,4,int.from_bytes(b'DXT1','little'),0,0,0,0,0)+struct.pack('<5I',0x1000,0,0,0,0)+data)
    image=Image.open(io.BytesIO(dds)).convert('RGB');image.save(source/f'original-sprite-{i:02}.png');frames.append(image)
sheet=Image.new('RGB',(7*164,4*184),(28,28,28));draw=ImageDraw.Draw(sheet)
for i,image in enumerate(frames):
    x=i%7*164;y=i//7*184;sheet.paste(image.resize((160,160)),(x,y));draw.text((x+5,y+162),str(i),fill='white')
sheet.save(source/'original-sprites-contact.png')
out=Path('XFEEDToolBox.Core/Rendering')
with open(out/'original-star-sprites.bc1.gz','wb') as stream:
    with gzip.GzipFile(filename='',mode='wb',fileobj=stream,mtime=0,compresslevel=9) as compressed:compressed.write(gpu)
result=dict(sourceResource=metadata['resource'],sourceArchiveSha256=metadata['sourceArchiveSha256'],frozenSha256=metadata['frozenSha256'],
    sourceTexture=texture['name'],physicalTextureIdentical=True,sourceFormat=95,format='BC1_UNorm',width=512,height=512,layers=28,
    mipCount=10,mips=texture['mipLayout'],payloadBytes=len(gpu),payloadSha256=hashlib.sha256(gpu).hexdigest(),
    gameProcessAccess=False,gameCalls=0,originalShaderRestored=False,
    notes='Exact original diffuse array. Original shader channel mixing, EV/tone mapping and world-to-pixel size are separate evidence; no parity claim.')
(out/'original-star-sprites.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(dict(payloadBytes=len(gpu),compressedBytes=(out/'original-star-sprites.bc1.gz').stat().st_size,payloadSha256=result['payloadSha256']),indent=2))
