import bpy, math, json, sys, os, argparse
from pathlib import Path
from mathutils import Vector, Quaternion

ROOT=Path(__file__).resolve().parents[1]
P=json.loads((ROOT.parent/'02_CAD_and_Parameters'/'design_parameters.json').read_text(encoding='utf-8'))
M=.001
args=sys.argv[sys.argv.index('--')+1:] if '--' in sys.argv else []
parser=argparse.ArgumentParser();parser.add_argument('--preview',action='store_true');opts=parser.parse_args(args)
bpy.ops.object.select_all(action='SELECT');bpy.ops.object.delete(use_global=False)
for co in list(bpy.data.collections):
    if co.name!='Collection':bpy.data.collections.remove(co)
base=bpy.data.collections.get('Collection');base.name='01_MODEL_PARTS'
studio=bpy.data.collections.new('90_STUDIO');bpy.context.scene.collection.children.link(studio)
scene=bpy.context.scene
scene.unit_settings.system='METRIC';scene.unit_settings.length_unit='MILLIMETERS';scene.unit_settings.scale_length=1
scene.frame_start=1;scene.frame_end=120
scene.render.engine='CYCLES';scene.cycles.samples=48 if opts.preview else 96
scene.cycles.use_adaptive_sampling=True;scene.cycles.adaptive_threshold=.035
scene.cycles.use_denoising=True;scene.cycles.max_bounces=8
try:
    pref=bpy.context.preferences.addons['cycles'].preferences;pref.compute_device_type='CUDA';pref.get_devices()
    for dev in pref.devices:dev.use=dev.type=='CUDA'
    scene.cycles.device='GPU'
except Exception as e:print('GPU_SETUP',e,flush=True)
scene.render.resolution_x=1400 if opts.preview else 2200
scene.render.resolution_y=1050 if opts.preview else 1650
scene.render.resolution_percentage=100
scene.render.image_settings.file_format='PNG';scene.render.image_settings.color_mode='RGBA';scene.render.image_settings.color_depth='8'
scene.render.film_transparent=False
scene.view_settings.view_transform='AgX';scene.view_settings.exposure=-1.1
try:scene.view_settings.look='AgX - Medium High Contrast'
except Exception:pass
scene.world.color=(.8,.8,.8)
scene.world.use_nodes=True
scene.world.node_tree.nodes['Background'].inputs['Color'].default_value=(.86,.88,.93,1)
scene.world.node_tree.nodes['Background'].inputs['Strength'].default_value=.2

def mat(name,color,metal=0,rough=.3,coat=0,noise=False):
    m=bpy.data.materials.new(name);m.use_nodes=True
    n=m.node_tree.nodes;p=n.get('Principled BSDF')
    p.inputs['Base Color'].default_value=(*color,1);p.inputs['Metallic'].default_value=metal
    p.inputs['Roughness'].default_value=rough;p.inputs['Coat Weight'].default_value=coat
    p.inputs['Coat Roughness'].default_value=.2
    if noise:
        tex=n.new('ShaderNodeTexNoise');tex.inputs['Scale'].default_value=1800;tex.inputs['Detail'].default_value=2
        bump=n.new('ShaderNodeBump');bump.inputs['Strength'].default_value=.035;bump.inputs['Distance'].default_value=.00008
        m.node_tree.links.new(tex.outputs['Fac'],bump.inputs['Height']);m.node_tree.links.new(bump.outputs['Normal'],p.inputs['Normal'])
    m.diffuse_color=(*color,1)
    return m
ENAMEL=mat('Uniform white enamel inside and outside',(.82,.815,.79),.05,.235,.28,True)
INSIDE=ENAMEL
STEEL=mat('Satin stainless steel',(.53,.57,.59),.92,.245,.08)
BRIGHT=mat('Polished stainless wire',(.64,.68,.70),1,.175,.05)
BLACK=mat('Charcoal phenolic grip',(.022,.026,.025),.0,.4,.05,True)
RUBBER=mat('Foot pad concept',(.026,.029,.03),0,.65)
CARBON=mat('Heat resistant charcoal grate',(.12,.14,.145),.85,.36)
GROUND=mat('Warm studio surface',(.72,.705,.67),0,.83)

def move_collection(o,co):
    for cc in list(o.users_collection):cc.objects.unlink(o)
    co.objects.link(o)
def attach(o,parent,keep=True):
    if parent:
        mw=o.matrix_world.copy();o.parent=parent
        if keep:o.matrix_world=mw
    return o
def empty(name,p=(0,0,0),parent=None):
    o=bpy.data.objects.new(name,None);base.objects.link(o);o.empty_display_type='PLAIN_AXES';o.empty_display_size=.02
    o.location=Vector(p)*M;bpy.context.view_layer.update();attach(o,parent)
    return o
ASSEMBLY=empty('EN_LIGHT_ASSEMBLY')
ASSEMBLY['design_status']='Visualisation model based on Rev B nominal dimensions; not a manufacturing solid or tooling release.'
ASSEMBLY['body_OD_mm']=330;ASSEMBLY['closed_height_mm']=240
ASSEMBLY['view_presets']='Frame 1: deployed; Frame 60: exploded; Frame 90: stowed; Frame 120: legs up for carrying'

def finish(o,name,material,parent=None,bevel=0,smooth=True):
    o.name=name;move_collection(o,base)
    if material:o.data.materials.append(material)
    if bevel:
        mod=o.modifiers.new('Small edge radius','BEVEL');mod.width=bevel*M;mod.segments=3
    if smooth and hasattr(o.data,'polygons'):
        for p in o.data.polygons:p.use_smooth=True
    bpy.context.view_layer.update();attach(o,parent)
    return o
def cube(name,p,d,material,parent=None,bevel=.3):
    bpy.ops.mesh.primitive_cube_add(size=1,location=Vector(p)*M)
    o=bpy.context.object;o.dimensions=Vector(d)*M
    bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
    return finish(o,name,material,parent,bevel,False)
def cyl(name,p,r,depth,material,parent=None,axis=(0,0,1),verts=64,bevel=.12):
    bpy.ops.mesh.primitive_cylinder_add(vertices=verts,radius=r*M,depth=depth*M,location=Vector(p)*M)
    o=bpy.context.object;o.rotation_mode='QUATERNION';o.rotation_quaternion=Vector(axis).to_track_quat('Z','Y')
    return finish(o,name,material,parent,bevel)
def rod(name,a,b,r,material,parent=None,verts=16):
    a=Vector(a);b=Vector(b)
    return cyl(name,(a+b)/2,r,(b-a).length,material,parent,b-a,verts,0)
def path(name,pts,r,material,parent=None,res=10):
    data=bpy.data.curves.new(name,'CURVE');data.dimensions='3D';data.resolution_u=1
    sp=data.splines.new('POLY');sp.points.add(len(pts)-1)
    for q,p in zip(sp.points,pts):q.co=(*(Vector(p)*M),1)
    data.bevel_depth=r*M;data.bevel_resolution=res//2;data.resolution_u=1;data.use_fill_caps=True
    o=bpy.data.objects.new(name,data);base.objects.link(o);data.materials.append(material)
    bpy.context.view_layer.update();attach(o,parent)
    return o
def ring(name,p,major,minor,material,parent=None,axis=(0,0,1)):
    bpy.ops.mesh.primitive_torus_add(major_radius=major*M,minor_radius=minor*M,major_segments=160,minor_segments=12,location=Vector(p)*M)
    o=bpy.context.object;o.rotation_mode='QUATERNION';o.rotation_quaternion=Vector(axis).to_track_quat('Z','Y')
    return finish(o,name,material,parent)
def lathe(name,profile,material,parent=None,inside_from=None,n=160):
    verts=[];rings=[]
    for r,z in profile:
        if r<.0001:
            rings.append([len(verts)]);verts.append((0,0,z*M))
        else:
            ids=[]
            for j in range(n):
                a=2*math.pi*j/n;ids.append(len(verts));verts.append((r*M*math.cos(a),r*M*math.sin(a),z*M))
            rings.append(ids)
    faces=[];mats=[]
    for i in range(len(rings)):
        a=rings[i];b=rings[(i+1)%len(rings)]
        for j in range(n):
            k=(j+1)%n
            if len(a)==len(b)==1:break
            if len(a)==1:f=(a[0],b[k],b[j])
            elif len(b)==1:f=(a[j],a[k],b[0])
            else:f=(a[j],a[k],b[k],b[j])
            faces.append(f);mats.append(1 if inside_from is not None and i>=inside_from else 0)
    mesh=bpy.data.meshes.new(name);mesh.from_pydata(verts,[],faces);mesh.update()
    o=bpy.data.objects.new(name,mesh);base.objects.link(o);mesh.materials.append(material)
    if inside_from is not None:mesh.materials.append(INSIDE)
    for f,mi in zip(mesh.polygons,mats):f.material_index=mi;f.use_smooth=True
    bpy.context.view_layer.update();attach(o,parent)
    return o
def boolean(o,cut):
    bpy.context.view_layer.update();mod=o.modifiers.new('Functional opening','BOOLEAN');mod.operation='DIFFERENCE';mod.solver='EXACT';mod.object=cut
    bpy.context.view_layer.objects.active=o;o.select_set(True)
    bpy.ops.object.modifier_apply(modifier=mod.name);bpy.data.objects.remove(cut,do_unlink=True)
    o.select_set(False)
def extruded_poly(name,pts,z1,z2):
    n=len(pts);verts=[(x*M,y*M,z*M) for z in [z1,z2] for x,y in pts]
    faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]
    faces += [(j,(j+1)%n,(j+1)%n+n,j+n) for j in range(n)]
    mesh=bpy.data.meshes.new(name);mesh.from_pydata(verts,[],faces);mesh.update();o=bpy.data.objects.new(name,mesh);base.objects.link(o)
    return o
def slot_points(r,a1,a2,w):
    rr=w/2;vec=lambda rad,a:Vector((rad*math.cos(math.radians(a)),rad*math.sin(math.radians(a))))
    pts=[vec(r+rr,a1+(a2-a1)*i/32) for i in range(33)]
    end=vec(r,a2);start=vec(r,a1)
    pts += [end+vec(rr,a2+180*i/16) for i in range(1,17)]
    pts += [vec(r-rr,a2-(a2-a1)*i/32) for i in range(1,33)]
    pts += [start+vec(rr,a1+180+180*i/16) for i in range(1,16)]
    return pts
def round_path(points,radius=10,steps=12):
    p=[Vector(v) for v in points];out=[p[0]]
    for a,b,d in zip(p,p[1:],p[2:]):
        va=(a-b).normalized();vb=(d-b).normalized();ang=va.angle(vb)
        le=min(radius/max(math.tan(ang/2),.001),(a-b).length*.4,(d-b).length*.4)
        r=le*math.tan(ang/2);cent=b+(va+vb).normalized()*(r/math.sin(ang/2))
        q1=b+va*le;q2=b+vb*le;u=q1-cent;v=q2-cent;axis=u.cross(v).normalized();angle=u.angle(v)
        out.append(q1)
        for j in range(1,steps+1):out.append(cent+Quaternion(axis,angle*j/steps)@u)
    out.append(p[-1]);return out
def screw(name,p,r=2.3,axis=(0,0,1),parent=None):
    p=Vector(p);a=Vector(axis).normalized()
    cyl(name+'_shaft',p,r*.6,5,STEEL,parent,a,32)
    cap=cyl(name+'_head',p+a*2.5,r,1.4,BRIGHT,parent,a,6,.1)
    return cap

def smooth_profile(points):
    p=sorted(points);n=len(p);sl=[(p[i+1][1]-p[i][1])/(p[i+1][0]-p[i][0]) for i in range(n-1)]
    m=[0]+[0 if sl[i-1]*sl[i]<=0 else 2*sl[i-1]*sl[i]/(sl[i-1]+sl[i]) for i in range(1,n-1)]+[sl[-1]]
    out=[]
    for i in range(n-1):
        x0,y0=p[i];x1,y1=p[i+1];h=x1-x0
        for j in range(12):
            t=j/12;y=(2*t**3-3*t*t+1)*y0+(t**3-2*t*t+t)*h*m[i]+(-2*t**3+3*t*t)*y1+(t**3-t*t)*h*m[i+1]
            out.append((x0+t*h,y))
    return out+[p[-1]]

# Main shell: closed-thickness lathed mesh and genuine inlet holes.
BOWL=empty('01_Bowl',parent=ASSEMBLY)
outer=[(0,75)]+smooth_profile([(90,75),(120,77),(140,87),(154,105),(158,122),(162,150),(163.5,153)])
inside_profile=[]
for i,(r,z) in enumerate(outer):
    prev=outer[max(0,i-1)];nxt=outer[min(len(outer)-1,i+1)];dr=nxt[0]-prev[0];dz=nxt[1]-prev[1];length=math.hypot(dr,dz)
    inside_profile.append((max(0,r-.8*dz/length),z+.8*dr/length))
inner=inside_profile[::-1]
body=lathe('01_Enamel_bowl_t0.8',outer+inner,ENAMEL,BOWL,len(outer))
for i in range(6):
    a=i*math.tau/6+math.radians(7.5)
    cut=cyl('CUT_body_inlet',(22*math.cos(a),22*math.sin(a),75),5,8,None)
    boolean(body,cut)
ring('01_Rolled_rim',(0,0,154),164,1,ENAMEL,BOWL)
for a in [30,150,270]:
    ra=math.radians(a);t=cube('04_Grate_support_tab',(154*math.cos(ra),154*math.sin(ra),144.8),(13,8,1.4),STEEL,BOWL,.3)
    t.rotation_euler.z=ra

# Separate lid root allows lifted/exploded views.
LID=empty('02_Lid_assembly',(0,0,155),ASSEMBLY)
# Taller drawn lid, constant normal-offset nominal wall thickness.
lid_outer=smooth_profile(P['lid_profile_rz'])+[(166,155)]
lid_inner=[]
for i,(r,z) in enumerate(lid_outer):
    prev=lid_outer[max(0,i-1)];nxt=lid_outer[min(len(lid_outer)-1,i+1)]
    dr=nxt[0]-prev[0];dz=nxt[1]-prev[1];le=math.hypot(dr,dz)
    lid_inner.append((max(0,r+.7*dz/le),z-.7*dr/le))
prof=lid_outer+lid_inner[::-1]
lid=lathe('02_Enamel_lid_t0.7',prof,ENAMEL,LID,len(lid_outer))
ring('02_Rolled_lid_edge',(0,0,155.2),165.2,.8,ENAMEL,LID)
def lid_height(r):
    for (a,z1),(b,z2) in zip(lid_outer,lid_outer[1:]):
        if a<=r<=b:return z1+(z2-z1)*(r-a)/(b-a)
    raise ValueError(r)
# No fixed lid-top handle. Hot lid removal uses a separate purchased rim clamp.

# Inclined exhaust disc with arc windows through rotor, back plate and lid.
rr=math.hypot(105,50);zz=lid_height(rr)
root=empty('08_Exhaust_local')
back=cyl('08_Vent_backplate',(0,0,.3),28,.5,STEEL,root,bevel=.1)
rotor=cyl('08_Vent_rotor',(0,0,.95),27.5,.6,BRIGHT,root,bevel=.1)
for a in [0,120,240]:
    polygon=slot_points(18,a,a+70,6)
    for ob in [back,rotor]:boolean(ob,extruded_poly('CUT_vent',polygon,-4,5))
tab=cube('08_Insulated_exhaust_tab',(0,-25,5.3),(8,4,10),BLACK,root,1)
screw('08_Central_rivet',(0,0,.7),3,parent=root)
slope=(lid_height(rr+.05)-lid_height(rr-.05))/.1
dzx=slope*(-105)/rr;dzy=slope*(-50)/rr
root.location=Vector((-105,-50,zz+.3))*M;root.rotation_mode='QUATERNION';root.rotation_quaternion=Vector((-dzx,-dzy,1)).to_track_quat('Z','Y')
bpy.context.view_layer.update()
for a in [0,120,240]:
    cutter=extruded_poly('CUT_lid_exhaust',slot_points(18,a,a+70,6),-8,8)
    cutter.matrix_world=root.matrix_world.copy();boolean(lid,cutter)
attach(root,LID)

# Grates are individual welded wires; no texture substitutes.
FOOD=empty('04_Food_grate',(0,0,150),ASSEMBLY)
ring('04_Outer_ring',(0,0,147.75),150.25,2.25,BRIGHT,FOOD)
for i in range(-14,15):
    x=i*10;y=math.sqrt(148**2-x*x)
    rod(f'04_Grill_wire_{i+14:02d}',(x,-y,148.25),(x,y,148.25),1.75,BRIGHT,FOOD)
for y in [-65,65]:
    x=math.sqrt(148**2-y*y);rod('04_Under_wire',(-x,y,144.9),(x,y,144.9),1.5,STEEL,FOOD)
for y in [-136,136]:
    path('04_Grate_lift_tab',[(-10,y,150),(-10,y,155),(10,y,155),(10,y,150)],1.1,BRIGHT,FOOD,6)
CHAR=empty('05_Charcoal_grate',(0,0,95),ASSEMBLY)
ring('05_Charcoal_ring',(0,0,92.5),107.5,2.5,CARBON,CHAR)
for i in range(-8,9):
    x=i*12;y=math.sqrt(105**2-x*x);rod('05_Charcoal_wire',(x,-y,93),(x,y,93),2,CARBON,CHAR)
for a in [30,150,270]:
    a=math.radians(a)
    rod('05_Grate_standoff',(100*math.cos(a),100*math.sin(a),92.5),(75*math.cos(a),75*math.sin(a),76.5),1.5,CARBON,CHAR)

print('MODEL_STAGE_1_COMPLETE',flush=True)

# Low-profile removable ash cup and rotating intake collar.
ASH=empty('09_Ash_cup_intake',parent=ASSEMBLY)
cup=lathe('09_Closed_bottom_ash_cup',[(0,53),(49.4,53),(50,53.6),(50,75),(49.4,75),(49.4,53.6),(0,53.6)],STEEL,ASH,n=96)
collar=lathe('09_Rotating_intake_collar',[(50.3,58),(50.9,58),(50.9,72),(50.3,72)],BRIGHT,ASH,n=96)
for a in [-90,30,150]:
    ar=math.radians(a)
    for ob in [cup,collar]:
        cut=cube('CUT_intake',(50*math.cos(ar),50*math.sin(ar),65),(7,20,8),None,bevel=.1)
        cut.rotation_euler.z=ar;boolean(ob,cut)
cube('09_Intake_tab_steel',(0,-55,54),(14,18,1),STEEL,ASH,.5)
cube('09_Intake_tab_grip',(0,-61,53),(15,12,3),BLACK,ASH,1)
for a in [30,150,270]:
    ar=math.radians(a);cube('09_Provisional_bayonet_lug',(49*math.cos(ar),49*math.sin(ar),73),(5,3,1.5),STEEL,ASH,.3)

SHIELD=empty('10_Local_heat_reflector',parent=ASSEMBLY)
cyl('10_Reflector_disc',(0,0,44.75),99.5,.5,STEEL,SHIELD,verts=128,bevel=.04)
ring('10_Reflector_rolled_edge',(0,0,44.5),99.5,.5,BRIGHT,SHIELD)
for x in [-80,80]:
    for y in [-20,20]:
        cube('10_Hanger_strip',(x,y,60),(1,5,29),STEEL,SHIELD,.15)
        cube('10_Hanger_top_tab',(x,y,74.5),(7,5,1),STEEL,SHIELD,.2)
        cube('10_Hanger_base_tab',(x,y,45.5),(7,5,1),STEEL,SHIELD,.2)

# USER-CONFIRMED: both supporting U-frames flip upwards to become the carry handle.
# Coaxial short pivots at each side, without a shaft passing through the firebox.
LEGS=[]
for sg,label,halfspan in [(1,'FRONT',170),(-1,'REAR',178)]:
    frame=empty('06_Flip_frame_'+label,(0,0,112),ASSEMBLY);LEGS.append((sg,frame))
    pts=round_path([(-halfspan,0,112),(-halfspan,sg*148,7),(halfspan,sg*148,7),(halfspan,0,112)],12,16)
    path('06_Dual_use_U_frame_'+label,pts,3,BRIGHT,frame)
    cyl('06_Dual_grip_foot_sleeve_'+label,(0,sg*148,7),7,80,BLACK,frame,(1,0,0),64,.8)
    for x in [-115,115]:
        cyl('06_Foot_pad_'+label,(x,sg*148,7),7,20,RUBBER,frame,(1,0,0),48,.8)
    for side in [-1,1]:
        lug=cube('06_Rotating_frame_lug_'+label,(side*halfspan,0,112),(2,13,16),STEEL,frame,.7)
        cut=cyl('CUT_frame_pin',(side*halfspan,0,112),2.7,5,None,axis=(1,0,0),bevel=0);boolean(lug,cut)
for side in [-1,1]:
    mounting=cube('11_Pre_enamel_shell_backing_CONCEPT',(side*157,0,112),(1.8,27,34),STEEL,BOWL,1)
    mounting['status']='Factory to finalize pre-enamel welding, inner backing and heat/load tests.'
    cyl('11_Short_side_shoulder_pin',(side*170,0,112),2.5,28,STEEL,BOWL,(1,0,0),48,.1)
    cyl('11_Pivot_spacer',(side*163,0,112),5,8,STEEL,BOWL,(1,0,0),48,.1)
    for x in [166,174,182]:
        cyl('11_Axial_spacer_washer',(side*x,0,112),6,1,STEEL,BOWL,(1,0,0),48,.1)
    cyl('11_Shoulder_pin_head',(side*185,0,112),4.5,2,BRIGHT,BOWL,(1,0,0),6,.1)
    # Small blocks mark required stationary stop/lock volumes; not final mechanism geometry.
    stop=cube('11_Required_deployed_stop_CONCEPT',(side*163,9,99),(9,8,5),STEEL,BOWL,.5)
    lock=cube('11_Independent_frame_lock_CONCEPT',(side*183,9,121),(2,8,11),STEEL,BOWL,.5)
    lock['status']='Concept location only. Both frames require deployed positive locks; carry detents/coupling also to be engineered.'

# Two small spring clips indicate cold-transport retention only.
for sg in [-1,1]:
    x=sg*120;y=-math.sqrt(165**2-x*x);a=math.atan2(y,x)
    tang=Vector((-math.sin(a),math.cos(a),0));rad=Vector((math.cos(a),math.sin(a),0))
    def clip_pos(r,z):return Vector((r*math.cos(a),r*math.sin(a),z))
    pp=[clip_pos(165.5,142),clip_pos(168,144),clip_pos(168,154),clip_pos(167,159),clip_pos(163.5,159)]
    # Ribbon mesh; two faces form a visible, replaceable metal clip.
    vv=[tuple((p+tang*side*4)*M) for p in pp for side in [-1,1]]
    ff=[(2*i,2*i+1,2*i+3,2*i+2) for i in range(len(pp)-1)]
    mesh=bpy.data.meshes.new('12_Clip_ribbon');mesh.from_pydata(vv,[],ff);mesh.update()
    ob=bpy.data.objects.new('12_Transport_clip_CONCEPT',mesh);base.objects.link(ob);mesh.materials.append(STEEL)
    so=ob.modifiers.new('Spring strip thickness','SOLIDIFY');so.thickness=.6*M
    be=ob.modifiers.new('Clip edge radius','BEVEL');be.width=.25*M;be.segments=3
    attach(ob,BOWL)
    screw('12_Clip_fixing',clip_pos(166,144),2.2,rad,BOWL)

# Correct shell orientation after booleans. Mesh parts remain separate and named.
import bmesh
for ob in list(base.objects):
    if ob.type=='MESH':
        bm=bmesh.new();bm.from_mesh(ob.data)
        bmesh.ops.remove_doubles(bm,verts=list(bm.verts),dist=1e-7)
        bmesh.ops.dissolve_degenerate(bm,edges=list(bm.edges),dist=1e-10)
        if ob in [body,lid,cup]:
            boundary=[e for e in bm.edges if e.is_boundary]
            if boundary:bmesh.ops.holes_fill(bm,edges=boundary,sides=4)
        bmesh.ops.recalc_face_normals(bm,faces=bm.faces);bm.to_mesh(ob.data);bm.free()

# Animation doubles as three easy-to-find model presets.
def key(o,frame,location=None,rotation=None):
    if location is not None:o.location=Vector(location)*M;o.keyframe_insert(data_path='location',frame=frame)
    if rotation is not None:o.rotation_mode='XYZ';o.rotation_euler=rotation;o.keyframe_insert(data_path='rotation_euler',frame=frame)
for frame in [1,60,90,120]:
    exploded=frame==60;stowed=frame==90;carried=frame==120
    key(ASSEMBLY,frame,(0,0,-P['stow_drop'] if stowed else 0))
    key(LID,frame,(0,0,475 if exploded else 155))
    key(FOOD,frame,(0,0,295 if exploded else 150))
    key(CHAR,frame,(0,0,200 if exploded else 95))
    key(ASH,frame,(0,0,-24 if exploded else 0))
    key(SHIELD,frame,(0,0,-36 if exploded else 0))
    angle=P['carry_angle_deg'] if carried else P['stow_angle_deg'] if stowed else 0
    for sg,frame_root in LEGS:key(frame_root,frame,rotation=(sg*math.radians(angle),0,0))
for ob in base.objects:
    if ob.animation_data and ob.animation_data.action:
        try:
            for fc in ob.animation_data.action.fcurves:
                for k in fc.keyframe_points:k.interpolation='LINEAR'
        except Exception:pass
for frame,name in [(1,'01 DEPLOYED - legs support'),(60,'02 EXPLODED - structure'),(90,'03 STOWED - compact'),(120,'04 CARRY - legs flip up')]:scene.timeline_markers.new(name,frame=frame)

# Studio: actual ray-traced lighting, no background bitmap.
bpy.ops.mesh.primitive_plane_add(size=200,location=(0,0,-.001))
floor=bpy.context.object;floor.name='Studio_ground';floor.data.materials.append(GROUND);move_collection(floor,studio)
def area(name,p,power,size,color,target=(0,0,.12),shape='DISK'):
    data=bpy.data.lights.new(name,'AREA');data.energy=power;data.shape=shape;data.size=size;data.color=color
    ob=bpy.data.objects.new(name,data);studio.objects.link(ob);ob.location=p;ob.rotation_euler=(Vector(target)-ob.location).to_track_quat('-Z','Y').to_euler();return ob
area('Key_softbox',(.15,-.38,.75),12,.52,(1,.94,.86))
area('Left_fill',(-.5,-.15,.38),6,.4,(.84,.9,1))
area('Rim_strip',(.35,.35,.58),14,.38,(1,.98,.93))
area('Front_reflection',(-.1,-.5,.15),2.5,.28,(1,1,1))
camdata=bpy.data.cameras.new('Product_camera');camera=bpy.data.objects.new('Product_camera',camdata);studio.objects.link(camera);scene.camera=camera
def cam(pos,target,ortho=None):
    camera.location=pos;camera.rotation_euler=(Vector(target)-camera.location).to_track_quat('-Z','Y').to_euler()
    if ortho:camdata.type='ORTHO';camdata.ortho_scale=ortho
    else:camdata.type='PERSP';camdata.lens=62;camdata.sensor_width=36
cam((.58,-.76,.48),(0,0,.115),.60)
camera.name='Camera_CLOSED'
def preset_camera(name,pos,target,scale):
    data=camdata.copy();data.name=name;data.type='ORTHO';data.ortho_scale=scale
    ob=bpy.data.objects.new(name,data);studio.objects.link(ob);ob.location=pos
    ob.rotation_euler=(Vector(target)-ob.location).to_track_quat('-Z','Y').to_euler();return ob
CAMERAS={1:camera,60:preset_camera('Camera_EXPLODED',(.75,-1.1,.73),(0,0,.295),.87),90:preset_camera('Camera_STOWED',(.52,-.68,.38),(0,0,.115),.55),120:preset_camera('Camera_CARRY',(.52,-.68,.36),(0,0,.175),.54)}
for marker in scene.timeline_markers:marker.camera=CAMERAS[marker.frame]
scene.frame_set(1)

# Readable landing state when the engineer opens the .blend file.
for area_ in bpy.context.screen.areas:
    if area_.type=='VIEW_3D':
        area_.spaces.active.region_3d.view_perspective='CAMERA';area_.spaces.active.clip_end=100
        area_.spaces.active.shading.type='MATERIAL'
        area_.spaces.active.overlay.show_floor=False
for ob in bpy.context.selected_objects:ob.select_set(False)
ASSEMBLY.select_set(True);bpy.context.view_layer.objects.active=ASSEMBLY

# Model notes are embedded in the native file, independent of external files.
notes=bpy.data.texts.new('READ_ME_EN_LIGHT')
notes.write('EN LIGHT - REV B - ENGLISH EDITION\nDesign revision: 2026-11-02. English issue: 2026-11-03.\n\nUser-confirmed arrangement: both U-shaped leg frames flip upwards and meet as the carrying grip. There is no separate carry bail or fixed lid-top handle.\nLid rise changes from 32 to 85 mm. The bowl and lid have the same white enamel on both sides. Nominal central headroom is 89.3 mm. A D280 x H50 food-cylinder example has about 10.3 mm minimum vertical clearance, excluding enamel, deformation and tolerances.\n\nTimeline presets:\nFrame 1: legs deployed, lid closed.\nFrame 60: exploded structure.\nFrame 90: compact stowage, frames rotated about 11.3 degrees.\nFrame 120: frames raised about 122.2 degrees for suspended carrying. This is not a resting configuration.\nLinear keyframe interpolation illustrates poses; it is not an operating sequence or a complete collision check.\n\nThe short side pivots are coaxial along X. Front and rear frames are offset axially by 8 mm. Each central grip/foot sleeve is L80 x OD14; their raised centre spacing is 20 mm. The sleeve underside is about 46.2 mm above the lid crown.\nRigid deployed stops, independent anti-fold locks for both frames, three-position retention and a coupling between the grips remain to be engineered. Small lock blocks only indicate required locations.\nAfter complete cooling, empty the ash, latch the lid and support the cold body while moving the frames. Validate one-person operation on a sample. Restore and lock both support frames before resting the grill on a table.\nA separate purchased rim-clamp lid lifter is required for hot-lid removal and must be tested. Do not use the vent as a handle.\n\nLocal geometric checks do not constitute thermal, strength, stability or tooling approval. Existing mould dimensions have not been obtained, so mould reuse is unconfirmed.\nScene units are metres; displayed lengths are millimetres. This editable mesh/curve visualization is not parametric mechanical CAD or STEP.\n')
BLEND=ROOT/'EN_Light_RevB_3D_Model.blend'
for material in list(bpy.data.materials):
    if material.users==0:bpy.data.materials.remove(material)
bpy.ops.wm.save_as_mainfile(filepath=str(BLEND),compress=True)
print('BLEND_SAVED',str(BLEND),flush=True)

# First closed view can be checked before spending time on all final views.
scene.render.filepath=str(ROOT/('preview_closed.png' if opts.preview else '01_Blender_Closed_Deployed.png'))
bpy.ops.render.render(write_still=True)
if opts.preview:
    print('PREVIEW_COMPLETE',flush=True)
else:
    scene.frame_set(60);scene.camera=CAMERAS[60]
    scene.render.resolution_x=1760;scene.render.resolution_y=2200
    scene.render.filepath=str(ROOT/'02_Blender_Exploded_View.png');bpy.ops.render.render(write_still=True)
    scene.render.resolution_x=2200;scene.render.resolution_y=1650
    scene.frame_set(90);scene.camera=CAMERAS[90]
    scene.render.filepath=str(ROOT/'03_Blender_Stowed.png');bpy.ops.render.render(write_still=True)
    scene.frame_set(120);scene.camera=CAMERAS[120]
    scene.render.filepath=str(ROOT/'04_Blender_Legs_Up_Carry.png');bpy.ops.render.render(write_still=True)

    # GLB preview: evaluate all curves/modifiers as meshes, without changing native parts.
    scene.frame_set(1);scene.camera=CAMERAS[1]
    for ob in bpy.context.selected_objects:ob.select_set(False)
    temp=bpy.data.collections.new('TEMP_GLB_EXPORT');scene.collection.children.link(temp)
    deps=bpy.context.evaluated_depsgraph_get();exported=[]
    for ob in list(base.objects):
        if ob.type not in ['MESH','CURVE']:continue
        ev=ob.evaluated_get(deps);mesh=bpy.data.meshes.new_from_object(ev,depsgraph=deps)
        dup=bpy.data.objects.new(ob.name,mesh);temp.objects.link(dup);dup.matrix_world=ob.matrix_world.copy();dup.select_set(True);exported.append(dup)
    bpy.ops.export_scene.gltf(filepath=str(ROOT/'EN_Light_RevB_3D_Preview.glb'),export_format='GLB',use_selection=True,export_animations=False,export_apply=True)
    for ob in exported:bpy.data.objects.remove(ob,do_unlink=True)
    bpy.data.collections.remove(temp)
    ASSEMBLY.select_set(True);bpy.context.view_layer.objects.active=ASSEMBLY
    scene.render.filepath=str(ROOT/'01_Blender_Closed_Deployed.png')
    bpy.ops.wm.save_as_mainfile(filepath=str(BLEND),compress=True)

metrics={'blender_version':bpy.app.version_string,'model_objects':len(base.objects),'mesh_objects':sum(o.type=='MESH' for o in base.objects),'curve_objects':sum(o.type=='CURVE' for o in base.objects),'frame_presets':{'deployed':1,'exploded':60,'stowed':90,'leg_frames_up_carry':120},'nominal_dimensions_mm':P,'status':'Visualisation model, not mechanical CAD or a tooling release'}
(ROOT/'support'/'model_manifest.json').write_text(json.dumps(metrics,ensure_ascii=False,indent=2),encoding='utf-8')
print('ALL_COMPLETE',json.dumps(metrics),flush=True)
