from pathlib import Path
from xml.etree import ElementTree as E
import sys,zipfile,json,uuid,trimesh as t,numpy as np
q=lambda s:'{http://schemas.microsoft.com/3dmanufacturing/core/2015/02}'+s
p=lambda s:'{http://schemas.microsoft.com/3dmanufacturing/production/2015/06}'+s
core=q('') [1:-1]; prod=p('') [1:-1]
bs='http://schemas.bambulab.com/package/2021'
rel='http://schemas.openxmlformats.org/package/2006/relationships'
typ='http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel'
uid=lambda:str(uuid.uuid4())
base=f'<model unit="millimeter" xmlns="{core}" xmlns:p="{prod}" xmlns:BambuStudio="{bs}" requiredextensions="p">'
identity='1 0 0 0 1 0 0 0 1'
meshparts={}; rootobj=[]; build=[]; leaves=[]
cfg=E.Element('config')
def md(e,k,w):E.SubElement(e,'metadata',key=k,value=str(w))
def rels(targets):
 return f'<Relationships xmlns="{rel}">'+''.join(f'<Relationship Target="{x}" Id="rel-{i}" Type="{typ}"/>' for i,x in enumerate(targets,1))+'</Relationships>'
plateitems=[[],[]]; placements=[]
for i,(key,name,x,y,plate) in enumerate([('BO','双夔菱锦镂空零食盒',91,128,0),('Divider','通用挡片',195,128,0),('DO','三星堆栖枝鸟镂空零食盒',91,128,1),('Divider','通用挡片',195,128,1)],1):
 d=json.loads(Path(f'{key}.json').read_text());v,inv=np.unique(np.array(d['v']).round(6),return_inverse=True,axis=0);f=inv[np.array(d['f'])]
 if key=='Divider':v=v[:,[0,2,1]]*np.array([1,-1,1])
 v-=np.array([*(v.max(0)+v.min(0))[:2]/2,v[:,2].min()])
 m=t.Trimesh(v,f,process=False)
 components=m.split(only_watertight=False)
 if len(components)!=1:
  outer=[c for c in components if c.volume>0]; assert len(outer)==1
  for c in components:
   if c.volume>0:continue
   assert c.is_watertight and c.is_winding_consistent and abs(c.volume)<.001 and max(c.extents)<.4
   assert np.all(c.bounds[0]>=outer[0].bounds[0]) and np.all(c.bounds[1]<=outer[0].bounds[1])
  m=outer[0]; v,f=m.vertices,m.faces
 assert m.is_watertight and m.is_winding_consistent and abs(m.volume-d['vol'])<.001*d['vol']
 assert ((m.bounds[:,:2]+[x,y])>=2.99).all() and ((m.bounds[:,:2]+[x,y])<=253.01).all()
 print('plate-local bounds', (m.bounds[:,:2]+[x,y]).tolist(), flush=True)
 leaf=f'/3D/Objects/object_{i}.model';leaves.append(leaf); leafid=i+10
 meshparts[leaf[1:]]=base+f'<resources><object id="{leafid}" type="model" name="{name}" p:UUID="{uid()}"><mesh><vertices>'+''.join(f'<vertex x="{a:.6f}" y="{b:.6f}" z="{c:.6f}"/>' for a,b,c in v)+'</vertices><triangles>'+''.join(f'<triangle v1="{a}" v2="{b}" v3="{c}"/>' for a,b,c in f)+'</triangles></mesh></object></resources><build/></model>'
 rootobj.append(f'<object id="{i}" type="model" name="{name}" p:UUID="{uid()}"><components><component p:path="{leaf}" objectid="{leafid}" transform="{identity} 0 0 0" p:UUID="{uid()}"/></components></object>')
 tr=f'{identity} {x+plate*307.2} {y} 0';build.append(f'<item objectid="{i}" transform="{tr}" printable="1" p:UUID="{uid()}"/>')
 o=E.SubElement(cfg,'object',id=str(i));md(o,'name',name);md(o,'extruder',1);E.SubElement(o,'metadata',face_count=str(len(f)))
 part=E.SubElement(o,'part',id=str(leafid),subtype='normal_part');md(part,'name',name);md(part,'matrix','1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1')
 E.SubElement(part,'mesh_stat',face_count=str(len(f)),edges_fixed='0',degenerate_facets='0',facets_removed='0',facets_reversed='0',backwards_edges='0')
 plateitems[plate].append(i);placements.append(tr)
 print(i,name,len(f),m.volume,m.extents,flush=True)
for j,ids in enumerate(plateitems,1):
 pl=E.SubElement(cfg,'plate')
 for k,w in [('plater_id',j),('plater_name',('双夔菱锦镂空','三星堆栖枝鸟镂空')[j-1]),('locked','false'),('filament_map_mode','Auto For Flush'),('filament_maps','1'),('filament_volume_maps','0')]:md(pl,k,w)
 for i in ids:
  inst=E.SubElement(pl,'model_instance')
  for k,w in [('object_id',i),('instance_id',0),('identify_id',100+i)]:md(inst,k,w)
a=E.SubElement(cfg,'assemble')
for i,tr in enumerate(placements,1):E.SubElement(a,'assemble_item',object_id=str(i),instance_id='0',transform=tr,offset='0 0 0')
root=base+'<metadata name="Application">BambuStudio-02.09.02.62</metadata><metadata name="BambuStudio:3mfVersion">1</metadata><metadata name="Title">国风零食栏 · 两款原纹样镂空</metadata><resources>'+''.join(rootobj)+f'</resources><build p:UUID="{uid()}">'+''.join(build)+'</build></model>'
template=Path(sys.argv[1])
with zipfile.ZipFile(template) as z:
 types=z.read('[Content_Types].xml');profile=json.loads(z.read('Metadata/project_settings.config'))
assert profile['printer_settings_id']=='Bambu Lab P1S 0.4 nozzle' and profile['filament_settings_id']==['Generic PETG']
settings=dict(enable_prime_tower='0',enable_support='0',layer_height='0.2',wall_loops='2',top_shell_layers='5',bottom_shell_layers='3',sparse_infill_density='15%',sparse_infill_pattern='gyroid',infill_combination='0',print_sequence='by layer',brim_type='no_brim')
profile.update(settings)
keys=profile['different_settings_to_system'];keys[0]=';'.join(sorted(set(keys[0].split(';'))|set(settings)))
with zipfile.ZipFile(sys.argv[2],'w',zipfile.ZIP_DEFLATED,compresslevel=4) as z:
 for k,v in {'[Content_Types].xml':types,'_rels/.rels':rels(['/3D/3dmodel.model']),'3D/_rels/3dmodel.model.rels':rels(leaves),'3D/3dmodel.model':root,'Metadata/project_settings.config':json.dumps(profile,ensure_ascii=False),'Metadata/model_settings.config':E.tostring(cfg,encoding='utf-8'),**meshparts}.items():z.writestr(k,v)
