"""Phone-budget version of a vehicle card whose decoded texture memory is over the class budget (12 MB, 24 MB if > 10 m):
re-pack its raw Astra GLB with textures capped at --max px (ORM --orm px), KTX2 + Draco, same geometry and nodes -> card v+1.
usage: python3 tools/vehicles/lighter_textures.py <slug> [--max 512] [--orm 256]"""
import copy, glob, hashlib, json, os, shutil, subprocess, sys, tempfile, time
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(ROOT, 'lib'))
import glb, card as cardlib  # noqa: E402


def main(slug, mx=512, orm=256):
    allc = cardlib.load_all(ROOT)
    cid = next(k for k in allc if k.endswith('/' + slug))
    cur = allc[cid][-1]
    job = cur['provenance']['job']
    raw = f'{ROOT}/jobs/{job}/{slug}-raw.glb'
    t = tempfile.mkdtemp(prefix='veh-light-')
    try:
        subprocess.run(['node', f'{ROOT}/tools/pack/pack_asset.mjs', raw, f'{t}/{slug}.glb', '--max', str(mx), '--orm', str(orm), '--no-draco'],
                       check=True, capture_output=True)
        subprocess.run(['node', f'{ROOT}/tools/pack/pack-glb.mjs', t, '--ktx2', '--cache', f'{t}/cache'], check=True, capture_output=True)
        f = f'{t}/{slug}.glb'
        old = glb.measure(f'{ROOT}/store/blobs/{cur["files"]["glb"].split(":")[1]}.glb')
        m = glb.measure(f)
        assert m['tris'] == old['tris'] and m['nodes'] == old['nodes'], 'geometry or nodes changed'
        h = hashlib.sha256(open(f, 'rb').read()).hexdigest()
        shutil.copyfile(f, f'{ROOT}/store/blobs/{h}.glb')
    finally:
        shutil.rmtree(t, ignore_errors=True)
    big = max(m['size_xyz']) > 10
    budget = 24 if big else 12
    c = copy.deepcopy(cur)
    c['version'] = cur['version'] + 1
    c['files'] = {**cur['files'], 'glb': f'sha256:{h}'}
    c['render'] = {**cur['render'], 'bytes': m['bytes'], 'textures': m['textures'], 'gpu_mb_decoded': m['gpu_mb_decoded']}
    ok = m['gpu_mb_decoded'] <= budget
    c['status'] = 'approved' if ok else 'candidate'
    c['quality'] = {**cur['quality'], 'gates': (f"pass: {m['gpu_mb_decoded']:.0f} MB of {budget} MB texture budget, {m['tris']} tris" if ok else
                                                 f"fail: decoded texture memory {m['gpu_mb_decoded']:.0f} MB > {budget} MB budget")}
    c['provenance'] = {**cur['provenance'], 'fix': f'phone texture budget: textures capped {mx} px (ORM {orm}) from the raw GLB, same geometry',
                       'fixed': time.strftime('%Y-%m-%d')}
    c['release'] = cardlib.release_hash(c)
    print(cardlib.write(ROOT, c).replace(ROOT + '/', ''), f"{old['gpu_mb_decoded']:.1f} -> {m['gpu_mb_decoded']:.1f} MB", c['status'])


if __name__ == '__main__':
    a = sys.argv[1:]
    main(a[0], int(a[a.index('--max') + 1]) if '--max' in a else 512, int(a[a.index('--orm') + 1]) if '--orm' in a else 256)
