"""Parametric telescoping playing-card box. Writes card_box_base.stl and card_box_lid.stl.

Cards stand upright in the base. The upper part of the base is a thinner "neck";
the lid slides down over it so the closed box is flush on the outside.
All dimensions in mm. Mirror of card_box.scad.
"""
from manifold3d import CrossSection, JoinType, Manifold
import numpy as np

# --- cards ---
card_w, card_h = 63.0, 88.0      # standard poker size (bridge: 57 x 89)
deck_t = 17.0                    # ~54 unsleeved cards; measure yours (sleeved ~ 30)
fit = 1.5                        # total slack around the cards in width/depth
head = 1.5                       # slack above the cards

# --- box ---
wall = 2.4          # full outer wall thickness (6 perimeters at 0.4 nozzle)
neck_wall = 1.2     # base wall above the split, where the lid overlaps
clear = 0.2         # per-side clearance between neck and lid (raise to 0.25-0.3 if tight)
floor_t = 1.6       # base floor and lid top
split = 50.0        # height of the full-thickness part of the base, above floor
r = 3.0             # outer corner radius
notch_w, notch_d = 22.0, 18.0    # finger notch in the wide faces of the neck

in_w, in_d, in_h = card_w + fit, deck_t + fit, card_h + head
out_w, out_d = in_w + 2 * wall, in_d + 2 * wall


def rrect(w, d, rad, h, z=0.0):
    rad = max(rad, 0.01)
    cs = CrossSection.square([w - 2 * rad, d - 2 * rad], center=True).offset(
        rad, JoinType.Round, circular_segments=48)
    return Manifold.extrude(cs, h).translate([0, 0, z])


def base():
    neck_w, neck_d = in_w + 2 * neck_wall, in_d + 2 * neck_wall
    top = floor_t + in_h
    body = rrect(out_w, out_d, r, floor_t + split)
    neck = rrect(neck_w, neck_d, r - (wall - neck_wall), top - (floor_t + split), floor_t + split)
    cavity = rrect(in_w, in_d, r - wall, in_h + 1, floor_t)
    # U-shaped finger notch through both wide faces
    nr = notch_w / 2
    notch = (Manifold.cylinder(out_d + 2, nr, nr, 64).rotate([90, 0, 0]).translate([0, out_d / 2 + 1, top - notch_d + nr])
             + Manifold.cube([notch_w, out_d + 2, notch_d], center=True).translate([0, 0, top - notch_d / 2 + nr]))
    return body + neck - cavity - notch


def lid():
    neck_w, neck_d = in_w + 2 * neck_wall, in_d + 2 * neck_wall
    lid_in_w, lid_in_d = neck_w + 2 * clear, neck_d + 2 * clear
    depth = in_h - split + 0.3           # small gap so the lid seats on the shoulder, not the neck top
    shell = rrect(out_w, out_d, r, depth + floor_t)
    hollow = rrect(lid_in_w, lid_in_d, r - (wall - neck_wall) + clear, depth + 1, floor_t)
    return shell - hollow                # printed as-is: closed top on the bed


def write_stl(m, path):
    mesh = m.to_mesh()
    v = np.asarray(mesh.vert_properties)[:, :3]
    tris = np.asarray(mesh.tri_verts)
    with open(path, "w") as f:
        f.write("solid card_box\n")
        for a, b, c in tris:
            n = np.cross(v[b] - v[a], v[c] - v[a])
            n = n / (np.linalg.norm(n) or 1)
            f.write(f" facet normal {n[0]:.6f} {n[1]:.6f} {n[2]:.6f}\n  outer loop\n")
            for p in (v[a], v[b], v[c]):
                f.write(f"   vertex {p[0]:.4f} {p[1]:.4f} {p[2]:.4f}\n")
            f.write("  endloop\n endfacet\n")
        f.write("endsolid card_box\n")


if __name__ == "__main__":
    for name, part in (("base", base()), ("lid", lid())):
        lo, hi = np.array(part.bounding_box()[:3]), np.array(part.bounding_box()[3:])
        print(f"{name}: {hi - lo} mm, {part.volume() / 1000:.1f} cm3, genus {part.genus()}")
        write_stl(part, f"card_box_{name}.stl")
    print(f"closed box: {out_w:.1f} x {out_d:.1f} x {floor_t * 2 + in_h + 0.3:.1f} mm")
