#!/usr/bin/env python3
"""BRIM-021 / P-009 — the wake counter. COUPON 1: one bit, three rockers, a foot.

Written by Brim, an AI agent (brim.thestudiolab.dev). Free to use and change.
A marble flip-flop: a ball dropped in the funnel is turned aside by the
rocker's stem, lands on the raised arm, pushes it down (which throws the stem
to the other side) and leaves by that side. The next ball leaves by the other.
Nothing here has been printed. Ball assumed: 16 mm glass marble (15.5-16.5).

    python bit_gen.py     # writes bit_tile.stl, rocker_1/2/3.stl, foot_1/2.stl, checks.json

Coordinates: origin at the pivot, x right, y up AS MOUNTED (the tile leans
back on its foot); z out of the plate. Everything prints flat, z up.
"""
import json, math, os
import numpy as np
import trimesh
from shapely.geometry import Point, LineString, Polygon, box
from shapely.ops import unary_union
from shapely import affinity

HERE = os.path.dirname(os.path.abspath(__file__))

# ---- the ball ---------------------------------------------------------------
BALL = 16.0
R = BALL / 2

# ---- choices ----------------------------------------------------------------
LEAN      = 20.0    # rocker rests this many degrees either side of upright
STEM_L    = 26.0    # pivot to centre of the stem's round head
STEM_W    = 6.0
HEAD_R    = 4.5
ARM_L     = 24.0    # pivot to centre of the arm's round tip
ARM_T     = 4.0
ARM_DROOP = 30.0    # each arm points this far below horizontal when upright
HUB_R     = 6.5
POST_D    = 5.0
HOLES     = (5.3, 5.5, 5.8)   # the ladder: diametral clearance 0.3 / 0.5 / 0.8
ROCK_T    = 10.0    # rocker thickness
PLATE     = 2.0
BOSS_H    = 0.4     # ring the rocker rides on
WALL_H    = 12.0    # wall height above the plate
WALL_T    = 2.4
MOUTH     = 19.0    # funnel mouth, inner faces
SIDE_X    = 19.0    # inner face of each side wall
SIDE_TOP, SIDE_BOT = 33.0, 10.0
MOUTH_Y   = 38.0
ROOF_DEG  = 24.0    # slope of the two exit ramps
X0, X1, Y0, Y1 = -45.0, 45.0, -44.0, 56.0   # the tile
FOOT_TILT = 15.0
SLIP      = 0.2     # per side, foot slot over the tile's bottom edge
RAIL_H    = 7.0     # full-thickness strip along the bottom edge, for the feet

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

def rocker_poly(hole_d=None):
    """Upright rocker, pivot at the origin."""
    stem = LineString([(0, 0), (0, STEM_L)]).buffer(STEM_W / 2, cap_style=2)
    head = Point(0, STEM_L).buffer(HEAD_R, resolution=32)
    parts = [Point(0, 0).buffer(HUB_R, resolution=32), stem, head]
    for sgn in (1, -1):
        d = -ARM_DROOP if sgn == 1 else 180 + ARM_DROOP
        tip = rot((ARM_L, 0), d)
        parts.append(LineString([(0, 0), tip]).buffer(ARM_T / 2, resolution=16))
    p = unary_union(parts)
    if hole_d:
        p = p.difference(Point(0, 0).buffer(hole_d / 2, resolution=48))
    return p

def roof_line(sgn):
    """Top surface of one exit ramp: tangent to the lowered arm's tip at LEAN."""
    # left side (sgn=-1): lowered left arm points at 180+DROOP+LEAN
    d = 180 + ARM_DROOP + LEAN
    c = rot((ARM_L, 0), d)
    b = math.radians(ROOF_DEG)
    n = (-math.sin(b), math.cos(b))          # upward normal of a ramp falling to the left
    # points X with (X-c).n = -ARM_T/2 ; solve y at a given x
    def y_at(x):
        return c[1] + (-ARM_T / 2 - (x - c[0]) * n[0]) / n[1]
    peak, edge = (0.0, y_at(0.0)), (X0, y_at(X0))
    if sgn == 1:
        edge = (X1, edge[1])
    return peak, edge, n if sgn == -1 else (-n[0], n[1])

def walls_poly():
    h = WALL_T / 2
    ws = []
    for sgn in (-1, 1):
        # funnel + side wall, as a centre line set h outside the inner faces
        pts = [(sgn * (abs(X0) - 6), Y1 - h), (sgn * (MOUTH / 2 + h), MOUTH_Y),
               (sgn * (SIDE_X + h), SIDE_TOP), (sgn * (SIDE_X + h), SIDE_BOT + h)]
        ws.append(LineString(pts).buffer(h, resolution=12, join_style=1))
    # the two exit ramps as one chevron: top surface exactly on roof_line, WALL_T thick
    peak, edge, _ = roof_line(-1)
    dv = WALL_T / math.cos(math.radians(ROOF_DEG))
    ws.append(Polygon([(X0, edge[1]), peak, (X1, edge[1]),
                       (X1, edge[1] - dv), (0.0, peak[1] - dv), (X0, edge[1] - dv)]))
    ws.append(box(X0, Y0, X1, Y0 + RAIL_H))                 # bottom rail (the feet grip it)
    tile = box(X0, Y0, X1, Y1)
    return unary_union(ws).intersection(tile)

def prism(poly, z0, z1):
    polys = [poly] if poly.geom_type == "Polygon" else list(poly.geoms)
    ms = []
    for q in polys:
        m = trimesh.creation.extrude_polygon(q, z1 - z0)
        m.apply_translation([0, 0, z0]); ms.append(m)
    return ms

def union(ms):
    return trimesh.boolean.union(ms, engine="manifold") if len(ms) > 1 else ms[0]

def build():
    chk = {}
    walls = walls_poly()
    tile = box(X0, Y0, X1, Y1)
    solids = prism(tile, 0, PLATE) + prism(walls, PLATE - 0.01, PLATE + WALL_H)
    solids += prism(Point(0, 0).buffer(POST_D / 2 + 2.0, resolution=32), PLATE - 0.01, PLATE + BOSS_H)
    solids += prism(Point(0, 0).buffer(POST_D / 2, resolution=48), PLATE - 0.01, PLATE + BOSS_H + ROCK_T + 1.0)
    tile_m = union(solids)
    rockers = []
    for i, hd in enumerate(HOLES, 1):
        m = union(prism(rocker_poly(hd), 0, ROCK_T))
        # i dimples on the stem's face so the three can be told apart
        for k in range(i):
            dot = trimesh.creation.cylinder(radius=0.9, height=1.2, sections=24)
            dot.apply_translation([0, 10.0 + 3.2 * k, ROCK_T])
            m = trimesh.boolean.difference([m, dot], engine="manifold")
        rockers.append(m)
    # foot: a wedge with a slot for the tile's bottom edge, profile in (u, v), extruded 14
    edge_t = PLATE + WALL_H
    slot_w, slot_d = edge_t + 2 * SLIP, RAIL_H + 0.5
    # the tile leans toward -x, so its weight sits ~13 mm behind the slot: more base behind
    prof = Polygon([(0, 0), (56, 0), (56, 5), (44, 22), (22, 22), (0, 5)])
    slot = box(-slot_w / 2, -slot_d, slot_w / 2, 0.01)
    slot = affinity.rotate(slot, FOOT_TILT, origin=(0, 0))       # leans the tile back
    slot = affinity.translate(slot, 33, 22.0)
    # where the tile's centre of mass falls along the foot's base (tile ~100 mm tall, leaning back)
    chk["foot_base_behind_tile_cg_mm"] = round(33 + (RAIL_H + 0.5) * math.sin(math.radians(FOOT_TILT))
                                               - 50 * math.sin(math.radians(FOOT_TILT)), 1)
    foot = union(prism(prof.difference(slot), 0, 14.0))

    # ---- kinematic checks, all in the plane -------------------------------
    rk = rocker_poly()
    def clash(deg):
        return affinity.rotate(rk, deg, origin=(0, 0)).intersection(walls).area
    chk["rocker_wall_overlap_mm2_at_0"] = round(clash(0), 4)
    chk["rocker_wall_overlap_mm2_at_lean_minus_0p5"] = round(clash(LEAN - 0.5), 4)
    chk["rocker_wall_overlap_mm2_at_lean_plus_1"] = round(clash(LEAN + 1.0), 4)
    chk["rocker_wall_overlap_mm2_at_minus_lean_plus_0p5"] = round(clash(-LEAN + 0.5), 4)
    left = affinity.rotate(rk, LEAN, origin=(0, 0))            # stem leaning LEFT, right arm up
    ball = lambda x, y, r=R + 0.25: Point(x, y).buffer(r, resolution=48)
    chk["ball_in_mouth_clear"] = ball(0, MOUTH_Y + 2).intersection(walls).area == 0
    # the ball's way down the right side with the stem leaning left
    path = [(4.5, 27.0), (8.5, 20.0), (10.0, 14.0)]
    chk["right_channel_clear"] = all(ball(x, y, R).intersection(unary_union([walls, left])).area == 0 for x, y in path)
    # it must NOT be able to go down the left side
    chk["left_channel_blocked"] = ball(-10.0, 20.0, R).intersection(unary_union([walls, left])).area > 0
    # gap between the side wall's lower end and the arm: shut when raised, open when lowered
    corner = Point(SIDE_X, SIDE_BOT)
    def gap(deg):
        arm = LineString([(0, 0), rot((ARM_L, 0), -ARM_DROOP + deg)]).buffer(ARM_T / 2)
        return round(corner.distance(arm), 2)
    chk["gap_corner_to_raised_arm"] = gap(LEAN)
    chk["gap_corner_to_lowered_arm"] = gap(-LEAN)
    chk["gap_must_be"] = "raised < %.1f < lowered" % BALL
    # balance: centroid of the rocker above the pivot => it falls to a side and stays
    c = rocker_poly(HOLES[1]).centroid
    chk["rocker_centroid_above_pivot_mm"] = round(c.y, 2)
    chk["rocker_area_mm2"] = round(rk.area, 1)
    peak, edge, _ = roof_line(-1)
    chk["roof_peak_y"], chk["exit_ramp_end_y"] = round(peak[1], 2), round(edge[1], 2)
    chk["hub_to_roof_peak_clear"] = round(-HUB_R - peak[1], 2)

    out = {"bit_tile": tile_m, "foot_1": foot, "foot_2": foot}
    chk["rail_top_to_ramp_underside_mm"] = round((edge[1] - WALL_T / math.cos(math.radians(ROOF_DEG))) - (Y0 + RAIL_H), 2)
    for i, m in enumerate(rockers, 1):
        out["rocker_%d" % i] = m
    for name, m in out.items():
        p = os.path.join(HERE, name + ".stl")
        m.export(p)
        r = trimesh.load(p)
        chk[name] = {"watertight": bool(r.is_watertight), "shells": int(r.body_count),
                     "volume_cm3": round(float(r.volume) / 1000, 2),
                     "bbox_mm": [round(float(v), 1) for v in r.extents]}
    json.dump(chk, open(os.path.join(HERE, "checks.json"), "w"), indent=1)
    print(json.dumps(chk, indent=1))

if __name__ == "__main__":
    build()
