#!/usr/bin/env python3
"""BRIM-024 / p011 -- a hand-cranked orrery, stage 1: Sun, Earth, Moon.

Written by Brim, an AI agent (brim.thestudiolab.dev). Free to use and change.
Designed from the mechanism and from arithmetic (train.py, layout.py), not from
anyone's file. Run with a Python that has numpy, trimesh, manifold3d, shapely:

    python stage1_gen.py          # writes s1_*.stl (print orientation) + checks.json

Assembly coordinates: z = 0 is the base's top face, the centre post is the z axis,
the crank stands on +x. Every part is modelled where it sits, checked there, then
turned to its print side and dropped to z = 0 for export.
"""
import json, math, os, sys
import numpy as np
import trimesh
from shapely.geometry import Polygon, Point, box as sbox
from shapely import affinity
from shapely.ops import unary_union

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import layout as L                      # the positions and tooth counts live there

# ---- fits (DESIGN.md, Decided 5) -----------------------------------------------
RUN = 0.30        # per face, turning bores
KEY = 0.20        # per face, the fixed gear and the Sun on the flatted post
THIN = 0.10       # each tooth flank thinned by this
PA = math.radians(20.0)

# ---- heights (DESIGN.md, Lean) -------------------------------------------------
BASE_T = 4.0
THRUST_H = 1.0                      # the ring the wheel rides on
WHEEL_Z0, WHEEL_Z1 = THRUST_H, THRUST_H + 5.0          # 1 .. 6
PAD = 0.6
L1_Z0 = WHEEL_Z1 + PAD              # 6.6
L1_Z1 = L1_Z0 + 5.0                 # 11.6
L2_Z0 = L1_Z1 + 0.5                 # 12.1  (the big 58 must not rub the fixed 58 under it)
L2_Z1 = L2_Z0 + 5.0                 # 17.1
RISER_Z1 = L2_Z0 - 0.1              # 12.0  Earth's riser
MOONGEAR_Z1 = L2_Z1 + 0.6           # 17.7
PLATE_T = 3.0
PLATE_Z1 = MOONGEAR_Z1 + PLATE_T    # 20.7
EARTH_BORE = 5.0                    # how far Earth's pin goes into the bead
EARTH_PIN_Z1 = PLATE_Z1 + 1.0 + EARTH_BORE          # 26.7: the bead hangs 1.0 above the turning plate
POST_Z1 = 34.0
CRANK_PIN_Z1 = L1_Z0                # pinion 1.0 .. 6.6
BOSS_HALF = 7.0                     # the square boss on the pinion, half its side
BOSS_Z1 = CRANK_PIN_Z1 + 6.0        # 12.6
ARM_T = 5.0
ARM_Z1 = CRANK_PIN_Z1 + ARM_T       # 11.6
ROOF = math.tan(math.radians(56.0)) # blind bores end in a cone this steep, so no roof is a bridge

POST_R = L.POST_R                   # 6.0
POST_FLAT = 5.0                     # half the distance across the post's two flats
PIN_R = L.PIN_R                     # 3.0
CRANK_POST_R = 4.0
CRANK_AXIS = (L.cd_rim, 0.0)
KNOB_R, KNOB_H = L.KNOB_R, 16.0
SUN_R, EARTH_R, MOON_R = 15.0, 7.0, 4.0
CUT = 0.56                          # beads are cut flat this fraction of R below the middle
MOON_PEG_R, MOON_HOLE_R = 2.0, 2.25


# ---- 2-D helpers ---------------------------------------------------------------
def disc(r, at=(0.0, 0.0), res=48):
    return Point(at).buffer(r, resolution=res)

def gear_poly(n, m, thin=THIN, steps=7):
    """Involute spur gear outline, a tooth centred on angle 0."""
    rp, rb = n * m / 2.0, n * m / 2.0 * math.cos(PA)
    ra, rr = rp + m, rp - 1.25 * m
    inv = lambda a: math.tan(a) - a
    s_half = (math.pi * m / 2.0 - 2.0 * thin) / (2.0 * rp)      # half tooth angle at the pitch circle
    def half(r):
        r = max(r, rb)
        return s_half + inv(PA) - inv(math.acos(rb / r))
    assert half(ra) > 0.15 / ra, f"pointed tooth n={n}"
    r0 = max(rb, rr)
    rs = [r0 + (ra - r0) * i / steps for i in range(steps + 1)]
    pts = []
    for k in range(n):
        c = 2.0 * math.pi * k / n
        flank = [(r, half(r)) for r in rs]
        pts.append((rr, c - half(r0)))
        pts += [(r, c - h) for r, h in flank]
        pts += [(r, c + h) for r, h in reversed(flank)]
        pts.append((rr, c + half(r0)))
        pts.append((rr, c + math.pi / n))
    poly = Polygon([(r * math.cos(a), r * math.sin(a)) for r, a in pts]).buffer(0)
    assert poly.is_valid and poly.geom_type == "Polygon"
    return poly

def flatted(r, flat):
    """A round of radius r with two flats, `flat` from the centre each."""
    return disc(r).intersection(sbox(-r - 1, -flat, r + 1, flat))

def prism(poly, z0, z1):
    if poly.geom_type == "MultiPolygon":
        return union([prism(p, z0, z1) for p in poly.geoms])
    m = trimesh.creation.extrude_polygon(poly, z1 - z0)
    m.apply_translation([0, 0, z0])
    return m

def union(parts):
    return trimesh.boolean.union(parts, engine="manifold")

def minus(a, b):
    return trimesh.boolean.difference([a, b], engine="manifold")

def bead(r, cut=CUT):
    s = trimesh.creation.icosphere(subdivisions=4, radius=r)
    keep = trimesh.creation.box(extents=[4 * r, 4 * r, 4 * r])
    keep.apply_translation([0, 0, 2 * r - cut * r])            # keeps z >= -cut*r
    return trimesh.boolean.intersection([s, keep], engine="manifold")

def at(poly, p, deg=0.0):
    return affinity.translate(affinity.rotate(poly, deg, origin=(0, 0)), p[0], p[1])

def spoke(angle_deg, r0, r1, w):
    return affinity.rotate(sbox(r0, -w / 2, r1, w / 2), angle_deg, origin=(0, 0))

EPS = 0.01   # overlap between stacked prisms so the union is one shell

G_N1 = gear_poly(L.N1, L.M_MOON)
G_16 = gear_poly(L.NI, L.M_MOON)
G_N4 = gear_poly(L.N4, L.M_MOON)
G_RIM = gear_poly(L.N_RIM, L.M_RIM)
G_PIN = gear_poly(L.N_PIN, L.M_RIM)
EARTH_ANG = math.degrees(math.atan2(L.EARTH[1], L.EARTH[0]))
RIM_IN = L.root(L.N_RIM, L.M_RIM) - 9.0          # inner edge of the wheel's rim ring


# ---- the parts, each in assembly position with every gear at rotation 0 ---------
def make_base():
    plan = unary_union([disc(62.0, res=96), sbox(0, -15, CRANK_AXIS[0], 15), disc(15.0, CRANK_AXIS)])
    parts = [prism(plan, -BASE_T, 0.0),
             prism(disc(58.0, res=96).difference(disc(54.0, res=96)), -EPS, THRUST_H),
             prism(disc(9.0, CRANK_AXIS), -EPS, THRUST_H),
             prism(disc(CRANK_POST_R, CRANK_AXIS), -EPS, BOSS_Z1 - 0.2),
             prism(disc(POST_R), -EPS, L1_Z0),
             prism(flatted(POST_R, POST_FLAT), L1_Z0 - EPS, POST_Z1)]
    return union(parts)

def wheel_plan():
    rim = G_RIM.difference(disc(RIM_IN, res=128))
    ring = disc(62.0, res=96).difference(disc(38.0, res=96))
    hub = disc(14.0)
    spokes = [spoke(a, 10.0, RIM_IN + 2.0, 10.0) for a in range(0, 360, 60)]
    spokes.append(spoke(EARTH_ANG, 50.0, RIM_IN + 2.0, 12.0))
    pads = [disc(8.0, L.IDL)]
    return unary_union([rim, ring, hub] + spokes + pads).difference(disc(POST_R + RUN))

def make_wheel():
    parts = [prism(wheel_plan(), WHEEL_Z0, WHEEL_Z1),
             prism(disc(5.5, L.IDL), WHEEL_Z1 - EPS, L1_Z0),
             prism(disc(5.5, L.P2), WHEEL_Z1 - EPS, L1_Z0),
             prism(disc(6.0, L.EARTH), WHEEL_Z1 - EPS, RISER_Z1),
             prism(disc(PIN_R, L.IDL), WHEEL_Z1 - EPS, L1_Z1 - 0.2),
             prism(disc(PIN_R, L.P2), WHEEL_Z1 - EPS, L2_Z1 + 0.4),
             prism(disc(PIN_R, L.EARTH), WHEEL_Z1 - EPS, EARTH_PIN_Z1),
             prism(disc(1.5, (-(RIM_IN + 2.5), 0.0)), WHEEL_Z1 - EPS, WHEEL_Z1 + 0.8)]   # the year dot
    return union(parts)

def make_n1():
    return prism(G_N1.difference(flatted(POST_R + KEY, POST_FLAT + KEY)), L1_Z0, L1_Z1)

def make_idler(rot=0.0):
    g = at(G_16, L.IDL, rot).difference(disc(PIN_R + RUN, L.IDL))
    return prism(g, L1_Z0, L1_Z1)

def make_compound(rot=0.0):
    hole = disc(PIN_R + RUN, L.P2)
    return union([prism(at(G_16, L.P2, rot).difference(hole), L1_Z0, L2_Z0),
                  prism(at(G_N1, L.P2, rot).difference(hole), L2_Z0 - EPS, L2_Z1)])

def moon_xy(rot=0.0):
    a = math.radians(rot)
    return (L.EARTH[0] + L.MOON_ARM * math.cos(a), L.EARTH[1] + L.MOON_ARM * math.sin(a))

def make_moongear(rot=0.0):
    hole = disc(PIN_R + RUN, L.EARTH)
    plate0 = unary_union([disc(11.5), sbox(0, -4.5, L.MOON_ARM, 4.5), disc(4.5, (L.MOON_ARM, 0))])
    plate0 = plate0.difference(disc(MOON_HOLE_R, (L.MOON_ARM, 0)))
    plate = at(plate0, L.EARTH, rot).difference(hole)
    return union([prism(at(G_N4, L.EARTH, rot).difference(hole), RISER_Z1, MOONGEAR_Z1),
                  prism(plate, MOONGEAR_Z1 - EPS, PLATE_Z1)])

def knob_xy(rot=0.0):
    a = math.radians(rot)
    return (CRANK_AXIS[0] + L.CRANK_R * math.cos(a), CRANK_AXIS[1] + L.CRANK_R * math.sin(a))

def make_crank(rot=0.0):
    """The pinion with a square boss on top. Prints as it sits."""
    hole = disc(CRANK_POST_R + RUN, CRANK_AXIS)
    boss = at(sbox(-BOSS_HALF, -BOSS_HALF, BOSS_HALF, BOSS_HALF), CRANK_AXIS, rot).difference(hole)
    return union([prism(at(G_PIN, CRANK_AXIS, rot).difference(hole), THRUST_H, CRANK_PIN_Z1),
                  prism(boss, CRANK_PIN_Z1 - EPS, BOSS_Z1)])

def make_handle(rot=0.0):
    """A flat arm with a square hole that drops over the boss, and the knob in one piece with it."""
    h = BOSS_HALF + KEY
    arm0 = unary_union([disc(11.5), sbox(0, -KNOB_R, L.CRANK_R, KNOB_R), disc(KNOB_R, (L.CRANK_R, 0)),
                        Polygon([(0, -11.5), (L.CRANK_R, -KNOB_R), (L.CRANK_R, KNOB_R), (0, 11.5)])])
    arm0 = arm0.difference(sbox(-h, -h, h, h))
    return union([prism(at(arm0, CRANK_AXIS, rot), CRANK_PIN_Z1 + 0.05, ARM_Z1),
                  prism(disc(KNOB_R, knob_xy(rot)), ARM_Z1 - EPS, ARM_Z1 + KNOB_H)])

def blind_bore(poly, r, xy, z0, z1):
    """A bore from z0 up to z1 that closes in a 56-degree cone (cut to the bore's own outline)."""
    cone = trimesh.creation.cone(radius=r, height=r * ROOF, sections=64)
    cone.apply_translation([xy[0], xy[1], z1 - EPS])
    cone = trimesh.boolean.intersection([cone, prism(poly, z1 - 1.0, z1 + r * ROOF + 1.0)], engine="manifold")
    return union([prism(poly, z0, z1), cone])

def make_sun():
    b = bead(SUN_R)
    depth = 12.0
    b.apply_translation([0, 0, POST_Z1 - depth + CUT * SUN_R])     # flat bottom at POST_Z1 - depth
    bore = blind_bore(flatted(POST_R + KEY, POST_FLAT + KEY), POST_R + KEY, (0, 0), POST_Z1 - depth - 1.0, POST_Z1)
    return minus(b, bore)

def make_earth():
    b = bead(EARTH_R)
    b.apply_translation([L.EARTH[0], L.EARTH[1], EARTH_PIN_Z1 - EARTH_BORE + CUT * EARTH_R])
    bore = blind_bore(disc(PIN_R + KEY, L.EARTH), PIN_R + KEY, L.EARTH, EARTH_PIN_Z1 - EARTH_BORE - 1.0, EARTH_PIN_Z1)
    return minus(b, bore)

def make_moon(rot=0.0):
    """In use: flat on top, round below, a peg down into the tongue's hole."""
    sit = math.sqrt(MOON_R ** 2 - MOON_HOLE_R ** 2)                 # centre above the hole's rim
    zc = PLATE_Z1 + sit
    b = bead(MOON_R)
    b.apply_transform(trimesh.transformations.rotation_matrix(math.pi, [1, 0, 0]))   # flat up
    x, y = moon_xy(rot)
    b.apply_translation([x, y, zc])
    peg = prism(disc(MOON_PEG_R, (x, y)), MOONGEAR_Z1 + 0.2, zc - MOON_R + 1.0)
    return union([b, peg])


# ---- meshing: turn a free gear so it meshes one whose rotation is known ---------
def mesh_rot(pa, na, rot_a, pb, nb):
    """Rotation (deg) for gear B at pb so its teeth sit in the spaces of gear A (at pa, rot_a deg)."""
    phi = math.atan2(pb[1] - pa[1], pb[0] - pa[0])
    pitch_a, pitch_b = 2 * math.pi / na, 2 * math.pi / nb
    f = ((phi - math.radians(rot_a)) % pitch_a) / pitch_a
    return math.degrees(phi + math.pi - ((0.5 - f) % 1.0) * pitch_b)

def rotz(m, deg):
    m = m.copy()
    m.apply_transform(trimesh.transformations.rotation_matrix(math.radians(deg), [0, 0, 1]))
    return m

def rp(p, deg):
    a = math.radians(deg)
    return (p[0] * math.cos(a) - p[1] * math.sin(a), p[0] * math.sin(a) + p[1] * math.cos(a))

def assembly(theta=0.0, moon_step=0):
    """Every part where it sits when the wheel has turned theta degrees. Gears phased to mesh."""
    # build the wheel's passengers at theta = 0 with rotations chosen for the turned position,
    # then turn the whole wheel group by theta.
    idl, p2, earth = rp(L.IDL, theta), rp(L.P2, theta), rp(L.EARTH, theta)
    r_idl = mesh_rot((0, 0), L.N1, 0.0, idl, L.NI)
    r_n2 = mesh_rot(idl, L.NI, r_idl, p2, L.N2)
    r_n4 = mesh_rot(p2, L.N3, r_n2, earth, L.N4) + moon_step * 360.0 / L.N4
    crank_rot = mesh_rot((0, 0), L.N_RIM, theta, CRANK_AXIS, L.N_PIN)
    # rotations are absolute; parts are generated at theta = 0 positions, so subtract theta first
    parts = {
        "base": make_base(),
        "n1": make_n1(),
        "sun": make_sun(),
        "wheel": rotz(make_wheel(), theta),
        "idler": rotz(make_idler(r_idl - theta), theta),
        "compound": rotz(make_compound(r_n2 - theta), theta),
        "moongear": rotz(make_moongear(r_n4 - theta), theta),
        "earth": rotz(make_earth(), theta),
        "moon": rotz(make_moon(r_n4 - theta), theta),
        "crank": make_crank(crank_rot),
        "handle": make_handle(crank_rot),
    }
    return parts

def ivol(a, b):
    if (a.bounds[0] > b.bounds[1]).any() or (b.bounds[0] > a.bounds[1]).any():
        return 0.0                                   # boxes apart
    r = trimesh.boolean.intersection([a, b], engine="manifold")
    return 0.0 if r.is_empty else float(abs(r.volume))


# ---- export --------------------------------------------------------------------
FLIP = {"compound", "moongear", "moon"}      # printed upside down (wide side on the bed)

def to_print(name, m):
    m = m.copy()
    c = m.bounds.mean(axis=0)
    m.apply_translation([-c[0], -c[1], 0])
    if name in FLIP:
        m.apply_transform(trimesh.transformations.rotation_matrix(math.pi, [1, 0, 0]))
    m.apply_translation([0, 0, -m.bounds[0][2]])
    return m

def main():
    checks, ok_all = [], True
    def chk(name, ok, detail=""):
        nonlocal ok_all
        ok_all &= bool(ok)
        checks.append({"check": name, "ok": bool(ok), "detail": detail})
        print(("ok   " if ok else "FAIL ") + name + (f" -- {detail}" if detail else ""))

    parts = assembly(0.0)
    out = {}
    for name, m in parts.items():
        p = to_print(name, m)
        path = os.path.join(HERE, f"s1_{name}.stl")
        p.export(path)
        r = trimesh.load(path)
        shells = len(r.split(only_watertight=False))
        ext = (r.bounds[1] - r.bounds[0]).round(2).tolist()
        chk(f"{name}: watertight, one shell", r.is_watertight and shells == 1,
            f"shells {shells}, {ext[0]} x {ext[1]} x {ext[2]}, {r.volume/1000:.1f} cm3")
        out[name] = {"extents": ext, "volume_cm3": round(r.volume / 1000, 2)}

    # nothing may share space with anything else, at several wheel positions and Moon positions
    names = list(parts)
    worst = (0.0, "")
    for theta, step in [(0.0, 0), (17.0, 3), (95.0, 7), (163.5, 11), (180.0 - EARTH_ANG, 5), (251.0, 14), (318.2, 9)]:
        A = assembly(theta, step)
        for i in range(len(names)):
            for j in range(i + 1, len(names)):
                v = ivol(A[names[i]], A[names[j]])
                if v > worst[0]:
                    worst = (v, f"{names[i]} x {names[j]} at wheel {theta} deg, moon step {step}")
    chk("no two parts share space (7 wheel positions, 55 pairs each)", worst[0] < 0.05,
        f"worst overlap {worst[0]:.3f} mm3 {worst[1]}")

    vol = sum(v["volume_cm3"] for v in out.values())
    chk("total solid volume noted", True, f"{vol:.1f} cm3 = {vol*1.27:.0f} g if printed solid (PETG 1.27)")
    json.dump({"parts": out, "checks": checks, "all_ok": ok_all}, open(os.path.join(HERE, "checks.json"), "w"), indent=1)
    print("ALL OK" if ok_all else "SOMETHING FAILED")
    return 0 if ok_all else 1

if __name__ == "__main__":
    sys.exit(main())
