"""Check that a 20-tooth and a 40-tooth gear mesh: the right centre distance, no overlap, and the gear ratio."""
import math, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import cadquery as cq
from gear import spur_gear, gear_profile, MODULE, WIDTH

z1, z2 = 20, 40
a = MODULE * (z1 + z2) / 2                         # centre distance
pinion, _ = spur_gear(z=z1)
wheel, _ = spur_gear(z=z2, bore=12)
turn = 180 / z2                                    # half a tooth, so a gap of the wheel faces the pinion's tooth
wheel = wheel.rotate((0, 0, 0), (0, 0, 1), turn).translate((a, 0, 0))
overlap = pinion.intersect(wheel)
vol = overlap.val().Volume() if overlap.vals() else 0.0
print(f"centre distance {a:.1f} mm, gear ratio {z2 / z1:.1f} : 1, overlap {vol:.4f} mm³")
for turn_off in (0.0, 180 / z2 * 0.5):           # a wrong turn shows what a clash looks like
    w2, _ = spur_gear(z=z2, bore=12)
    w2 = w2.rotate((0, 0, 0), (0, 0, 1), turn_off).translate((a, 0, 0))
    o = pinion.intersect(w2)
    print(f"  wheel turned {turn_off:4.1f}°: overlap {(o.val().Volume() if o.vals() else 0.0):.2f} mm³")
cq.exporters.export(pinion.union(wheel), "gear_pair.step")

fig, ax = plt.subplots(figsize=(8, 5))
for z, dx, rot, col in ((z1, 0, 0, "#6d3fc4"), (z2, a, math.radians(turn), "#e0a000")):
    pts, d = gear_profile(MODULE, z, 20.0)
    xs = [x * math.cos(rot) - y * math.sin(rot) + dx for x, y in pts + pts[:1]]
    ys = [x * math.sin(rot) + y * math.cos(rot) for x, y in pts + pts[:1]]
    ax.fill(xs, ys, color=col, alpha=0.25); ax.plot(xs, ys, color=col, lw=0.8)
    ax.add_patch(plt.Circle((dx, 0), d["pitch"] / 2, fill=False, ls="--", color="#555", lw=0.6))
ax.set_aspect("equal"); ax.set(xlim=(-25, 105), ylim=(-45, 45), title=f"20 and 40 teeth, module {MODULE} mm, centres {a:.0f} mm apart (pitch circles dashed)")
fig.savefig("gear_pair.png", dpi=140, bbox_inches="tight")
print("saved gear_pair.png and gear_pair.step")
