"""Build the editable ARTISAN collection and photograph its exact geometry."""
from pathlib import Path
import sys
ROOT=Path(__file__).resolve().parent.parent
source=(ROOT/'modeling/build_mezzo.py').read_text().split('DECK_START=4.12')[0]
exec(compile(source,str(ROOT/'modeling/build_mezzo.py'),'exec'))
if '--render-only' in sys.argv:
    bpy.ops.wm.open_mainfile(filepath=str(ROOT/'modeling/cartridge-library.blend'))
    scene=bpy.context.scene
    modules={name:bpy.data.objects['cartridge_'+name] for name in CARTRIDGE_BUILDERS}
else:
    modules={}
    for name,builder in CARTRIDGE_BUILDERS.items():
        g=finalize_cartridge(builder());modules[name]=g
        objects=[g]+list(g.children_recursive)
        bpy.ops.object.select_all(action='DESELECT')
        for ob in objects:
            ob.select_set(True);ob.location*=.01
            if ob.type=='MESH':
                for v in ob.data.vertices:v.co*=.01
        bpy.ops.export_scene.gltf(filepath=str(OUT/f'cartridge-{name}.glb'),export_format='GLB',use_selection=True,export_apply=True,export_yup=True,export_extras=True)
        for ob in objects:
            ob.location*=100
            if ob.type=='MESH':
                for v in ob.data.vertices:v.co*=100
        print('CARTRIDGE_EXPORTED',name,flush=True)
    for i,g in enumerate(modules.values()):g.location.x=(i-2)*17
    bpy.ops.wm.save_as_mainfile(filepath=str(ROOT/'modeling/cartridge-library.blend'))
if '--no-render' in sys.argv:
    print('CARTRIDGE_LIBRARY_READY',flush=True);sys.exit(0)
for g in modules.values():g.location=(0,0,0)
world=bpy.data.worlds.new('Cartridge studio');scene.world=world;world.use_nodes=True
world.node_tree.nodes['Background'].inputs['Color'].default_value=(.10,.115,.10,1)
world.node_tree.nodes['Background'].inputs['Strength'].default_value=.35
floor=cube('Studio / floor',(0,0,-1.0),(2000,2000,.10),material('Studio / floor finish','#242D25',.46),0)
def area(name,loc,power,size,sy,color):
    d=bpy.data.lights.new(name,'AREA');d.energy=power;d.shape='RECTANGLE';d.size=size;d.size_y=sy;d.color=color
    ob=bpy.data.objects.new(name,d);bpy.context.collection.objects.link(ob);ob.location=loc;ob.rotation_euler=(Vector((0,0,3))-ob.location).to_track_quat('-Z','Y').to_euler()
area('Studio / key',(-14,-18,24),9500,13,17,(1,.95,.87))
area('Studio / rim',(12,8,20),11000,3,19,(.92,.96,1))
area('Studio / top',(-10,10,24),11000,18,4,(1,.98,.91))
area('Studio / fill',(5,-22,8),2200,12,12,(.94,.97,1))
d=bpy.data.cameras.new('Cartridge camera');c=bpy.data.objects.new('Cartridge camera',d);bpy.context.collection.objects.link(c);scene.camera=c;d.type='ORTHO'
scene.render.threads_mode='FIXED';scene.render.threads=8
scene.render.engine='CYCLES';scene.cycles.samples=48;scene.cycles.use_denoising=True
scene.render.resolution_x=1000;scene.render.resolution_y=1000;scene.render.resolution_percentage=100
scene.render.image_settings.file_format='PNG';scene.view_settings.view_transform='AgX';scene.view_settings.look='AgX - Medium High Contrast';scene.view_settings.exposure=-.5
for name,g in modules.items():
    if '--upright-only' in sys.argv and name in ('world','audio','mix'):continue
    if '--only' in sys.argv and name!=sys.argv[sys.argv.index('--only')+1]:continue
    if '--skip' in sys.argv and name==sys.argv[sys.argv.index('--skip')+1]:continue
    if '--sides-only' in sys.argv and name=='world':continue
    for other,root in modules.items():
        for ob in [root]+list(root.children_recursive):ob.hide_render=other!=name
    target=(0,0,1.5) if name=='mix' else (0,0,0) if name in ('world','audio') else (0,0,3.30)
    floor.location.z=.0 if name=='mix' else -.70 if name=='audio' else -.57 if name=='world' else -1.55
    for view,loc in [('front',(15,-27,15)),('left',(-25,-7,11)),('right',(25,-7,11)),('rear',(-12,27,11))]:
        if '--sides-only' in sys.argv and view=='front':continue
        if name in ('world','audio'):loc={'front':(17,-22,25),'left':(-19,-8,22),'right':(19,-8,24),'rear':(12,19,18)}[view]
        if name=='mix':loc={'front':(28,-35,33),'left':(-32,-10,23),'right':(32,-10,23),'rear':(-14,38,18)}[view]
        c.location=loc;c.rotation_euler=(Vector(target)-c.location).to_track_quat('-Z','Y').to_euler()
        d.ortho_scale=37 if name=='mix' else 12 if name in ('world','audio') else (17.8 if view in ('front','rear') else 13.8)
        suffix='' if view=='front' else '-'+view
        scene.render.filepath=str(IMG/f'cartridge-{name}{suffix}.png');bpy.ops.render.render(write_still=True)
    print('CARTRIDGE_RENDERED',name,flush=True)
