"""browse/vehicles.json for the vehicle showroom (browse/vehicles.html): the newest version of every Astra vehicle card
made from a jobs/<slug>-v<N> vehicle job (job.json has a 'family'). usage: python3 tools/vehicles/manifest.py"""
import glob, json, os, subprocess, sys
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(ROOT, 'lib'))
import card as cardlib  # noqa: E402

ORDER = ['cars', 'race', 'motos', 'bikes', 'buses', 'wheeled', 'tanks', 'rotor', 'jets']
out = []


def job_json(job):
    """jobs/<job>/job.json, from git when a disk cleanup removed the job dir (15 Oct 2026: 23 of 47 vehicles vanished)"""
    p = f'{ROOT}/jobs/{job}/job.json'
    if os.path.exists(p):
        return json.load(open(p))
    r = subprocess.run(['git', '-C', ROOT, 'show', f'HEAD:jobs/{job}/job.json'], capture_output=True)
    return json.loads(r.stdout) if r.returncode == 0 else None


for jid, versions in cardlib.load_all(ROOT).items():
    c = versions[-1]
    job = (c.get('provenance') or {}).get('job')
    j = job_json(job) if job else None
    if not j:
        continue
    if 'family' not in j or not c.get('paint') or c['paint'].get('material') != 'Paint':
        continue
    m = c['size']['measured_m']
    fam = 'race' if c['id'].startswith('vehicle.car.race/') else j['family']  # race cars: their own showroom group
    out.append(dict(id=c['id'], slug=j['slug'], job=job, title=j.get('title') or c['name'], family=fam, version=c['version'],
                    glb=c['files']['glb'].split(':')[1], size=[m['w'], m['h'], m['l']], tris=c['render']['tris'],
                    bytes=c['render']['bytes'], gpu_mb=c['render']['gpu_mb_decoded'], paints=c['paint']['paints'],
                    nodes=c['nodes'], release=c['release'],
                    damage_glb=(c['files'].get('damage_glb') or ':').split(':')[1] or None, tags=j.get('tags') or [],
                    author=(c.get('provenance') or {}).get('author')))  # the model that drew it in Blender (shown as 'drawn by')
out.sort(key=lambda v: (ORDER.index(v['family']), v['size'][2]))
json.dump(out, open(f'{ROOT}/browse/vehicles.json', 'w'), indent=1)
print(len(out), 'vehicles ->', 'browse/vehicles.json')
