"""Turn a finished Astra author job into a library card version. usage: python3 tools/import_job.py <job_dir>
Reads job.json (+ <slug>.glb, NOTES.md), copies the GLB into store/blobs by hash, writes cards/.../v<version>.json.
Spatial numbers are measured from the file; the GPU pass (tools/gpu/run.sh) adds exact sizes and the thumbnail."""
import hashlib, json, os, re, shutil, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, 'lib')); sys.path.insert(0, os.path.join(ROOT, 'tools'))
import glb, card as cardlib  # noqa: E402
from import_existing import build_card  # noqa: E402

# job.json "pen" = the model that drew the asset in Blender -> card provenance.author (shown as "Drawn by" in the library)
PENS = {'astra': ('gpt-6-astra (Blender)', 'Astra'),
        'gemini4': ('gemini-4-argon via Antigravity (Blender)', 'Gemini 4 Argon (Antigravity CLI)')}


def main(jd):
    jd = os.path.abspath(jd); j = json.load(open(f'{jd}/job.json'))
    cls, slug = j['id'].split('/')
    f = f"{jd}/{j['slug']}.glb"
    if not os.path.exists(f):
        raise SystemExit(f'no {f}')
    notes = open(f'{jd}/NOTES.md').read() if os.path.exists(f'{jd}/NOTES.md') else ''
    ph = sorted(set(re.findall(r'\b[a-z0-9]+(?:_[a-z0-9]+)+\b', notes)))[:30]
    h = hashlib.sha256(open(f, 'rb').read()).hexdigest()
    os.makedirs(f'{ROOT}/store/blobs', exist_ok=True)
    shutil.copyfile(f, f'{ROOT}/store/blobs/{h}.glb')
    kind = cls.split('.')[0]
    contract = {'vehicle': 'library/vehicle-+Z-front', 'building': 'kit/+Z-front', 'prop': 'kit/+Z-front', 'part': 'kit/+Z-front',
                'weapon': 'weapon/grip-origin-muzzle-minus-z'}.get(kind, 'kit/+Z-front')
    if cls.startswith('vehicle.sea'):
        contract = 'library/vessel-waterline-origin-+Z-bow'
    s = dict(file=f, slug=slug, path=cls, name=j.get('title') or j['name'][:80].strip().capitalize(), version=j.get('version', 1),
             summary=(notes.splitlines()[0][:300] if notes else j['name']), style='realistic', frame=contract, gates='authored',
             status=j.get('status', 'approved'),  # job.json "status": "candidate" = shown, never picked (pen comparison twins)
             licence=dict(kind='owned', game_use=True, raw_redistribute=False,
                          evidence=f"Forge {PENS.get(j.get('pen', 'astra'), PENS['astra'])[1]} Blender job {os.path.basename(jd)} "
                                   f"(Nano Banana Pro sheet, CC0 Poly Haven textures: {', '.join(ph) or 'see NOTES.md'})"),
             provenance=dict(author=PENS.get(j.get('pen', 'astra'), PENS['astra'])[0], source=f'jobs/{os.path.basename(jd)}',
                             kit='library-author', job=os.path.basename(jd), feedback=j.get('feedback')))
    m = glb.measure(f)
    big = max(m['size_xyz']) > 10
    budget = {'prop': 6, 'part': 6, 'vehicle': 24 if big else 12, 'building': 16 if not big else 24, 'weapon': 24}.get(kind, 12)
    if m['gpu_mb_decoded'] > budget:  # over the phone budget: kept, shown, never picked for games
        s['status'] = 'candidate'
        s['gates'] = f"fail: decoded texture memory {m['gpu_mb_decoded']:.0f} MB > {budget} MB budget"
    else:
        s['gates'] = f"pass: {m['gpu_mb_decoded']:.0f} MB of {budget} MB texture budget, {m['tris']} tris"
    c = build_card(s, m, h)
    p = cardlib.write(ROOT, c)
    print(p, c['render']['tris'], 'tris', c['release'][:23])


if __name__ == '__main__':
    main(sys.argv[1])
