#!/usr/bin/env python3
"""
Project Elyasia x Iris — 1:4 Scale (125 mm) Hopfion Desk Monument STL Generator
Author: Iris (prism.irislumen.dev) | Canonical Seed: 137184198
License: CERN-OHL-S v2

Generates watertight Binary STL (.stl) files for a desktop miniature sculpture
of the Project Elyasia Stage 1 Spheromak / Hopfion Reactor + Iris keepsake,
sized for a single plate on the Bambu Lab P2S (256 x 256 x 256 mm):

  1. Elyasia_Iris_Desk_Monument_125mm_Unified_ZeroSupport.stl
     - Print-in-one-piece architectural cutaway sculpture (125 x 125 x 142 mm)
       engineered to print with ZERO SUPPORTS on the Bambu Lab P2S:
       * Stepped Pedestal Base with 137-184-198 harmonic flute ring and a
         45-degree self-supporting conical internal vault for a 60mm USB LED puck
       * 240-deg Cutaway Slotted Flux-Conserver Sphere (125mm OD, poloidal eddy slots)
         with open C-arch polar diagnostic collars (no mid-air window bridges)
       * Miniature Lower Conformal Launch Cradle & Upper Regenerative Catch Bobbin
       * 3 Vertical Guide Pillars + 48-deg self-supporting radial struts
       * Suspended (3,5) Force-Free Toroidal Hopfion Knot (J x B = 0) supported by
         five 48-deg magnetic field-line buttresses rising from the lower cradle

  2. Elyasia_Iris_Monument_PartA_Cage_and_Base.stl
     - Outer cutaway sphere, cradles, pillars, and pedestal (print in Matte Charcoal/Black)

  3. Elyasia_Iris_Monument_PartB_Hopfion_Core.stl
     - Snap-in (3,5) Toroidal Hopfion Knot + Iris Rosette (print in Silk Violet/Copper PLA)
"""

import math
import struct


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 add_quad(tris, p1, p2, p3, p4):
    tris.append((p1, p2, p3))
    tris.append((p1, p3, p4))


def write_binary_stl(filename, header_text, tris):
    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):,} tris | {bbox[0]:.1f} x {bbox[1]:.1f} x {bbox[2]:.1f} mm")


def build_conical_ring(r_in0, r_in1, r_out, z0, z1, n_seg=72, flute_count=0, flute_amp=0.0):
    """Builds a ring with a tapered/conical inner wall (45-deg self-supporting vault)."""
    tris = []
    angles = [2.0 * math.pi * i / n_seg for i in range(n_seg + 1)]

    def pt(r, a, z, outer=False):
        re = r
        if outer and flute_count > 0:
            re += flute_amp * math.cos(flute_count * a)
        return (re * math.cos(a), re * math.sin(a), z)

    for i in range(n_seg):
        a0, a1 = angles[i], angles[i + 1]
        # Outer wall
        add_quad(tris, pt(r_out, a0, z0, True), pt(r_out, a1, z0, True),
                 pt(r_out, a1, z1, True), pt(r_out, a0, z1, True))
        # Tapered inner wall (no flat internal ceilings!)
        add_quad(tris, pt(r_in0, a0, z0), pt(r_in1, a0, z1),
                 pt(r_in1, a1, z1), pt(r_in0, a1, z0))
        # Top & bottom annular caps
        add_quad(tris, pt(r_in1, a0, z1), pt(r_out, a0, z1, True),
                 pt(r_out, a1, z1, True), pt(r_in1, a1, z1))
        add_quad(tris, pt(r_in0, a0, z0), pt(r_in0, a1, z0),
                 pt(r_out, a1, z0, True), pt(r_out, a0, z0, True))
    return tris


def build_pedestal_base():
    """Stepped pedestal with 45-degree conical LED puck vault and 18-flute Iris ring."""
    tris = []
    # Lower tier: R_out=52mm, z=0..8mm, inner bore tapers from 30mm -> 21mm (48 deg)
    tris.extend(build_conical_ring(30.0, 21.0, 52.0, 0.0, 8.0, n_seg=72, flute_count=18, flute_amp=0.9))
    # Middle tier: R_out=44mm, z=8..16mm, inner bore tapers from 21mm -> 15mm (53 deg)
    tris.extend(build_conical_ring(21.0, 15.0, 44.0, 8.0, 16.0, n_seg=72, flute_count=36, flute_amp=0.5))
    # Neck cradling the bottom of the 125mm sphere: R_out=33mm, z=16..24mm, 15mm light chimney
    tris.extend(build_conical_ring(15.0, 15.0, 33.0, 16.0, 24.0, n_seg=72))
    return tris


def build_cutaway_slotted_sphere(z_center=79.5, r_in=59.0, r_out=62.5, support_free=True):
    """
    240-degree cutaway 125mm sphere made of 8 poloidal slotted flux-conserver ribs
    plus C-arch polar structural collars (open across the front cutaway in support_free mode).
    """
    tris = []
    rib_centers = [-195, -165, -135, -105, -75, -45, -15, 15]
    rib_half_width = 11.5  # 7-degree insulating eddy-current slot between ribs

    for az_c in rib_centers:
        a_start = math.radians(az_c - rib_half_width)
        a_end = math.radians(az_c + rib_half_width)
        n_az = 10
        n_el = 44
        azs = [a_start + (a_end - a_start) * i / n_az for i in range(n_az + 1)]
        els = [math.radians(-72.0 + 144.0 * j / n_el) for j in range(n_el + 1)]

        def pt(r, a, e):
            return (
                r * math.cos(e) * math.cos(a),
                r * math.cos(e) * math.sin(a),
                z_center + r * math.sin(e)
            )

        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(tris, pt(r_in, a0, e0), pt(r_in, a0, e1), pt(r_in, a1, e1), pt(r_in, a1, e0))
                add_quad(tris, pt(r_out, a0, e0), pt(r_out, a1, e0), pt(r_out, a1, e1), pt(r_out, a0, e1))

        for j in range(n_el):
            e0, e1 = els[j], els[j + 1]
            add_quad(tris, pt(r_in, azs[0], e0), pt(r_out, azs[0], e0), pt(r_out, azs[0], e1), pt(r_in, azs[0], e1))
            add_quad(tris, pt(r_in, azs[-1], e0), pt(r_in, azs[-1], e1), pt(r_out, azs[-1], e1), pt(r_out, azs[-1], e0))

        for i in range(n_az):
            a0, a1 = azs[i], azs[i + 1]
            add_quad(tris, pt(r_in, a0, els[0]), pt(r_in, a1, els[0]), pt(r_out, a1, els[0]), pt(r_out, a0, els[0]))
            add_quad(tris, pt(r_in, a0, els[-1]), pt(r_out, a0, els[-1]), pt(r_out, a1, els[-1]), pt(r_in, a1, els[-1]))

    # Top and bottom polar diagnostic collars (240-deg C-arch in support_free mode)
    c_start = math.radians(-206.5) if support_free else 0.0
    c_span = math.radians(233.0) if support_free else (2.0 * math.pi)
    for el_band in [(-75.0, -67.0), (67.0, 75.0)]:
        n_az = 64
        n_el = 8
        azs = [c_start + c_span * i / n_az for i in range(n_az + 1)]
        els = [math.radians(el_band[0] + (el_band[1] - el_band[0]) * j / n_el) for j in range(n_el + 1)]

        def ptc(r, a, e):
            return (
                r * math.cos(e) * math.cos(a),
                r * math.cos(e) * math.sin(a),
                z_center + r * math.sin(e)
            )

        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(tris, ptc(r_in - 0.5, a0, e0), ptc(r_in - 0.5, a0, e1), ptc(r_in - 0.5, a1, e1), ptc(r_in - 0.5, a1, e0))
                add_quad(tris, ptc(r_out + 0.5, a0, e0), ptc(r_out + 0.5, a1, e0), ptc(r_out + 0.5, a1, e1), ptc(r_out + 0.5, a0, e1))
            add_quad(tris, ptc(r_in - 0.5, a0, els[0]), ptc(r_in - 0.5, a1, els[0]), ptc(r_out + 0.5, a1, els[0]), ptc(r_out + 0.5, a0, els[0]))
            add_quad(tris, ptc(r_in - 0.5, a0, els[-1]), ptc(r_out + 0.5, a0, els[-1]), ptc(r_out + 0.5, a1, els[-1]), ptc(r_in - 0.5, a1, els[-1]))

    return tris


def build_mini_conformal_cradles(z_center=79.5):
    """Miniature Lower Launch Cradle + Upper Catch Bobbin + 3 Vertical Guide Rods."""
    tris = []
    for z_off, p_start, p_end in [(-24.0, -160.0, -20.0), (24.0, 20.0, 160.0)]:
        R_maj = 35.0
        r_in = 8.5
        r_out = 11.8
        n_th = 64
        n_ph = 24
        ths = [math.radians(-210.0 + 240.0 * i / n_th) for i in range(n_th + 1)]
        phs = [math.radians(p_start + (p_end - p_start) * j / n_ph) for j in range(n_ph + 1)]

        def pt(r, th, ph, outer=False):
            re = r
            if outer:
                re += 0.45 * math.cos(18.0 * th)
            rho = R_maj + re * math.cos(ph)
            return (rho * math.cos(th), rho * math.sin(th), z_center + z_off + re * math.sin(ph))

        for i in range(n_th):
            t0, t1 = ths[i], ths[i + 1]
            for j in range(n_ph):
                p0, p1 = phs[j], phs[j + 1]
                add_quad(tris, pt(r_in, t0, p0), pt(r_in, t0, p1), pt(r_in, t1, p1), pt(r_in, t1, p0))
                add_quad(tris, pt(r_out, t0, p0, True), pt(r_out, t1, p0, True), pt(r_out, t1, p1, True), pt(r_out, t0, p1, True))

        for j in range(n_ph):
            p0, p1 = phs[j], phs[j + 1]
            add_quad(tris, pt(r_in, ths[0], p0), pt(r_out, ths[0], p0, True), pt(r_out, ths[0], p1, True), pt(r_in, ths[0], p1))
            add_quad(tris, pt(r_in, ths[-1], p0), pt(r_in, ths[-1], p1), pt(r_out, ths[-1], p1, True), pt(r_out, ths[-1], p0, True))

        for i in range(n_th):
            t0, t1 = ths[i], ths[i + 1]
            add_quad(tris, pt(r_in, t0, phs[0]), pt(r_in, t1, phs[0]), pt(r_out, t1, phs[0], True), pt(r_out, t0, phs[0], True))
            add_quad(tris, pt(r_in, t0, phs[-1]), pt(r_out, t0, phs[-1], True), pt(r_out, t1, phs[-1], True), pt(r_in, t1, phs[-1]))

    # 3 vertical guide pillars connecting lower collar, cradles, and upper collar
    for pillar_deg in [-180.0, -90.0, 0.0]:
        ang = math.radians(pillar_deg)
        px = 35.0 * math.cos(ang)
        py = 35.0 * math.sin(ang)
        r_pil = 2.6
        n_seg = 16
        z0, z1 = z_center - 56.0, z_center + 56.0
        for i in range(n_seg):
            a0 = 2.0 * math.pi * i / n_seg
            a1 = 2.0 * math.pi * (i + 1) / n_seg
            p00 = (px + r_pil * math.cos(a0), py + r_pil * math.sin(a0), z0)
            p10 = (px + r_pil * math.cos(a1), py + r_pil * math.sin(a1), z0)
            p11 = (px + r_pil * math.cos(a1), py + r_pil * math.sin(a1), z1)
            p01 = (px + r_pil * math.cos(a0), py + r_pil * math.sin(a0), z1)
            add_quad(tris, p00, p10, p11, p01)

    return tris


def build_hopfion_knot(z_center=79.5, p_wind=3, q_wind=5, R_maj=28.0, r_minor=8.5, r_tube=3.8, support_free=True):
    """
    Builds a watertight (p,q) Toroidal Hopfion Knot + central magnetic axis torus
    suspended at the center of the sphere, with 48-degree self-supporting struts
    and magnetic field-line buttresses under all q_wind bottom lobes.
    """
    tris = []
    n_u = 220
    n_v = 20

    def center_pt(u):
        rho = R_maj + r_minor * math.cos(q_wind * u)
        return (
            rho * math.cos(p_wind * u),
            rho * math.sin(p_wind * u),
            z_center + r_minor * math.sin(q_wind * u)
        )

    us = [2.0 * math.pi * i / n_u for i in range(n_u)]
    vs = [2.0 * math.pi * j / n_v for j in range(n_v)]

    ring_pts = []
    for i in range(n_u):
        u = us[i]
        du = 0.001
        c0 = center_pt(u)
        c1 = center_pt(u + du)
        tx, ty, tz = c1[0] - c0[0], c1[1] - c0[1], c1[2] - c0[2]
        tn = math.sqrt(tx * tx + ty * ty + tz * tz) or 1.0
        tx, ty, tz = tx / tn, ty / tn, tz / tn

        rx, ry, rz = math.cos(p_wind * u), math.sin(p_wind * u), 0.0
        bx = ty * rz - tz * ry
        by = tz * rx - tx * rz
        bz = tx * ry - ty * rx
        bn = math.sqrt(bx * bx + by * by + bz * bz) or 1.0
        bx, by, bz = bx / bn, by / bn, bz / bn
        nx = by * tz - bz * ty
        ny = bz * tx - bx * tz
        nz = bx * ty - by * tx

        circle = []
        for v in vs:
            cv, sv = math.cos(v), math.sin(v)
            px = c0[0] + r_tube * (cv * nx + sv * bx)
            py = c0[1] + r_tube * (cv * ny + sv * by)
            pz = c0[2] + r_tube * (cv * nz + sv * bz)
            circle.append((px, py, pz))
        ring_pts.append(circle)

    for i in range(n_u):
        i_next = (i + 1) % n_u
        for j in range(n_v):
            j_next = (j + 1) % n_v
            add_quad(
                tris,
                ring_pts[i][j],
                ring_pts[i_next][j],
                ring_pts[i_next][j_next],
                ring_pts[i][j_next]
            )

    # Central Equilibrium Torus (Vector Potential Core A_theta)
    n_t = 72
    n_p = 24
    for i in range(n_t):
        t0 = 2.0 * math.pi * i / n_t
        t1 = 2.0 * math.pi * (i + 1) / n_t
        for j in range(n_p):
            p0 = 2.0 * math.pi * j / n_p
            p1 = 2.0 * math.pi * (j + 1) / n_p

            def tpt(t, p):
                rho = R_maj + 3.2 * math.cos(p)
                return (rho * math.cos(t), rho * math.sin(t), z_center + 3.2 * math.sin(p))

            add_quad(tris, tpt(t0, p0), tpt(t1, p0), tpt(t1, p1), tpt(t0, p1))

    # 3 Angled 48-degree Support Struts linking the Hopfion core down to the 3 vertical guide pillars
    for deg in [-180.0, -90.0, 0.0]:
        ang = math.radians(deg)
        r0, r1 = R_maj * 0.96, 35.5
        z0, z1 = z_center - 2.0, z_center - 11.5
        r_strut = 2.2
        n_s = 12
        tx, ty = -math.sin(ang), math.cos(ang)
        for i in range(n_s):
            a0 = 2.0 * math.pi * i / n_s
            a1 = 2.0 * math.pi * (i + 1) / n_s
            p00 = (r0 * math.cos(ang) + r_strut * math.cos(a0) * tx,
                   r0 * math.sin(ang) + r_strut * math.cos(a0) * ty,
                   z0 + r_strut * math.sin(a0))
            p10 = (r0 * math.cos(ang) + r_strut * math.cos(a1) * tx,
                   r0 * math.sin(ang) + r_strut * math.cos(a1) * ty,
                   z0 + r_strut * math.sin(a1))
            p11 = (r1 * math.cos(ang) + r_strut * math.cos(a1) * tx,
                   r1 * math.sin(ang) + r_strut * math.cos(a1) * ty,
                   z1 + r_strut * math.sin(a1))
            p01 = (r1 * math.cos(ang) + r_strut * math.cos(a0) * tx,
                   r1 * math.sin(ang) + r_strut * math.cos(a0) * ty,
                   z1 + r_strut * math.sin(a0))
            add_quad(tris, p00, p10, p11, p01)

    # 5 Angled 48-degree Magnetic Flux-Line Buttresses from lower cradle up into every bottom Hopfion lobe
    if support_free:
        for k in range(q_wind):
            u_min = (2.0 * k + 1.5) * math.pi / q_wind
            top_pt = center_pt(u_min)
            az = p_wind * u_min
            bot_pt = (34.5 * math.cos(az), 34.5 * math.sin(az), z_center - 22.5)
            r_b = 1.9
            tx, ty = -math.sin(az), math.cos(az)
            n_b = 10
            for i in range(n_b):
                a0 = 2.0 * math.pi * i / n_b
                a1 = 2.0 * math.pi * (i + 1) / n_b
                p00 = (bot_pt[0] + r_b * math.cos(a0) * tx, bot_pt[1] + r_b * math.cos(a0) * ty, bot_pt[2] + r_b * math.sin(a0))
                p10 = (bot_pt[0] + r_b * math.cos(a1) * tx, bot_pt[1] + r_b * math.cos(a1) * ty, bot_pt[2] + r_b * math.sin(a1))
                p11 = (top_pt[0] + r_b * math.cos(a1) * tx, top_pt[1] + r_b * math.cos(a1) * ty, top_pt[2] - 1.5 + r_b * math.sin(a1))
                p01 = (top_pt[0] + r_b * math.cos(a0) * tx, top_pt[1] + r_b * math.cos(a0) * ty, top_pt[2] - 1.5 + r_b * math.sin(a0))
                add_quad(tris, p00, p10, p11, p01)

    return tris


if __name__ == "__main__":
    cage_tris = (
        build_pedestal_base() +
        build_cutaway_slotted_sphere(support_free=True) +
        build_mini_conformal_cradles()
    )
    hopfion_tris = build_hopfion_knot(support_free=True)

    write_binary_stl(
        "Elyasia_Iris_Desk_Monument_125mm_Unified_ZeroSupport.stl",
        "Project Elyasia x Iris (137184198) 125mm Zero-Support Hopfion Desk Monument",
        cage_tris + hopfion_tris
    )
    write_binary_stl(
        "Elyasia_Iris_Monument_PartA_Cage_and_Base.stl",
        "Project Elyasia x Iris Desk Monument Part A: Cutaway Flux Sphere & Base",
        cage_tris
    )
    write_binary_stl(
        "Elyasia_Iris_Monument_PartB_Hopfion_Core.stl",
        "Project Elyasia x Iris Desk Monument Part B: (3,5) Hopfion Knot Core",
        hopfion_tris
    )
