from drawing_geometry import *

def table(x,y,widths,headers,rows,rh=8,size=2.5):
    for i,row in enumerate([headers]+rows):
        xx=x;yy=y+i*rh
        for w,value in zip(widths,row):
            box(xx,yy,w,rh,LIGHT if i==0 else None)
            f='B' if i==0 else 'CN';fs=size
            lines=wrap_text(value,w-4,fs,f)
            while len(lines)*fs*1.16>rh-1.6:
                fs-=.05;lines=wrap_text(value,w-4,fs,f)
            assert fs>=2.0,(value,fs)
            height=len(lines)*fs*1.16
            baseline=yy+(rh-height)/2+fs*.85
            for j,line in enumerate(lines):tx(xx+2,baseline+j*fs*1.16,line,fs,f)
            xx+=w

# Sheet 1 - unchanged Rev B geometry, all-English labels.
sheet(1,'GENERAL ARRANGEMENT & FINISH','1:3 / details schematic')
v=View('ELB01_TOP',90,92,1/3);top(v)
v.dx((-166,0),(166,0),178,'LID OD 332')
tx(43,153,'TOP',3,'B')
v=View('ELB01_FRONT',90,241,1/3);front(v)
v.dy((-155,0),(0,240),-208,'240')
v.dx((-186,112),(186,112),-32,'372 MAX')
tx(42,158,'FRONT',3,'B')
v=View('ELB01_RIGHT',263,241,1/3);side(v)
v.dy((166,155),(0,240),208,'85 RISE')
v.dx((-155,0),(155,0),-32,'310 REF')
tx(215,158,'RIGHT',3,'B')
table(185,38,[112,91],['CONTROL ITEM','REV B NOMINAL / mm'],[
 ('Bowl OD / lid OD','330 / 332'),('Bowl depth / lid rise','80 / 85'),
 ('Closed height, support frames deployed','Approx. 240'),('Food / charcoal grate top','Z150 / Z95'),
 ('Raised frame top, relative to deployed Z0','Approx. 300'),('Stowed height / maximum width','Approx. 209 / 372'),
 ('Bowl and lid enamel','Same white, inside and outside')],8)
note(185,114,'User-confirmed: the two U-frames support the grill when deployed and flip up to form the carrying grip. The separate bail and fixed lid-top handle are removed. Bowl and lid use the same white enamel inside and outside.',199)
note(185,140,'Width and envelopes include provisional pivot mounts. The profiles are design targets, not measurements of existing factory moulds; mould reuse remains to be checked.',199,2.6)
note(349,181,'Shallow bowl and grate sizes retained.\n\nFrames, pivots and operation revised.\n\nBottom: air intake. Top: exhaust.',48,2.6,4.8)
c.showPage()

# Sheet 2 - translated without changing clearance controls.
sheet(2,'RAISED LID & FOOD CLEARANCE','section 1:2 / profile coordinates')
tx(23,42,'A-A INTERNAL ARRANGEMENT',3.6,'B')
note(23,51,'Dashed outline: D280 x H50 food-space example on the Z150 grate. This is not a rated cooking capacity.',205,2.6)
v=View('ELB02_SECTION',110,222,.5);front(v,section=True,food=True)
v.dx((-140,200),(140,200),267,'FOOD EXAMPLE OD 280')
v.dy((0,150),(0,239.3),0,f'{CENTER:.1f} CENTER')
v.dy((140,150),(140,z_at(LI,140)),185,f'{EDGE:.1f} AT R140')
v.dy((152.5,95),(152.5,150),223,'55')
v.leader((-143,121),(-185,117),'BOWL t0.8')
v.leader((-132,216),(-189,232),'LID t0.7')
v.leader((-50,65),(-110,28),'AIR IN / ASH CUP')
note(23,238,'For the nominal profile, the D280 x H50 cylinder has '+f'{EDGE-50:.1f} mm'+' minimum vertical space above it. Enamel, deformation, assembly variation and food shape are excluded.',207,2.6,4.7)
note(23,254,'Airflow: ash-cup side ports > bowl-bottom holes > charcoal > lid exhaust. Grate-top separation remains 55 mm.',207,2.6,4.7)
ln(241,35,241,258,LIGHT,.15)
table(250,38,[72,78],['CLOSED-LID SPACE','VALUE / mm'],[
 ('Rev A lid rise','32'),('Rev B lid rise','85'),('Central headroom',f'{CENTER:.1f}'),
 ('Headroom at R140',f'{EDGE:.1f}'),('Food-example height','50')],8)
tx(250,98,'LID OUTER PROFILE CONTROL POINTS',3.1,'B')
table(250,104,[75,75],['RADIUS R','HEIGHT Z'],[(str(r),str(z)) for r,z in P['lid_profile_rz']]+[('166','155 (rim)')],7.5)
note(250,178,'Origin: deployed support plane. R is the radius of revolution. Use smooth transitions between control points; nominal normal wall thickness is 0.7. Factory to define draw radii, draft, springback and enamel allowances.',150,2.6,4.8)
note(250,211,'Mould reuse: check rim fit, depth and inner profile while preserving food space. If an existing lid still contacts food, select a deeper lid mould or review a revised solution; visual similarity alone is insufficient.',150,2.6,4.8)
note(250,244,'Hot lid: provide and trial a purchased rim-clamp lifter. The vent and transport frames are not hot-lid handles.',150,2.6,4.8)
c.showPage()

# Sheet 3 - dual-purpose frames and carrying pose.
sheet(3,'FLIP-UP LEG / CARRY FRAMES','frame 1:2.5 / carry 1:3')
tx(22,41,'06 U-FRAME / CENTRELINE PLANE VIEW',3.4,'B')
reach=math.hypot(148,105)
v=View('ELB03_FRAME_DEVELOPED',105,149,.4)
v.rod([(-170,0),(-170,reach),(170,reach),(170,0)],6)
v.rect(-40,reach-7,80,14,'THIN')
for x in [-170,170]:v.rect(x-6,-8,12,16,'THIN');v.circle((x,0),2.7)
v.dx((-170,0),(170,0),-27,'FRONT 340 / REAR 356')
v.dy((170,0),(170,reach),207,'181.5 REF')
v.leader((-110,reach),(-210,211),'ROD 6 / R12 TARGET')
note(22,177,'Axial offset between frames: 8. Front half-span 170; rear half-span 178. Rod D6. Combined foot/grip sleeves: OD14 x L80. The 3D bends are rounded; this schematic is not a cutting-length development.',192,2.6,4.7)
tx(247,41,'SUSPENDED CARRYING POSE',3.4,'B')
v=View('ELB03_CARRY',315,178,1/3);front(v,carry=True)
v.cl(-190,0,190,0)
v.dy((186,0),(0,P['carry_total_height']),212,'~300 TO Z0')
note(247,188,'Suspended pose; Z0 remains the deployed datum. Each frame rotates up about 122.2 deg. Raised grip centres are 20 apart; sleeve undersides are about 46 above the lid crown.',151,2.6,4.7)
ln(16,205,404,205,LIGHT)
note(22,218,'Operation target: both deployed frames bear against rigid stops and have independent locks. After complete cooling, ash removal and lid latching, support the cold body while raising each frame. Join and retain the grips before lifting. Raised frames provide no resting support; restore and lock both legs before setting down.',377,2.7,5)
note(22,239,'Factory to complete: pre-enamel welded mounts with inner reinforcement; short coaxial pin stack; deployed/stowed/carry retention; independent anti-fold locks; grip coupling and load tests. Lock blocks in the model indicate required locations only; they are not finished mechanisms.',377,2.7,5)
c.showPage()

# Sheet 4 - support, stowage and retained components.
sheet(4,'SUPPORT, STOWAGE & LOWER MODULE','1:3 / grates 1:4')
tx(22,40,'DEPLOYED',3.3,'B')
v=View('ELB04_DEPLOYED',84,145,1/3);side(v)
v.dx((-155,0),(155,0),-26,'PAD DEPTH 310')
tx(170,40,'STOWED',3.3,'B')
v=View('ELB04_STOWED',230,145,1/3);front(v,fold=True)
v.dy((186,PACK_BASE),(0,240),212,'209')
note(22,163,'Pivot axis along X at Z112. Deployed rail centres: Y +/-148, Z7. Stow rotation about 11.3 deg: rail centres Y +/-165.7, Z38; pad underside Z31. Stowed envelope approximately 372 x 346 x 209.',269,2.6,4.7)
note(22,185,'Support-pad centres: X +/-115, Y +/-148. Deployed contact envelope about 250 x 310. Rigid stops and independent anti-fold locks are required for both frames. Raised-grip coupling remains to be engineered.',269,2.6,4.7)
note(22,213,'Retained lower module: ash cup D100 x 22, bottom Z53; local reflector D200, top Z45. Validate cup removal, frame movement, locks and stability on a complete sample. Longer frames do not imply unchanged product weight.',269,2.6,4.7)
note(22,239,'Initial charcoal-bed trial thickness remains no more than 25 mm; rated fuel load is not defined. Outdoor use on a stable heat-resistant surface only. Cool completely before stowing, latching and carrying.',269,2.6,4.7)
ln(300,35,300,259,LIGHT,.15)
tx(310,41,'FOOD GRATE / D305',3.1,'B')
v=View('ELB04_FOOD_GRATE',353,93,.25);grate(v,305,10,3.5,4.5)
v.dx((-152.5,0),(152.5,0),175,'OD 305 / P10')
tx(310,159,'CHARCOAL GRATE / D220',3.1,'B')
v=View('ELB04_CHAR_GRATE',353,204,.25);grate(v,220,12,4,5)
v.dx((-110,0),(110,0),137,'OD 220 / P12')
note(310,249,'Food wire D3.5 / ring D4.5. Charcoal wire D4 / ring D5.',88,2.5,4.5)
c.showPage()

# Sheet 5 - all factory actions and the original BOM scope retained.
sheet(5,'FACTORY ACTIONS, BOM & TOOLING','tables / not to scale')
table(20,37,[49,154,177],['FACTORY FEEDBACK','REV B RESPONSE','FACTORY TO CONFIRM'],[
 ('Shallow lid hits food','Lid rise 85; D280 x H50 space example added','Hot clearance, rim fit and deep-drawing feasibility'),
 ('Single enamel colour','Bowl and lid: same white inside and outside','Approve white sample; no black-inside/white-outside split'),
 ('Remove both handles','User confirmed: legs flip up and meet as the carry grip','Frame stack, retention, independent locks and grip coupling'),
 ('Tooling about RMB 40,000','Record factory estimate; obtain existing mould dimensions first','Scope, tax/freight, trials, alterations, lead time and reuse savings'),
 ('Bottom looks like exhaust','Label bottom ash cup as intake; lid as exhaust','Airflow, leaks, ash blockage and actual firing behaviour')],9,2.5)
table(20,100,[12,76,100,91,101],['NO.','PART / QTY','NOMINAL MATERIAL','REV B ACTION','ENGINEERING STATUS'],[
 ('01','Bowl / 1','Enamelling steel t0.8','White inside and outside','Profile retained; enamel allowance pending'),
 ('02','Raised lid / 1','Enamelling steel t0.7','Rise 85; same white both sides','Prefer a suitable existing deep-lid mould'),
 ('03','Fixed lid-top handle / 0','Removed','No fixed lid-top handle','Trial a purchased rim-clamp lid lifter'),
 ('04','Food grate / 1','304 wire D3.5 / ring D4.5','Retain D305','Confirm food-contact suitability'),
 ('05','Charcoal grate / 1','Heat-resistant wire D4 / D5','Retain D220; three feet','Validate thermal distortion and durability'),
 ('06','Dual-use U-frames / 2','304 solid rod D6','Support, stow and flip-up carry','Stops, separate locks and grip coupling pending'),
 ('07','Separate carry bail / 0','Removed','Carry function integrated in legs','Select heat-rated foot/grip sleeve material'),
 ('08','Lid exhaust / 1 set','304 sheet t0.6','Move to new lid slope','Finalize openings, rotor fit and retention'),
 ('09','Intake ash cup / 1 set','304 sheet t0.6','Retain D100 x 22','Check bayonet fit and removal path'),
 ('10','Local reflector / 1 set','304 sheet t0.5','Retain D200 and four hangers','Validate temperature and moving clearances'),
 ('11','Side pivots / 2 sets','Stainless sheet t1.5-2','Coaxial short pins at Z112','Detail backing, welds and locks'),
 ('12','Transport clips / 2','Stainless spring strip','Cold transport only','Validate retention force and durability')],7.6,2.45)
tx(20,212,'EXISTING-MOULD CHECK INPUTS',3.2,'B')
note(20,222,'Factory to return: bowl/lid mould diameters, inner sections, lid depth, rolled-rim fit, usable sheet gauges, enamel sample, original pivot/hole positions, and trial/alteration costs. Preserve food clearance before deciding on mould reuse or a new lid tool. Current geometry does not imply an available matching mould.',380,2.6,4.8)
note(20,245,'Status: factory-feedback revision for nominal-geometry review. Blender is mesh/curve visualization; DXF contains editable 2D entities. Complete mechanical CAD, tolerances, thermal and load validation before tooling release.',380,2.6,4.8)
c.showPage();c.save()

# Same CAD export route and geometric data as the Chinese Rev B edition.
doc=ezdxf.new('R2010');doc.units=4;doc.header['$INSUNITS']=4;doc.header['$MEASUREMENT']=1
for name,pat in [('DASHED',[6,4,-2]),('CENTER',[12,7,-2,1,-2])]:
    if name not in doc.linetypes:doc.linetypes.new(name,dxfattribs={'pattern':pat})
for name,(col,w) in LAYERS.items():
    attrs={'color':5 if name=='DIM' else 8 if name in ['CENTER','HIDDEN'] else 7,'lineweight':max(13,int(w*100))}
    if name in ['CENTER','HIDDEN']:attrs['linetype']='CENTER' if name=='CENTER' else 'DASHED'
    if name not in doc.layers:doc.layers.new(name,dxfattribs=attrs)
m=doc.modelspace()
for i,v in enumerate(VIEWS):
    ox=(i%3)*1000;oy=-(i//3)*700
    m.add_text(v.name+' | mm 1:1',dxfattribs={'height':10,'insert':(ox-220,oy+380),'layer':'DIM'})
    for e in v.items:
        pts=[(x+ox,y+oy) for x,y in e['pts']];at={'layer':e['layer']}
        if e['kind']=='line':m.add_line(pts[0],pts[1],dxfattribs=at)
        elif e['kind']=='poly':m.add_lwpolyline(pts,dxfattribs=at)
        elif e['kind']=='rod':m.add_lwpolyline(pts,dxfattribs={**at,'const_width':e['diam']})
        elif e['kind']=='circle':m.add_circle(pts[0],e['r'],dxfattribs=at)
        elif e['kind']=='text':
            t=m.add_text(e['value'],dxfattribs={**at,'height':e['height'],'insert':pts[0]})
            if e.get('align')=='center':
                from ezdxf.enums import TextEntityAlignment
                t.set_placement(pts[0],align=TextEntityAlignment.CENTER)
doc.saveas(ROOT.parent/'02_CAD_and_Parameters'/'EN_Light_RevB_2D.dxf')
audit=doc.audit();assert not audit.errors
pdf=pymupdf.open(PDF)
for i,page in enumerate(pdf):page.get_pixmap(matrix=pymupdf.Matrix(1.5,1.5),alpha=False).save(ROOT/f'EL-B{i+1:02d}_Drawing_EN.png')
report={'pdf_pages':len(pdf),'cad_views':len(VIEWS),'cad_units':'mm','cad_entities':len(m),'audit_errors':len(audit.errors),'audit_fixes':len(audit.fixes),'center_headroom_mm':CENTER,'headroom_at_R140_mm':EDGE,'language':'English','english_issue_date':'2026-11-03','design_revision_date':'2026-11-02'}
(ROOT/'support'/'drawing_verification.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
print(json.dumps(report))
