"""Add the existing sprout/cube SVG and name as readable rear intaglio."""
from pathlib import Path
import hashlib,re,xml.etree.ElementTree as ET
import FreeCAD as A, Part
V=A.Vector
SVG=Path(__file__).resolve().parents[4]/'models/mark-miaozhuang-three-variants/miaozhuang-logo.svg'
FONT=Path('/System/Library/Fonts/STHeiti Medium.ttc')
NAME='苗壮'
DEPTH=.25
WIDTH=15.5
FONT_HEIGHT=8.5
OVERSHOOT=.08

def make_mark(rear):
 def logo_pt(x,z):return V(-x,rear+OVERSHOOT,z)
 advance=WIDTH/(410-27)
 cutters=[]
 for el in ET.parse(SVG).getroot():
  if not el.tag.endswith('path'):continue
  wires=[]
  for sub in re.findall(r'M\s*([^Z]+)Z',el.attrib['d']):
   nums=[float(n) for n in re.findall(r'-?\d+(?:\.\d+)?',sub)]
   pts=[logo_pt((nums[i]-218.5)*advance-9.8,18+(285-nums[i+1])*advance) for i in range(0,len(nums),2)]
   assert (pts[0]-pts[-1]).Length>1e-8
   wires.append(Part.makePolygon(pts+[pts[0]]))
  f=Part.makeFace(wires,'Part::FaceMakerBullseye');assert f.isValid()
  cutters.append(f.extrude(V(0,-DEPTH-OVERSHOOT,0)))
 # Use the same system font as the previously signed model.
 glyphs=Part.makeWireString(NAME,str(FONT.parent)+"/",FONT.name,FONT_HEIGHT,0)
 if not glyphs or any(not char for char in glyphs):raise ValueError('字体没有提供完整签名轮廓')
 faces=[Part.makeFace(char,'Part::FaceMakerBullseye') for char in glyphs]
 t=Part.makeCompound(faces);bb=t.BoundBox
 cx=(bb.XMin+bb.XMax)/2; cy=(bb.YMin+bb.YMax)/2
 k=FONT_HEIGHT/bb.YLength
 m=A.Matrix()
 m.A11=-k;m.A12=0;m.A13=0;m.A14=cx*k-9.5
 m.A21=0;m.A22=0;m.A23=1;m.A24=rear+OVERSHOOT
 m.A31=0;m.A32=k;m.A33=0;m.A34=18-cy*k
 t=t.transformGeometry(m)
 for f in t.Faces:cutters.append(f.extrude(V(0,-DEPTH-OVERSHOOT,0)))
 cut=Part.makeCompound(cutters)
 assert cut.isValid() and all(s.Volume>0 for s in cut.Solids)
 return cut

def engrave(body,rear,wall):
 cut=make_mark(rear)
 bb=cut.BoundBox
 assert wall-DEPTH>=1.10 and bb.YMin>rear-wall
 actual=body.common(cut).Volume
 expected=cut.Volume*DEPTH/(DEPTH+OVERSHOOT)
 assert abs(actual-expected)<1e-4,(actual,expected)
 q=body.cut(cut).removeSplitter()
 assert q.isValid() and len(q.Solids)==1 and abs(body.Volume-q.Volume-actual)<.01
 assert max(abs(getattr(body.BoundBox,k)-getattr(q.BoundBox,k)) for k in ('XMin','XMax','YMin','YMax','ZMin','ZMax'))<.00001
 return q,dict(name=NAME,face='+Y',depth_mm=DEPTH,remaining_wall_mm=round(wall-DEPTH,3),
   logo_width_mm=WIDTH,svg_sha256=hashlib.sha256(SVG.read_bytes()).hexdigest(),
   removed_volume_mm3=round(actual,5),signature_width_mm=round(bb.XLength,4),
   signature_height_mm=round(bb.ZLength,4))
