#!/usr/bin/env python3
"""A new version removes unreachable texture buffers. Old pinned blobs remain untouched."""
import hashlib,json,sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path[:0]=[str(ROOT/'lib'),str(ROOT/'tools')]
import card,glb,ingest_photo_object as imp
saved=0;count=0
for cid,vs in card.load_all(ROOT).items():
    c=card.active(vs)
    if not any(t in cid for t in ['room3-rerun2','/trellis2-','/pixal3d-']):continue
    src=ROOT/'store/blobs'/(c['files']['glb'].split(':')[1]+'.glb');doc,binary,nbytes=glb.read(src);d,b=imp.compact(doc,binary);data=imp.pack(d,b);sha=hashlib.sha256(data).hexdigest()
    if sha==c['files']['glb'].split(':')[1]:continue
    dest=ROOT/'store/blobs'/(sha+'.glb')
    if not dest.exists():dest.write_bytes(data)
    old=glb.measure(src);new=glb.measure(dest)
    assert old['bounds']==new['bounds'] and old['tris']==new['tris'] and old['textures']==new['textures']
    saved+=nbytes-len(data);count+=1;c['version']+=1;c['files']['glb']='sha256:'+sha;c['render']['bytes']=len(data)
    c['frame'].setdefault('contract','props/+Z-front-ground');c['frame'].setdefault('unit','m');c['bounds']['footprint']['source']='measured'
    c['release']=card.release_hash(c);card.write(ROOT,c);print(cid,nbytes,'->',len(data),flush=True)
print('compacted',count,'bytes saved in active downloads',saved)
