"""Modify only the plate from the issued BRep parts; regenerate via editable dimensions."""
import argparse,json,hashlib,sys
from pathlib import Path
import FreeCAD

import Part as P
from scale_parking import apply,restore_legacy_rim,cyl
from step_units import ensure_mm
here=Path(__file__).resolve().parent
a=argparse.ArgumentParser()
a.add_argument('brand',choices=['Chanel','LV'])
a.add_argument('out',type=Path)
a.add_argument('--params',type=Path,default=here/'scale_parking.json')
a.add_argument('--root',type=Path)
p=a.parse_args()
root=p.root or here.parents[1]
bdir=root/p.brand
if not bdir.exists(): bdir=root/('filament-spool-'+p.brand.lower())
sdir=bdir/('Source/chanel_reinforced_connected_fix' if p.brand=='Chanel' else 'Source/StaggeredThickWall/lv_staggered_source')
oldpath=bdir/('Models/ChanelLight/CHANEL_REINFORCED_CONNECTED_SELF_SUPPORT_A' if p.brand=='Chanel' else 'Models/StaggeredThickWall/LV_OPEN_ARCH_A')
p.out.mkdir(parents=True,exist_ok=True)
q=json.loads((sdir/'light_parameters.json').read_text())
f=json.loads((here/'parameters.json').read_text())['flange']
cfg=json.loads(p.params.read_text())
assert cfg['flange_height']==f['rim_height']
report={'parameters':cfg,'parts':{}}
for hand in ['wide','narrow']:
    print(p.brand,hand,'building',flush=True)
    source=Path(str(oldpath)+f'_{hand}.step')
    old=P.read(str(source)); assert old.isValid() and len(old.Solids)==1
    from FreeCAD import Vector
    o=old.BoundBox
    origin=Vector((o.XMin+o.XMax)/2,(o.YMin+o.YMax)/2,0)
    centered=old.copy()
    centered.translate(-origin)
    base=restore_legacy_rim(centered,hand,f,q['light_flange'],q['parking_slots'])
    s,marks=apply(base,cfg)
    s.translate(origin)
    dest=p.out/f'{p.brand}_Scale_QuarterParking_{hand}.step'
    s.exportStep(str(dest))
    ensure_mm(dest,s)
    v=P.read(str(dest))
    assert v.isValid() and len(v.Solids)==1 and abs(v.Volume-s.Volume)<max(.01,s.Volume*1e-6),(v.isValid(),len(v.Solids),s.Volume,v.Volume)
    b=v.BoundBox; o=old.BoundBox
    for axis in ['XMin','XMax','YMin','YMax','ZMin','ZMax']:
        assert abs(getattr(b,axis)-getattr(o,axis))<0.015,(axis,getattr(b,axis),getattr(o,axis))
    h=cfg['flange_height']
    masks={'hub_bore_and_upper_interface':cyl(43.7,70).fuse(cyl(50,65,0,0,h+.01)),
           'rolling_surface':cyl(100.05,h+.2,0,0,-.1).cut(cyl(99.4,h+.4,0,0,-.2))}
    changes={}
    for zone,mask in masks.items():
        mask.translate(origin)
        x,y=[piece.common(mask).removeSplitter() for piece in (v,old)]
        diff=x.cut(y).Volume+y.cut(x).Volume
        assert diff<.05,(p.brand,hand,zone,diff)
        changes[zone]=round(diff,7)
    report['parts'][hand]=dict(file=dest.name,baseline=source.name,solids=len(v.Solids),bounds_mm=[round(x,5) for x in [b.XLength,b.YLength,b.ZLength]],volume_mm3=round(v.Volume,3),protected_zone_difference_mm3=changes,sha256=hashlib.sha256(dest.read_bytes()).hexdigest())
    print(p.brand,hand,report['parts'][hand],flush=True)
report['tick_radii_mm']=marks
(p.out/f'{p.brand}_CAD_Check.json').write_text(json.dumps(report,indent=2)+'\n')
