#!/usr/bin/env python3
"""
Project Elyasia — Bambu Lab P2S (256x256x256 mm) Binary STL Mesh Generator
Author: Iris (prism.irislumen.dev)
License: CERN-OHL-S v2

Generates watertight Binary STL (.stl) files for Mark's Stage 1 Cold Phantom &
LN2 (77K) Inductive Recovery Testbed, pre-segmented and oriented for the
Bambu Lab P2S (256 x 256 x 256 mm enclosed CoreXY build volume):

  1. P2S_Part1_Conformal_Launch_Cradle_90deg.stl  (189.7 x 189.7 x 40.8 mm, print 4x)
  2. P2S_Part2_Regenerative_Catch_Bobbin_90deg.stl (186.7 x 186.7 x 34.0 mm, print 4x)
  3. P2S_Part3_500mm_Sphere_Modular_Sector.stl     (190.6 x 164.5 x 98.2 mm, print 16x)
  4. P2S_Part4_Triaxial_Bdot_Rogowski_Mount.stl    (56.0 x 56.0 x 42.0 mm, print 4x)

Usage:
  python3 generate_p2s_stls.py
"""

import math
import struct
import os


def compute_normal(p1, p2, p3):
    ux, uy, uz = p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]
    vx, vy, vz = p3[0] - p1[0], p3[1] - p1[1], p3[2] - p1[2]
    nx = uy * vz - uz * vy
    ny = uz * vx - ux * vz
    nz = ux * vy - uy * vx
    norm = math.sqrt(nx * nx + ny * ny + nz * nz) or 1.0
    return (nx / norm, ny / norm, nz / norm)


def write_binary_stl(filename, header_text, tris):
    """Writes a standard 80-byte header + triangle count + 50-byte/tri binary STL."""
    xs = [p[0] for t in tris for p in t]
    ys = [p[1] for t in tris for p in t]
    zs = [p[2] for t in tris for p in t]
    cx = 0.5 * (min(xs) + max(xs))
    cy = 0.5 * (min(ys) + max(ys))
    min_z = min(zs)
    bbox = (max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs))

    header = header_text.encode("ascii")[:80].ljust(80, b" ")
    with open(filename, "wb") as f:
        f.write(header)
        f.write(struct.pack("<I", len(tris)))
        for p1, p2, p3 in tris:
            n = compute_normal(p1, p2, p3)
            v1 = (p1[0] - cx, p1[1] - cy, p1[2] - min_z)
            v2 = (p2[0] - cx, p2[1] - cy, p2[2] - min_z)
            v3 = (p3[0] - cx, p3[1] - cy, p3[2] - min_z)
            f.write(struct.pack("<12fH", n[0], n[1], n[2],
                                v1[0], v1[1], v1[2],
                                v2[0], v2[1], v2[2],
                                v3[0], v3[1], v3[2], 0))
    print(f"[OK] {filename}: {len(tris)} triangles | BBox: {bbox[0]:.1f} x {bbox[1]:.1f} x {bbox[2]:.1f} mm (Fits P2S 256^3 mm)")


def build_toroidal_cradle_sector(
    R_major=140.0,
    r_inner=41.5,
    r_outer=51.5,
    theta_deg=90.0,
    phi_start_deg=-165.0,
    phi_end_deg=-15.0,
    n_theta=96,
    n_phi=48,
    groove_count=20,
    groove_depth=1.4
):
    thetas = [math.radians(theta_deg * i / n_theta) for i in range(n_theta + 1)]
    phis = [math.radians(phi_start_deg + (phi_end_deg - phi_start_deg) * j / n_phi) for j in range(n_phi + 1)]

    def pt(r, th, ph, is_outer=False):
        r_eff = r
        if is_outer and groove_count > 0:
            phase = (ph - phis[0]) / (phis[-1] - phis[0]) * groove_count * 2.0 * math.pi
            r_eff = r - groove_depth * 0.5 * (1.0 - math.cos(phase))
        rho = R_major + r_eff * math.cos(ph)
        return (rho * math.cos(th), rho * math.sin(th), r_eff * math.sin(ph))

    tris = []
    def add_quad(p1, p2, p3, p4):
        tris.append((p1, p2, p3))
        tris.append((p1, p3, p4))

    for i in range(n_theta):
        th0, th1 = thetas[i], thetas[i + 1]
        for j in range(n_phi):
            ph0, ph1 = phis[j], phis[j + 1]
            add_quad(pt(r_inner, th0, ph0, False), pt(r_inner, th0, ph1, False),
                     pt(r_inner, th1, ph1, False), pt(r_inner, th1, ph0, False))
            add_quad(pt(r_outer, th0, ph0, True), pt(r_outer, th1, ph0, True),
                     pt(r_outer, th1, ph1, True), pt(r_outer, th0, ph1, True))

    for j in range(n_phi):
        ph0, ph1 = phis[j], phis[j + 1]
        th = thetas[0]
        add_quad(pt(r_inner, th, ph0, False), pt(r_outer, th, ph0, True),
                 pt(r_outer, th, ph1, True), pt(r_inner, th, ph1, False))
        th = thetas[-1]
        add_quad(pt(r_inner, th, ph0, False), pt(r_inner, th, ph1, False),
                 pt(r_outer, th, ph1, True), pt(r_outer, th, ph0, True))

    for i in range(n_theta):
        th0, th1 = thetas[i], thetas[i + 1]
        ph = phis[0]
        add_quad(pt(r_inner, th0, ph, False), pt(r_inner, th1, ph, False),
                 pt(r_outer, th1, ph, True), pt(r_outer, th0, ph, True))
        ph = phis[-1]
        add_quad(pt(r_inner, th0, ph, False), pt(r_outer, th0, ph, True),
                 pt(r_outer, th1, ph, True), pt(r_inner, th1, ph, True))

    return tris


def build_sphere_sector(
    R_inner=244.0,
    R_outer=250.0,
    az_deg=45.0,
    el_start_deg=5.0,
    el_end_deg=48.0,
    n_az=48,
    n_el=36
):
    azs = [math.radians(-az_deg / 2.0 + az_deg * i / n_az) for i in range(n_az + 1)]
    els = [math.radians(el_start_deg + (el_end_deg - el_start_deg) * j / n_el) for j in range(n_el + 1)]

    def pt(r, az, el, is_outer=False):
        r_eff = r
        # Add 0.4mm copper flux-conserver band recess in middle of tile
        if not is_outer and 0.25 * el_start_deg + 0.75 * el_end_deg > math.degrees(el) > 0.75 * el_start_deg + 0.25 * el_end_deg:
            if abs(math.degrees(az)) > 2.5:  # Leave 5-deg insulating poloidal gap ridge!
                r_eff = r + 0.45
        return (r_eff * math.cos(el) * math.sin(az),
                r_eff * math.sin(el),
                r_eff * math.cos(el) * math.cos(az))

    tris = []
    def add_quad(p1, p2, p3, p4):
        tris.append((p1, p2, p3))
        tris.append((p1, p3, p4))

    for i in range(n_az):
        a0, a1 = azs[i], azs[i + 1]
        for j in range(n_el):
            e0, e1 = els[j], els[j + 1]
            add_quad(pt(R_inner, a0, e0), pt(R_inner, a0, e1), pt(R_inner, a1, e1), pt(R_inner, a1, e0))
            add_quad(pt(R_outer, a0, e0, True), pt(R_outer, a1, e0, True), pt(R_outer, a1, e1, True), pt(R_outer, a0, e1, True))

    for j in range(n_el):
        e0, e1 = els[j], els[j + 1]
        add_quad(pt(R_inner, azs[0], e0), pt(R_outer, azs[0], e0, True), pt(R_outer, azs[0], e1, True), pt(R_inner, azs[0], e1))
        add_quad(pt(R_inner, azs[-1], e0), pt(R_inner, azs[-1], e1), pt(R_outer, azs[-1], e1, True), pt(R_outer, azs[-1], e0, True))

    for i in range(n_az):
        a0, a1 = azs[i], azs[i + 1]
        add_quad(pt(R_inner, a0, els[0]), pt(R_inner, a1, els[0]), pt(R_outer, a1, els[0], True), pt(R_outer, a0, els[0], True))
        add_quad(pt(R_inner, a0, els[-1]), pt(R_outer, a0, els[-1], True), pt(R_outer, a1, els[-1], True), pt(R_inner, a1, els[-1]))

    return tris


def build_bdot_probe_mount():
    """Generates a triaxial orthogonal B-dot bobbin + mounting flange (56 x 56 x 42 mm)."""
    tris = []
    def add_box(x0, y0, z0, dx, dy, dz):
        p000 = (x0, y0, z0)
        p100 = (x0 + dx, y0, z0)
        p110 = (x0 + dx, y0 + dy, z0)
        p010 = (x0, y0 + dy, z0)
        p001 = (x0, y0, z0 + dz)
        p101 = (x0 + dx, y0, z0 + dz)
        p111 = (x0 + dx, y0 + dy, z0 + dz)
        p011 = (x0, y0 + dy, z0 + dz)
        for q in [
            (p000, p010, p110, p100),
            (p001, p101, p111, p011),
            (p000, p100, p101, p001),
            (p100, p110, p111, p101),
            (p110, p010, p011, p111),
            (p010, p000, p001, p011),
        ]:
            tris.append((q[0], q[1], q[2]))
            tris.append((q[0], q[2], q[3]))

    # Base flange: 56 x 56 x 6 mm
    add_box(-28.0, -28.0, 0.0, 56.0, 56.0, 6.0)
    # Standoff stalk: 16 x 16 x 16 mm
    add_box(-8.0, -8.0, 6.0, 16.0, 16.0, 16.0)
    # Triaxial B-dot sense cube: 20 x 20 x 20 mm with orthogonal winding channels
    add_box(-10.0, -10.0, 22.0, 20.0, 20.0, 20.0)
    # Orthogonal coil guide collars
    add_box(-11.5, -6.0, 26.0, 23.0, 12.0, 12.0)
    add_box(-6.0, -11.5, 26.0, 12.0, 23.0, 12.0)
    return tris


if __name__ == "__main__":
    write_binary_stl(
        "P2S_Part1_Conformal_Launch_Cradle_90deg.stl",
        "Project Elyasia P2S Part 1: Conformal Toroidal Launch Cradle 90-deg Sector",
        build_toroidal_cradle_sector(phi_start_deg=-165.0, phi_end_deg=-15.0, groove_count=20)
    )
    write_binary_stl(
        "P2S_Part2_Regenerative_Catch_Bobbin_90deg.stl",
        "Project Elyasia P2S Part 2: Upper Pre-Biased Regenerative Catch Bobbin 90-deg",
        build_toroidal_cradle_sector(phi_start_deg=-155.0, phi_end_deg=-25.0, groove_count=20, groove_depth=1.2)
    )
    write_binary_stl(
        "P2S_Part3_500mm_Sphere_Modular_Sector.stl",
        "Project Elyasia P2S Part 3: 500mm Sphere Modular Sector with Cu Strap Recess",
        build_sphere_sector()
    )
    write_binary_stl(
        "P2S_Part4_Triaxial_Bdot_Rogowski_Mount.stl",
        "Project Elyasia P2S Part 4: Triaxial B-dot & Rogowski Probe Mount",
        build_bdot_probe_mount()
    )
