"""
Bay access cover - one piece: FOOT (on the deck, 2 screws down) + REAR WALL
+ SLOPE, top edge dropping into the groove in the slot-wall rail (my
image 20). Notch at the right end of the slope for the wire tube (image 21).
Drops in vertically. Built in the insert frame.  Run: python bay_cover.py
"""
from pathlib import Path
from build123d import *
import params as P
import insert as B

OUT = Path(__file__).resolve().parent.parent / "out"; OUT.mkdir(exist_ok=True)
T = P.COVER_T
HALF_X = P.TRAY_HX - P.WALL - P.COVER_SIDE_CLR         # between the END WALLS
FOOT_Z0 = P.FLOOR_TOTAL_H                              # sits on the deck
HOOK_Y = P.STEP_Y1 - P.COVER_CLR                       # 7.1 rear face of top edge
pts = [(B.COVER_OUT_Y + P.FOOT_LEN, FOOT_Z0), (B.COVER_OUT_Y + P.FOOT_LEN, FOOT_Z0 + T),
       (B.COVER_OUT_Y, FOOT_Z0 + T), B.BEND, B.PEAK, (B.PEAK[0], P.HOOK_BOT_Z),
       (HOOK_Y, P.HOOK_BOT_Z)]
zi = B.slope_z(HOOK_Y, T)
if zi > P.HOOK_BOT_Z + 0.05: pts.append((HOOK_Y, zi))
pts += [(B.COVER_IN_Y, B.slope_z(B.COVER_IN_Y, T)), (B.COVER_IN_Y, FOOT_Z0)]
PROFILE = pts

def build_cover():
    with BuildPart() as cp:
        with BuildSketch(Plane.YZ.offset(-HALF_X)) as sk: Polygon(*PROFILE, align=None)
        extrude(sk.sketch, amount=2 * HALF_X)
        for sx in (-P.FOOT_SCREW_X, P.FOOT_SCREW_X):                 # foot screws
            with BuildSketch(Plane.XY.offset(FOOT_Z0 - 0.1)) as sk:
                with Locations((sx, B.COVER_OUT_Y + P.FOOT_SCREW_Y_OFF)): Circle(P.SCREW_CLR_D / 2)
            extrude(sk.sketch, amount=T + 0.2, mode=Mode.SUBTRACT)
        # notch for the wire tube at the right end of the slope
        nx0, nx1 = B.TUBE_X0 - 0.5, HALF_X + 1
        with BuildSketch(Plane.XY.offset(-1)) as sk:
            with Locations(((nx0 + nx1) / 2, (P.TUBE_Y0 + B.TUBE_Y1) / 2)):
                Rectangle(nx1 - nx0, P.TUBE_OUT + 1.0)
        extrude(sk.sketch, amount=P.BOX_H + 2, mode=Mode.SUBTRACT)
    return cp.part

def check_notch():
    """The wire-tube notch must stay over the tube on the INSERT even when the
    cover's width changes. The notch's outer end is keyed to the cover edge and
    its inner end to the tube, so a width change moves one and not the other -
    assert the overlap rather than trusting that."""
    n0, n1 = B.TUBE_X0 - 0.5, HALF_X + 1
    errs = []
    if n0 > B.TUBE_X0:
        errs.append(f"notch starts at {n0:.1f}, tube starts at {B.TUBE_X0:.1f}")
    if n1 < B.TUBE_X1:
        errs.append(f"notch ends at {n1:.1f}, tube ends at {B.TUBE_X1:.1f}")
    if n1 > HALF_X + 2:
        errs.append(f"notch overruns the cover edge ({n1:.1f} vs {HALF_X:.1f})")
    return errs


if __name__ == "__main__":
    part = build_cover(); bb = part.bounding_box()
    for e in check_notch():
        print("  NOTCH FAIL:", e)
    print(f"Cover X {bb.min.X:.1f}..{bb.max.X:.1f}  Y {bb.min.Y:.1f}..{bb.max.Y:.1f}  Z {bb.min.Z:.1f}..{bb.max.Z:.1f}   vol {part.volume/1000:.1f} cm^3")
    print(f"top edge Y {B.PEAK[0]:.1f}..{HOOK_Y:.1f}, bottom Z {P.HOOK_BOT_Z} (step Y {P.LIP_Y1}..{P.STEP_Y1} at Z {P.STEP_Z})")
    print(f"notch X {B.TUBE_X0-0.5:.1f}..{HALF_X+1:.1f} over tube "
          f"{B.TUBE_X0:.1f}..{B.TUBE_X1:.1f}  "
          f"{'OK' if not check_notch() else 'CHECK'}")
    export_stl(part, str(OUT / "bay_cover.stl")); export_step(part, str(OUT / "bay_cover.step"))
    print("wrote out/bay_cover.stl, out/bay_cover.step")
