"""Through-cut windows from the approved B and D relief paths (millimetres)."""
import json, math
from build import (A, Part, V, ROOT, P, W, L, H, T, F, R, e, NX, lo, hi, y0,
                   common, make_divider, checked, fuse, border_front, engrave, save,
                   line, bez, mouth)
import relief_trace as rt

C = P['openwork']
WEB = C['minimum_web']
ZLO, ZHI = C['bottom_land'], H-C['top_land']
BOX_H = ZHI-ZLO

def box(x0,x1,z0,z1):
    if x1<=x0 or z1<=z0: raise ValueError('invalid planar box')
    return Part.Face(Part.makePolygon([V(x0,z0,0),V(x1,z0,0),V(x1,z1,0),V(x0,z1,0),V(x0,z0,0)]))

def face(path, fx):
    def point(x,z): return V(*fx(x,z),0)
    start=last=point(*path[0]); edges=[]
    for item in path[1:]:
        end=point(*item[-2:])
        edges.append(line(last,end) if len(item)==2 else bez([last,point(*item[:2]),point(*item[2:4]),end]))
        last=end
    if (last-start).Length>1e-8: edges.append(line(last,start))
    return Part.Face(Part.Wire(edges))

def circle(u,z,r):
    return Part.Face(Part.Wire([Part.makeCircle(r,V(u,z,0))]))

def stroke(path,fx,w):
    xy=[fx(*v) for v in path]
    pieces=[circle(*v,w/2) for v in dict.fromkeys(xy)]
    for (x,z),(u,v) in zip(xy,xy[1:]):
        m=math.hypot(u-x,v-z)
        if m<1e-8: continue
        a,b=-(v-z)*w/(2*m),(u-x)*w/(2*m)
        pieces.append(face([(x+a,z+b),(u+a,v+b),(u-a,v-b),(x-a,z-b)],lambda x,z:(x,z)))
    return pieces[0].fuse(pieces[1:]).removeSplitter()

def front_map(x,z):
    return ((x/740-.5)*(W-2*e-2*R-5),ZLO+(1-z/480)*BOX_H)

def side_map(x,z):
    return (R+3+x/1000*(L-2*(R+3)),ZLO+(1-z/290)*BOX_H)

def front_region():
    # Inset lower than the raised front outline and its existing retrieval notch.
    x=hi-R-1.6; p=lambda u,z:V(u,z,0); a=NX/2
    v=H-C['front_notch_land']
    seg=mouth(lambda u,z:p(u,z-C['front_notch_land']))
    return Part.Face(Part.Wire([line(p(-x,ZLO),p(x,ZLO)),line(p(x,ZLO),p(x,v)),
      line(p(x,v),p(a,v)),*[q.reversed() for q in reversed(seg)],
      line(p(-a,v),p(-x,v)),line(p(-x,v),p(-x,ZLO))]))

def side_region(ys,slot):
    region=box(R+2,L-R-2,ZLO,ZHI)
    # Keep continuous wall strips behind both posts of each divider position.
    half=slot/2+1.65+WEB
    return region.cut([box(y-half,y+half,ZLO-1,H*.43+WEB) for y in ys]).removeSplitter()

def keep(candidates, region, accepted=None):
    """Clip to the structural keep-outs and reject weak/thin secondary scraps."""
    if accepted is None: accepted=[]
    for item in candidates:
        q=item.common(region).removeSplitter()
        for f in sorted(q.Faces,key=lambda a:-a.Area):
            if len(f.Wires)>1:
                f=Part.Face(f.OuterWire)  # eliminate loose islands in looped negative strokes
            bb=f.BoundBox
            if f.Area<C['minimum_window_area'] or min(bb.XLength,bb.YLength)<C['minimum_window_dimension']: continue
            assert f.isValid()
            if any(f.distToShape(g)[0]<WEB-.001 for g in accepted): continue
            accepted.append(f)
    return accepted

def b_primary(m):
    for mirror in (False,True):
        fx=lambda x,z:m(740-x if mirror else x,z)
        a,b=(face(path,fx) for path in (rt.B_HEAD,rt.B_BODY))
        yield a.fuse(b).removeSplitter()

def b_keys(m):
    # These lines are from the same relief reference, not tiled geometric filler.
    for index in (0,8,9,10,12):
        for mirror in (False,True):
            fx=lambda x,z:m(740-x if mirror else x,z)
            yield stroke(rt.B_FIELD[index],fx,C['key_width'])

def d_bird(m):
    # Preserve the sloping back, beak, tail and crooked perch in the source.
    contours=[face(path,m) for path in (rt.D_BIRD,rt.D_BEAK,rt.D_TAIL,rt.D_BRANCH)]
    q=contours[0].fuse(contours[1:]).removeSplitter()
    # Positive wing is tied to the outer wall near the tail, and toward the neck.
    # Both attachments enter the remaining wall; residual isolated islands are forbidden.
    bridge1=stroke([(480,280),(531,287),(566,285)],m,C['bird_tie_width'])
    bridge2=stroke([(367,241),(329,236),(283,228)],m,C['bird_tie_width'])
    wing=face(rt.D_WING,m).fuse([bridge1,bridge2]).removeSplitter()
    return q.cut(wing).removeSplitter(),wing

def d_wheels():
    # Exact circular arcs. Preserve the original two sun wheels and their five spokes.
    for cx,cz,rx,phase in [(363,152,125,-1.57),(799,147,122,-1.60)]:
        u,z=side_map(cx,cz)
        rad=min(side_map(cx+rx,cz)[0]-u,z-ZLO+1,ZHI-z+1)-2.4
        hub=rad*.27
        assert rad>8 and hub>3
        for j in range(5):
            a=-(phase+2*math.pi*j/5); b=a+2*math.pi/5
            wi=C['wheel_spoke_width']/2
            def p(r,t):return V(u+r*math.cos(t),z+r*math.sin(t),0)
            inner=math.asin(wi/hub); outer=math.asin(wi/rad)
            mid=(a+b)/2
            yield Part.Face(Part.Wire([
                line(p(hub,a+inner),p(rad,a+outer)),
                Part.Arc(p(rad,a+outer),p(rad,mid),p(rad,b-outer)).toShape(),
                line(p(rad,b-outer),p(hub,b-inner)),
                Part.Arc(p(hub,b-inner),p(hub,mid),p(hub,a+inner)).toShape()]))

def lift(f,wall,inner_extra=0.0):
    q=f.copy()
    if wall=='front':
        q.rotate(V(0,0,0),V(1,0,0),90)
        q.translate(V(0,-.1,0))
        return q.extrude(V(0,y0+T+.2+inner_extra,0))
    q.rotate(V(0,0,0),V(1,1,1),120)
    sign=1 if wall=='right' else -1
    q.translate(V(sign*(hi+e+.1),0,0))
    return q.extrude(V(-sign*(T+e+.2+inner_extra),0,0))

def side_rails():
    for sign in (-1,1):
        x=sign*hi
        # Low sloped labels/edge bands restore the common 100 mm envelope.
        for z in (2.4,H-5.0):
            v=[V(x-.06*sign,R,z),V(x+e*sign,R,z+e+.06),
               V(x+e*sign,R,z+2),V(x-.06*sign,R,z+2+e+.06)]
            yield Part.Face(Part.makePolygon(v+[v[0]])).extrude(V(0,L-2*R,0))

def build(key, base, div, ys, slot, mark):
    fr=front_region(); sr=side_region(ys,slot); decoration=[]
    if key=='BO':
        primary=keep(b_primary(front_map),fr)
        assert len(primary)==2
        front=keep(b_keys(front_map),fr,primary)
        packs=[lambda x,z,a=a,b=b:side_map(a+x/740*(b-a),7+z/480*276)
                  for a,b in ((9,500),(513,991))]
        side=keep([s for m in packs for s in b_primary(m)],sr)
        side=keep([s for m in packs for s in b_keys(m)],sr,side)
    else:
        bird,wing=d_bird(front_map)
        front=keep([bird],fr)
        assert len(front)>=2
        # Engrave the two wing lines only where they fall on the tied wing web.
        for path in (rt.D_FEATHER1,rt.D_FEATHER2):
            for f in face(path,front_map).common(wing).Faces:
                decoration.append(lift(f,'front'))
        side=keep(list(d_wheels()),sr)
        side=keep([stroke(rt.D_SIDE_KEYS[i],side_map,C['key_width']) for i in (0,3,4,6,7,8,10)],sr,side)
    assert len(side)>=6 and len(front)>=2
    solid=fuse(base,[border_front(),*side_rails()])
    cutters=[lift(f,'front') for f in front]+[lift(f,w) for w in ('left','right') for f in side]
    print(key, 'front windows',len(front),'side windows',len(side), flush=True)
    raw=checked(solid.cut(cutters).removeSplitter())
    # Both planar windows and actual B-rep through-wall witnesses are checked.
    # No ornamental through-hole hits the floor, rear or divider posts.
    area=sum(f.Area for f in front)+2*sum(f.Area for f in side)
    removed=solid.Volume-raw.Volume
    assert abs(removed-area*T)<max(.2,area*T*.002),(area,removed)
    assert all(raw.common(c).Volume<1e-6 for c in cutters)
    if decoration:
        shallow=Part.makeBox(W+2,y0+.22, H+2,V(-W/2-1,-.1,-1))
        marks=[g.common(shallow) for g in decoration]
        raw=checked(raw.cut(marks).removeSplitter())
    floor=Part.makeBox(W+2,L+2,F,V(-W/2-1,-1,0))
    rear=Part.makeBox(W+2,T+.1,H+2,V(-W/2-1,L-T,-1))
    for slab in (floor,rear):
        assert abs(raw.common(slab).Volume-solid.common(slab).Volume)<.003
    for y in ys:
        half=slot/2+1.65
        zone=Part.makeBox(W+2,2*half,H*.43,V(-W/2-1,y-half,0))
        assert abs(raw.common(zone).Volume-solid.common(zone).Volume)<.003
        for dz in (0,4,10,25,44):
            d=div.copy(); d.translate(V(0,y,dz))
            assert raw.common(d).Volume<1e-7,(key,y,dz)
    b=save(key+'_Pattern_Openwork_Snack_Bin.step',raw)
    assert all(abs(x-y)<.003 for x,y in zip(b['bounds'],(W,L,H)))
    d=div.copy();d.translate(V(0,round(ys[2],3),0))
    a=save(key+'_Pattern_Openwork_Assembly_REFERENCE.step',Part.makeCompound([raw,d]))
    dist=min(g.distToShape(f)[0] for fs in (front,side) for i,f in enumerate(fs) for g in fs[:i])
    return b,a,dict(front_openings=len(front),openings_per_side=len(side),
        planar_open_area_mm2=round(area,2),removed_mm3=round(removed,3),
        min_window_to_window_web_mm=round(dist,3),floor_closed=True,rear_signature=mark,
        tested_divider_insert_poses=25,divider_overlap_mm3=0)

def main():
    base,div,ys,slot,_=make_divider(common())
    base,mark=engrave(base,L,T)
    p=ROOT/'QA'/'geometry.json'; audit=json.loads(p.read_text())
    for k in ('L','Lset','lattice'):audit.pop(k,None)
    audit['rear_signature'].pop('L',None)
    audit['openwork']={}
    for key in ('BO','DO'):
        audit[key],audit[key+'set'],audit['openwork'][key]=build(key,base,div,ys,slot,mark)
        audit['rear_signature'][key]=mark
        print(key,audit['openwork'][key],flush=True)
    p.write_text(json.dumps(audit,ensure_ascii=False,indent=2)+'\n')
if __name__=='__main__': main()
