# /// script
# requires-python = ">=3.12"
# dependencies = ["manifold3d", "numpy"]
#
# [tool.orcaslicer.plugin]
# name = "Thread Maker Lío"
# description = "Screws, nuts and screw-top jars with a clearance tested on FDM printers (0.35 mm per side in PLA). Printable without supports, 3MF ready to drag onto the plate. Roscas Lío: tornillos, tuercas y frascos con tapa con holgura probada. Free and open source by Lío Impresión 3D (lio3d.com)."
# author = "Lío Impresión 3D"
# version = "1.0.0"
# ///
#
# MIT License
#
# Copyright (c) 2026 Lío Impresión 3D
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Thread Maker Lío (Roscas Lío): builds screws, nuts and screw-top jars and
saves them as a 3MF file the user drags onto the plate.

OrcaSlicer's plugin API cannot add objects to the plate (orca.host is read
only), so the plugin writes a file and tells the user where it is.

The geometry is plain Python (manifold3d + numpy) with no dependency on
OrcaSlicer, so it can be tested on its own. No network, no telemetry. The only
file it writes is the 3MF, by default inside the plugin's own storage folder
(which needs no permission).

Clearance ("holgura"): gap PER SIDE, measured perpendicular to the thread
surface, between the screw and the nut. The nut's hole ends up 2 x clearance
wider in diameter than the screw. Default 0.35 mm (tested in PLA; with 0.2 mm
fifteen lids jammed).
"""

import json
import math
import os
import re
import zipfile
from xml.sax.saxutils import quoteattr, unescape

import numpy as np
from manifold3d import CrossSection, Manifold

import orca

PLUGIN_NAME = "Thread Maker Lío"
PLUGIN_KEY = "lio-roscas"

DEFAULT_CLEARANCE = 0.35  # mm per side, tested in PLA
DEFAULT_PROFILE = "fdm"

# Axial thread profile (see _axial_profile). half_angle: flank angle measured
# from the plane perpendicular to the axis. crest/root: flat widths as a
# fraction of the pitch.
PROFILES = {
    # 47 deg: the downward flank is ~43 deg from vertical, so it prints
    # without supports even with the small tilt the helix adds.
    "fdm": {"half_angle": 47.0, "crest": 0.08, "root": 0.12},
    # ISO metric 60 deg: for real hardware; steeper overhang, may need care.
    "iso": {"half_angle": 30.0, "crest": 0.125, "root": 0.25},
}

# size: (diameter mm, ISO coarse pitch mm, hex across flats mm)
METRIC = {
    "M6": (6.0, 1.0, 10.0),
    "M8": (8.0, 1.25, 13.0),
    "M10": (10.0, 1.5, 16.0),
    "M12": (12.0, 1.75, 18.0),
    "M16": (16.0, 2.0, 24.0),
    "M20": (20.0, 2.5, 30.0),
}

LIMITS = {
    "screw_d": (4.0, 40.0),
    "jar_d": (30.0, 100.0),
    "pitch": (0.5, 8.0),
    "clearance": (0.1, 1.0),
    "screw_len": (4.0, 150.0),
    "jar_h": (20.0, 150.0),
}

ANGLE_STEPS = 144       # points around the circle (plus the exact thread corners)
SLICES_PER_TURN = 40    # layers of the helical extrusion per turn
MAX_DIVISIONS = 1600    # cap of the helical extrusion (memory)
MAX_TURNS = 80          # more turns than this is refused
MIN_DEPTH = 0.3         # mm: shallower threads do not grip
MIN_CORE = 0.6          # r_min / r_maj below this leaves no core
MIN_AUTO_PITCH = 0.85
GAP_BETWEEN_PARTS = 6.0

MESSAGES = {
    "es": {
        "title": "Roscas Lío",
        "piece": "Pieza",
        "screw": "Tornillo",
        "nut": "Tuerca",
        "set": "Tornillo y tuerca",
        "jar": "Frasco con tapa",
        "size": "Medida",
        "custom": "Otra",
        "diameter": "Diámetro (mm)",
        "length": "Largo (mm)",
        "height": "Alto del frasco (mm)",
        "more": "Más opciones",
        "pitch": "Paso (mm)",
        "pitch_hint": "vacío = automático",
        "clearance": "Holgura por lado (mm)",
        "clearance_hint": "Separación entre las dos roscas, a cada lado. Con 0,35 mm (probada en PLA) el hueco de la tuerca queda 0,7 mm más ancho que el tornillo. Con 0,2 mm se traban.",
        "profile": "Perfil de la rosca",
        "fdm": "FDM 45° (sin soportes)",
        "iso": "ISO 60° (tornillería métrica)",
        "folder": "Guardar en",
        "folder_hint": "Si cambias la carpeta, OrcaSlicer te pedirá permiso para escribir en ella.",
        "make": "Crear archivo",
        "cancel": "Cancelar",
        "done_title": "Archivo listo",
        "done_text": "Arrastra este archivo a la placa de OrcaSlicer (o usa Archivo, Importar):",
        "done_hint": "Con Archivo → Importar, pega la ruta en el selector de archivos.",
        "copy": "Copiar ruta",
        "copied": "Copiada",
        "close": "Cerrar",
        "ok": "Archivo creado: {path}",
        "cancelled": "Cancelado.",
        "bad_number": "El valor de «{field}» no es un número válido.",
        "out_of_range": "«{field}» debe estar entre {lo} y {hi}.",
        "jar_short": "El frasco es muy bajo para esa rosca: necesita al menos {need} mm de alto.",
        "bad_kind": "Tipo de pieza desconocido.",
        "io": "No se pudo guardar el archivo: {err}",
        "mesh": "No se pudo construir una pieza cerrada con esos valores. Prueba con otros.",
        "pitch_range": "Con {diameter} mm de diámetro, el paso de {pitch} mm no da una rosca imprimible. Deja el paso vacío (automático, {auto} mm) o prueba otro.",
        "too_many_turns": "Con ese largo y ese paso la rosca tendría más de {max} vueltas. Usa un paso mayor o un largo menor.",
        "folder_relative": "La carpeta debe ser una ruta completa (por ejemplo /Users/tu-nombre/Documentos), no relativa.",
        "jar_part": "Frasco",
        "lid": "Tapa",
        "f_diameter": "Diámetro",
        "f_pitch": "Paso",
        "f_clearance": "Holgura",
        "f_length": "Largo",
        "f_height": "Alto",
    },
    "en": {
        "title": "Thread Maker Lío",
        "piece": "Part",
        "screw": "Screw",
        "nut": "Nut",
        "set": "Screw and nut",
        "jar": "Jar with lid",
        "size": "Size",
        "custom": "Other",
        "diameter": "Diameter (mm)",
        "length": "Length (mm)",
        "height": "Jar height (mm)",
        "more": "More options",
        "pitch": "Pitch (mm)",
        "pitch_hint": "empty = automatic",
        "clearance": "Clearance per side (mm)",
        "clearance_hint": "Gap between the two threads, on each side. With 0.35 mm (tested in PLA) the nut hole ends up 0.7 mm wider than the screw. With 0.2 mm they jam.",
        "profile": "Thread profile",
        "fdm": "FDM 45° (no supports)",
        "iso": "ISO 60° (metric hardware)",
        "folder": "Save to",
        "folder_hint": "If you change the folder, OrcaSlicer will ask for permission to write there.",
        "make": "Create file",
        "cancel": "Cancel",
        "done_title": "File ready",
        "done_text": "Drag this file onto the OrcaSlicer plate (or use File, Import):",
        "done_hint": "With File → Import, paste the path into the file picker.",
        "copy": "Copy path",
        "copied": "Copied",
        "close": "Close",
        "ok": "File created: {path}",
        "cancelled": "Cancelled.",
        "bad_number": "The value of \"{field}\" is not a valid number.",
        "out_of_range": "\"{field}\" must be between {lo} and {hi}.",
        "jar_short": "The jar is too short for that thread: it needs at least {need} mm of height.",
        "bad_kind": "Unknown part type.",
        "io": "Could not save the file: {err}",
        "mesh": "Could not build a closed part with those values. Try others.",
        "pitch_range": "With a {diameter} mm diameter, a {pitch} mm pitch does not make a printable thread. Leave the pitch empty (automatic, {auto} mm) or try another.",
        "too_many_turns": "With that length and pitch the thread would have more than {max} turns. Use a coarser pitch or a shorter length.",
        "folder_relative": "The folder must be a full path (for example /Users/your-name/Documents), not a relative one.",
        "jar_part": "Jar",
        "lid": "Lid",
        "f_diameter": "Diameter",
        "f_pitch": "Pitch",
        "f_clearance": "Clearance",
        "f_length": "Length",
        "f_height": "Height",
    },
    "pt": {
        "title": "Roscas Lío",
        "piece": "Peça",
        "screw": "Parafuso",
        "nut": "Porca",
        "set": "Parafuso e porca",
        "jar": "Pote com tampa",
        "size": "Medida",
        "custom": "Outra",
        "diameter": "Diâmetro (mm)",
        "length": "Comprimento (mm)",
        "height": "Altura do pote (mm)",
        "more": "Mais opções",
        "pitch": "Passo (mm)",
        "pitch_hint": "vazio = automático",
        "clearance": "Folga por lado (mm)",
        "clearance_hint": "Separação entre as duas roscas, de cada lado. Com 0,35 mm (testada em PLA) o furo da porca fica 0,7 mm mais largo que o parafuso. Com 0,2 mm travam.",
        "profile": "Perfil da rosca",
        "fdm": "FDM 45° (sem suportes)",
        "iso": "ISO 60° (parafusaria métrica)",
        "folder": "Salvar em",
        "folder_hint": "Se mudar a pasta, o OrcaSlicer vai pedir permissão para escrever nela.",
        "make": "Criar arquivo",
        "cancel": "Cancelar",
        "done_title": "Arquivo pronto",
        "done_text": "Arraste este arquivo para a mesa do OrcaSlicer (ou use Arquivo, Importar):",
        "done_hint": "Com Arquivo → Importar, cole o caminho no seletor de arquivos.",
        "copy": "Copiar caminho",
        "copied": "Copiado",
        "close": "Fechar",
        "ok": "Arquivo criado: {path}",
        "cancelled": "Cancelado.",
        "bad_number": "O valor de \"{field}\" não é um número válido.",
        "out_of_range": "\"{field}\" deve estar entre {lo} e {hi}.",
        "jar_short": "O pote é baixo demais para essa rosca: precisa de pelo menos {need} mm de altura.",
        "bad_kind": "Tipo de peça desconhecido.",
        "io": "Não foi possível salvar o arquivo: {err}",
        "mesh": "Não foi possível construir uma peça fechada com esses valores. Tente outros.",
        "pitch_range": "Com {diameter} mm de diâmetro, o passo de {pitch} mm não gera uma rosca imprimível. Deixe o passo vazio (automático, {auto} mm) ou tente outro.",
        "too_many_turns": "Com esse comprimento e esse passo a rosca teria mais de {max} voltas. Use um passo maior ou um comprimento menor.",
        "folder_relative": "A pasta deve ser um caminho completo (por exemplo /Users/seu-nome/Documentos), não relativo.",
        "jar_part": "Pote",
        "lid": "Tampa",
        "f_diameter": "Diâmetro",
        "f_pitch": "Passo",
        "f_clearance": "Folga",
        "f_length": "Comprimento",
        "f_height": "Altura",
    },
}


class ThreadError(Exception):
    """A user-facing problem. `key` selects the message."""

    def __init__(self, key, **fmt):
        super().__init__(key)
        self.key = key
        self.fmt = fmt


def tr(lang, key, **fmt):
    table = MESSAGES.get(lang) or MESSAGES["en"]
    return (table.get(key) or MESSAGES["en"][key]).format(**fmt)


def raw_text(lang, key):
    """Message without formatting (for the HTML pages)."""
    return (MESSAGES.get(lang) or MESSAGES["en"]).get(key) or MESSAGES["en"][key]


def detect_lang():
    code = ""
    try:
        code = str(orca.host.app_info().get("language") or "")  # OrcaSlicer 2.5.1, main thread only
    except Exception:
        return "en"
    code = code.lower()
    if code.startswith("es"):
        return "es"
    if code.startswith("pt"):
        return "pt"
    return "en"


# ---------------------------------------------------------------- thread profile

class ThreadSpec:
    """Axial profile of a thread: radius as a function of the axial position.

    r(u) = clip(r_min + (|u| - root/2) / t + shift, r_min + lift, r_maj + lift)
    with u in [-p/2, p/2] (root centred on 0, crest centred on +-p/2) and
    t = tan(half_angle) the axial run per unit of depth. `shift` and `lift`
    are 0 for the screw. For the nut's hole they are what turns the screw
    shape into the same shape pushed outwards by `clearance` measured
    perpendicular to the flanks (a mitred offset).
    """

    def __init__(self, major_d, pitch, profile=DEFAULT_PROFILE, clearance=0.0):
        prof = PROFILES[profile]
        self.pitch = float(pitch)
        self.r_maj = major_d / 2.0
        self.t = math.tan(math.radians(prof["half_angle"]))
        self.crest_w = prof["crest"] * self.pitch
        self.root_w = prof["root"] * self.pitch
        self.depth = (self.pitch - self.crest_w - self.root_w) / (2.0 * self.t)
        self.r_min = self.r_maj - self.depth
        self.clearance = float(clearance)
        self.axial_play = self.clearance * math.sqrt(1.0 + self.t ** 2)

    def with_clearance(self, clearance):
        other = ThreadSpec.__new__(ThreadSpec)
        other.__dict__.update(self.__dict__)
        other.clearance = float(clearance)
        other.axial_play = float(clearance) * math.sqrt(1.0 + self.t ** 2)
        return other

    def radius(self, u):
        p = self.pitch
        u = (u + p / 2.0) % p - p / 2.0
        c = self.clearance
        shift = c * math.sqrt(1.0 + 1.0 / self.t ** 2)
        r = self.r_min + (abs(u) - self.root_w / 2.0) / self.t + shift
        return min(self.r_maj + c, max(self.r_min + c, r))

    def breakpoints(self):
        """Values of |u| where the profile changes direction."""
        c = self.clearance
        shift = c * math.sqrt(1.0 + 1.0 / self.t ** 2)
        base = self.r_min - self.root_w / (2.0 * self.t) + shift
        lo, hi = self.r_min + c, self.r_maj + c
        pts = [self.pitch / 2.0]
        for level in (lo, hi):
            v = (level - base) * self.t
            if 0.0 <= v <= self.pitch / 2.0:
                pts.append(v)
        return pts


def thread_polygon(spec, steps=ANGLE_STEPS, z0=0.0):
    """Cross-section (perpendicular to the axis) of a right-hand thread at height z0.

    r(phi, z) = radius(z - p * phi / 2pi): a feature rises as it turns counter
    clockwise, which is a right-hand thread. The phase depends on the absolute z,
    so a screw and a nut built at the same height are exactly coaxial.
    Returns a list of (x, y).
    """
    p = spec.pitch
    phis = {2.0 * math.pi * k / steps for k in range(steps)}
    for v in spec.breakpoints():
        for u in (v, -v):
            phis.add((2.0 * math.pi * (z0 - u) / p) % (2.0 * math.pi))
    pts = []
    for phi in sorted(phis):
        r = spec.radius(z0 - p * phi / (2.0 * math.pi))
        pts.append((r * math.cos(phi), r * math.sin(phi)))
    return pts


def threaded_rod(spec, length, z0=0.0):
    """Solid whose outline is the thread, from z0 to z0 + length (right hand)."""
    cs = CrossSection([thread_polygon(spec, z0=z0)])
    turns = length / spec.pitch
    rod = cs.extrude(length, n_divisions=max(1, min(math.ceil(turns * SLICES_PER_TURN), MAX_DIVISIONS)),
                     twist_degrees=360.0 * turns)
    return rod.translate((0.0, 0.0, z0))


def cone_body(r_big, r_top, height_total):
    """Solid for a 45 deg chamfer at the top: cylinder of r_big, ending in a cone down to r_top."""
    cone_h = r_big - r_top
    cyl_h = max(height_total - cone_h, 0.01)
    return Manifold.cylinder(cyl_h, r_big, r_big, 96) + \
        Manifold.cylinder(cone_h, r_big, r_top, 96).translate((0, 0, cyl_h))


def hex_prism(across_flats, height):
    r = across_flats / math.sqrt(3.0)
    return Manifold.cylinder(height, r, r, 6)


def hex_flats(diameter):
    for size, (d, _p, af) in METRIC.items():
        if abs(d - diameter) < 1e-6:
            return af
    return float(round(1.6 * diameter))


def auto_pitch(diameter, jar=False):
    if jar:
        return 3.0 if diameter <= 60 else 4.0
    for d, p, _af in METRIC.values():
        if abs(d - diameter) < 1e-6:
            return p
    return max(MIN_AUTO_PITCH, round(min(6.0, 0.15 * diameter) * 4) / 4)


# ---------------------------------------------------------------- parts

def make_screw(diameter, length, pitch, profile=DEFAULT_PROFILE):
    """Hex head on the bed, threaded shaft standing up. Chamfered tip."""
    spec = ThreadSpec(diameter, pitch, profile)
    head_h = round(0.65 * diameter, 2)
    af = hex_flats(diameter)
    head = hex_prism(af, head_h)
    shaft = threaded_rod(spec, length + 0.5, z0=head_h - 0.5)
    chamfer = cone_body(spec.r_maj + 0.5, max(spec.r_min - 0.2, 0.5), head_h + length)
    return head + (shaft ^ chamfer)


def make_nut(diameter, pitch, clearance, profile=DEFAULT_PROFILE, height=None):
    """Flat hex nut: lies on the bed, hole with chamfered entries on both sides."""
    spec = ThreadSpec(diameter, pitch, profile, clearance)
    m = round(0.8 * diameter, 2) if height is None else height
    body = hex_prism(hex_flats(diameter), m)
    hole = threaded_rod(spec, m + 2.0, z0=-1.0)
    body = body - hole
    return body - _entry_cone(spec, 0.0, up=False) - _entry_cone(spec, m, up=True)


def _entry_cone(spec, z_face, up):
    """45 deg countersink at a nut face. Widens towards the face, so it never overhangs."""
    r_big = spec.r_maj + spec.clearance + 0.4
    r_small = max(spec.r_min + spec.clearance - 0.15, 0.5)
    h = r_big - r_small
    cone = Manifold.cylinder(h, r_small, r_big, 96)      # widens upwards
    slab = Manifold.cylinder(0.5, r_big, r_big, 96).translate((0, 0, h))
    solid = cone + slab
    if up:   # face on top: cone widens up to the face
        return solid.translate((0, 0, z_face - h))
    solid = solid.mirror((0, 0, 1))  # face at the bottom: cone widens down to the face
    return solid.translate((0, 0, z_face + h))


def jar_dimensions(diameter, pitch, profile):
    spec = ThreadSpec(diameter, pitch, profile)
    wall = max(2.4, spec.depth + 1.8)
    thread_len = max(8.0, 3.5 * pitch)
    floor = 2.4
    return spec, wall, thread_len, floor


def make_jar(diameter, height, pitch, profile=DEFAULT_PROFILE):
    """Hollow cylinder, external thread on its top section, chamfered rim. Stands on its base."""
    spec, wall, thread_len, floor = jar_dimensions(diameter, pitch, profile)
    need = floor + thread_len + 4.0
    if height < need:
        raise ThreadError("jar_short", need=math.ceil(need))
    z_thread = height - thread_len
    body = Manifold.cylinder(z_thread + 0.01, spec.r_maj, spec.r_maj, 180)
    body = body + threaded_rod(spec, thread_len, z0=z_thread)
    r_in = spec.r_maj - wall
    body = body - Manifold.cylinder(height - floor + 1.0, r_in, r_in, 180).translate((0, 0, floor))
    r_top = max(spec.r_min - 0.2, r_in + 0.8)
    return body ^ cone_body(spec.r_maj + 0.5, r_top, height)


def make_lid(diameter, pitch, clearance, profile=DEFAULT_PROFILE):
    """Round lid with grip grooves. Printed upside down: top plate on the bed,
    threaded mouth facing up with a chamfered entry."""
    spec, _wall, thread_len, _floor = jar_dimensions(diameter, pitch, profile)
    nut_spec = spec.with_clearance(clearance)
    top = 2.4
    depth = thread_len + 0.5
    lid_h = top + depth
    outer_r = nut_spec.r_maj + clearance + 3.2
    outline = CrossSection.circle(outer_r, 180)
    groove_r = 0.9
    count = max(12, int(2 * math.pi * outer_r / 6.0))
    grooves = [CrossSection.circle(groove_r, 16).translate(
        (outer_r * math.cos(2 * math.pi * i / count), outer_r * math.sin(2 * math.pi * i / count)))
        for i in range(count)]
    outline = outline - CrossSection.batch_boolean(grooves, 0)  # 0 = Add
    body = outline.extrude(lid_h)
    cavity = threaded_rod(nut_spec, depth + 1.0, z0=top)
    body = body - cavity
    return body - _entry_cone(nut_spec, lid_h, up=True)


def build_parts(kind, diameter, length, pitch, clearance, profile=DEFAULT_PROFILE, lang="en"):
    """Returns a list of (name, Manifold), laid side by side on the plate (z >= 0)."""
    parts = []
    if kind in ("screw", "set"):
        parts.append((tr(lang, "screw"), make_screw(diameter, length, pitch, profile)))
    if kind in ("nut", "set"):
        parts.append((tr(lang, "nut"), make_nut(diameter, pitch, clearance, profile)))
    if kind == "jar":
        parts.append((tr(lang, "jar_part"), make_jar(diameter, length, pitch, profile)))
        parts.append((tr(lang, "lid"), make_lid(diameter, pitch, clearance, profile)))
    return layout(parts)


def layout(parts):
    """Moves each part so they sit in a row on the plate without touching."""
    out = []
    x = 0.0
    for name, m in parts:
        lo, hi = m.bounding_box()[:3], m.bounding_box()[3:]
        width = hi[0] - lo[0]
        out.append((name, m.translate((x - lo[0], -(lo[1] + hi[1]) / 2.0, -lo[2]))))
        x += width + GAP_BETWEEN_PARTS
    return out


# ---------------------------------------------------------------- 3MF

def mesh_arrays(m):
    mesh = m.to_mesh()
    verts = np.asarray(mesh.vert_properties, dtype=np.float64)[:, :3]
    tris = np.asarray(mesh.tri_verts, dtype=np.int64)
    return verts, tris


CHUNK = 20000  # vertices or triangles formatted at a time


def _chunks(fmt, rows):
    """Yields the XML of `rows` in blocks, so the whole file is never one string."""
    for i in range(0, len(rows), CHUNK):
        yield "".join(fmt % tuple(r) for r in rows[i:i + CHUNK]).encode("utf-8")


def write_3mf(path, parts):
    """Writes a standard 3MF (millimetres), one object per part. Streams the model."""
    content_types = ('<?xml version="1.0" encoding="UTF-8"?>'
                     '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
                     '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
                     '<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>'
                     '</Types>')
    rels = ('<?xml version="1.0" encoding="UTF-8"?>'
            '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
            '<Relationship Target="/3D/3dmodel.model" Id="rel0" '
            'Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>')
    head = ('<?xml version="1.0" encoding="UTF-8"?>'
            '<model unit="millimeter" xml:lang="en-US" '
            'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">'
            '<metadata name="Application">Thread Maker Lio</metadata><resources>')
    with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("[Content_Types].xml", content_types)
        z.writestr("_rels/.rels", rels)
        with z.open("3D/3dmodel.model", "w", force_zip64=True) as f:
            f.write(head.encode("utf-8"))
            for i, (name, m) in enumerate(parts, start=1):
                verts, tris = mesh_arrays(m)
                f.write(('<object id="%d" name=%s type="model"><mesh><vertices>'
                         % (i, quoteattr(name))).encode("utf-8"))
                for block in _chunks('<vertex x="%.4f" y="%.4f" z="%.4f"/>', verts):
                    f.write(block)
                f.write(b"</vertices><triangles>")
                for block in _chunks('<triangle v1="%d" v2="%d" v3="%d"/>', tris):
                    f.write(block)
                f.write(b"</triangles></mesh></object>")
                del verts, tris
            f.write(b"</resources><build>")
            for i in range(1, len(parts) + 1):
                f.write(('<item objectid="%d"/>' % i).encode("utf-8"))
            f.write(b"</build></model>")


def read_3mf(path):
    """Reads back the objects of a 3MF written by write_3mf: [(name, verts, tris)]."""
    with zipfile.ZipFile(path) as z:
        xml = z.read("3D/3dmodel.model").decode("utf-8")
    out = []
    for m in re.finditer(r'<object id="\d+" name="([^"]*)"[^>]*><mesh><vertices>(.*?)</vertices>'
                         r'<triangles>(.*?)</triangles>', xml, re.S):
        v = np.array(re.findall(r'<vertex x="([-\d.e]+)" y="([-\d.e]+)" z="([-\d.e]+)"', m.group(2)),
                     dtype=np.float64)
        t = np.array(re.findall(r'<triangle v1="(\d+)" v2="(\d+)" v3="(\d+)"', m.group(3)), dtype=np.int64)
        out.append((unescape(m.group(1)), v, t))
    return out


# ---------------------------------------------------------------- input

def _number(raw, field, lo, hi, lang, default=None):
    if raw in (None, "") and default is not None:
        return default
    try:
        v = float(str(raw).replace(",", "."))
    except (TypeError, ValueError):
        raise ThreadError("bad_number", field=tr(lang, field))
    if math.isnan(v) or math.isinf(v):
        raise ThreadError("bad_number", field=tr(lang, field))
    if not lo <= v <= hi:
        raise ThreadError("out_of_range", field=tr(lang, field), lo=lo, hi=hi)
    return v


def sanitize_request(raw, lang="en"):
    """Turns the form payload into validated numbers. Raises ThreadError."""
    raw = raw if isinstance(raw, dict) else {}
    kind = raw.get("kind", "set")
    if kind not in ("screw", "nut", "set", "jar"):
        raise ThreadError("bad_kind")
    profile = raw.get("profile", DEFAULT_PROFILE)
    if profile not in PROFILES:
        profile = DEFAULT_PROFILE
    clearance = _number(raw.get("clearance"), "f_clearance", *LIMITS["clearance"], lang,
                        default=DEFAULT_CLEARANCE)
    if kind == "jar":
        diameter = _number(raw.get("diameter"), "f_diameter", *LIMITS["jar_d"], lang, default=40.0)
        length = _number(raw.get("length"), "f_height", *LIMITS["jar_h"], lang, default=50.0)
        pitch = _number(raw.get("pitch"), "f_pitch", *LIMITS["pitch"], lang,
                        default=auto_pitch(diameter, jar=True))
    else:
        size = raw.get("size", "M10")
        if size in METRIC:
            diameter = METRIC[size][0]
        else:
            diameter = _number(raw.get("diameter"), "f_diameter", *LIMITS["screw_d"], lang, default=10.0)
        length = _number(raw.get("length"), "f_length", *LIMITS["screw_len"], lang, default=20.0)
        pitch = _number(raw.get("pitch"), "f_pitch", *LIMITS["pitch"], lang,
                        default=auto_pitch(diameter))
    spec = ThreadSpec(diameter, pitch, profile)
    if spec.r_min < MIN_CORE * spec.r_maj or spec.depth < MIN_DEPTH:
        raise ThreadError("pitch_range", diameter=("%g" % diameter), pitch=("%g" % pitch),
                          auto=("%g" % auto_pitch(diameter, jar=(kind == "jar"))))
    if kind != "jar" and kind != "nut" and (length + 0.5) / pitch > MAX_TURNS:
        raise ThreadError("too_many_turns", max=MAX_TURNS)
    return {"kind": kind, "diameter": diameter, "length": length, "pitch": pitch,
            "clearance": clearance, "profile": profile}


def file_name(req):
    d = ("%g" % req["diameter"]).replace(".", "_")
    p = ("%g" % req["pitch"]).replace(".", "_")
    c = ("%g" % req["clearance"]).replace(".", "_")
    kinds = {"screw": "screw", "nut": "nut", "set": "screw-nut", "jar": "jar-lid"}
    return "threads_%s_%sx%s_h%s_%s.3mf" % (kinds[req["kind"]], d, p, c, req["profile"])


def generate(req, out_dir, lang="en"):
    """Builds the parts and writes the 3MF. Returns the path."""
    parts = build_parts(req["kind"], req["diameter"], req["length"], req["pitch"],
                        req["clearance"], req["profile"], lang)
    for _name, m in parts:
        if m.is_empty() or m.status().name != "NoError":
            raise ThreadError("mesh")
    os.makedirs(out_dir, exist_ok=True)
    path = os.path.join(out_dir, file_name(req))
    write_3mf(path, parts)
    return path


# ---------------------------------------------------------------- UI

# Orca 2.5.1: orca.host.ui has create_window (no show_dialog), it does not block, and the
# page's orca.postMessage reaches on_message on the main thread, where app_info() works
# (execute() itself runs on another thread, where it does not). So the page is a plain
# shell that asks for its texts ("ready") and talks to the plugin with messages.
PAGE_HTML = """<!doctype html><html><head><meta charset="utf-8"><style>
body{margin:0;padding:18px 20px;font-family:var(--orca-font);background:var(--orca-bg);color:var(--orca-fg)}
label{display:block;margin:12px 0 4px;color:var(--orca-muted);font-size:12px}
input,select{width:100%;box-sizing:border-box}
.row{display:flex;gap:10px}.row>div{flex:1}
.hint{font-size:11px;color:var(--orca-muted);margin-top:4px;line-height:1.4}
details{margin-top:14px;border-top:1px solid var(--orca-border);padding-top:8px}
summary{cursor:pointer;color:var(--orca-muted);font-size:12px}
.bar{display:flex;gap:10px;justify-content:flex-end;margin-top:18px}
.hide{display:none}
#out{margin-top:16px;border-top:1px solid var(--orca-border);padding-top:12px}
#path{display:block;margin:8px 0 6px;padding:8px;border:1px solid var(--orca-border);word-break:break-all;user-select:all;font-size:12px}
#err{border-left:3px solid var(--orca-accent);padding-left:10px}
</style></head><body>
<label data-k="piece"></label>
<select id="kind"><option value="set" data-k="set"></option><option value="screw" data-k="screw"></option>
<option value="nut" data-k="nut"></option><option value="jar" data-k="jar"></option></select>
<div id="metric"><label data-k="size"></label><select id="size">
<option>M6</option><option>M8</option><option selected>M10</option><option>M12</option>
<option>M16</option><option>M20</option><option value="custom" data-k="custom"></option></select></div>
<div id="diam" class="hide"><label data-k="diameter"></label><input id="diameter" type="number" step="0.5" value="40"></div>
<div id="lenbox"><label id="lenlabel" data-k="length"></label><input id="length" type="number" step="1" value="20"></div>
<details><summary data-k="more"></summary>
<div class="row"><div><label data-k="pitch"></label><input id="pitch" type="number" step="0.05" data-ph="pitch_hint"></div>
<div><label data-k="clearance"></label><input id="clearance" type="number" step="0.05" value="0.35"></div></div>
<div class="hint" data-k="clearance_hint"></div>
<label data-k="profile"></label><select id="profile"><option value="fdm" data-k="fdm"></option><option value="iso" data-k="iso"></option></select>
<label data-k="folder"></label><input id="folder" type="text">
<div class="hint" data-k="folder_hint"></div></details>
<div class="bar"><button id="close" data-k="close"></button><button id="go" data-k="make" style="background:var(--orca-accent);color:var(--orca-accent-fg)"></button></div>
<div id="out" class="hide"><div id="msg"></div><code id="path"></code><div class="hint" id="hint"></div>
<div class="bar"><button id="cp" data-k="copy"></button></div></div>
<script>
let S={};
const $=id=>document.getElementById(id);
function texts(){
  document.querySelectorAll("[data-k]").forEach(e=>{if(S[e.dataset.k]!==undefined)e.textContent=S[e.dataset.k];});
  document.querySelectorAll("[data-ph]").forEach(e=>{if(S[e.dataset.ph]!==undefined)e.placeholder=S[e.dataset.ph];});
  sync();
}
function sync(){
  const jar=$("kind").value==="jar", nut=$("kind").value==="nut";
  $("metric").classList.toggle("hide",jar);
  $("diam").classList.toggle("hide",!jar&&$("size").value!=="custom");
  $("lenbox").classList.toggle("hide",nut);
  $("lenlabel").textContent=jar?S.height:S.length;
  const was=$("length").dataset.k;
  if(jar&&was!=="jar"){$("length").value=50;if(+$("diameter").value<30)$("diameter").value=40;}
  if(!jar&&was==="jar"){$("length").value=20;}
  $("length").dataset.k=jar?"jar":"other";
}
orca.onMessage(d=>{
  if(d.type==="init"){S=d.strings;$("folder").value=d.folder;$("clearance").value=d.clearance;$("profile").value=d.profile;texts();}
  if(d.type==="done"){$("out").classList.remove("hide");$("msg").textContent=S.done_text;$("path").textContent=d.path;$("path").classList.remove("hide");
    $("hint").textContent=S.done_hint;$("cp").classList.remove("hide");}
  if(d.type==="error"){$("out").classList.remove("hide");$("msg").textContent=d.text;$("path").classList.add("hide");$("hint").textContent="";$("cp").classList.add("hide");}
  $("go").disabled=false;
});
$("kind").onchange=sync;$("size").onchange=sync;
$("close").onclick=()=>orca.close();
$("cp").onclick=()=>{try{navigator.clipboard.writeText($("path").textContent);$("cp").textContent=S.copied;}catch(e){}};
$("go").onclick=()=>{$("go").disabled=true;orca.postMessage({type:"generate",data:{kind:$("kind").value,size:$("size").value,
  diameter:$("diameter").value,length:$("length").value,pitch:$("pitch").value,clearance:$("clearance").value,
  profile:$("profile").value,folder:$("folder").value}});};
orca.postMessage({type:"ready"});
</script></body></html>"""


def ui_texts(lang):
    """Every text of the page for one language (English fills any gap)."""
    table = dict(MESSAGES["en"])
    table.update(MESSAGES.get(lang) or {})
    return table


# ---------------------------------------------------------------- plugin

class ThreadMaker(orca.script.ScriptPluginCapabilityBase):
    def __init__(self):
        super().__init__()
        self._win = None
        self._token = 0
        self._lang = "en"
        self._folder = ""

    def get_name(self):
        return PLUGIN_NAME

    def get_default_config(self):
        return {"clearance_mm": DEFAULT_CLEARANCE, "profile": DEFAULT_PROFILE}

    def _config(self):
        try:
            cfg = json.loads(self.get_config())
        except Exception:
            cfg = {}
        try:
            clearance = float(cfg.get("clearance_mm", DEFAULT_CLEARANCE))
        except (TypeError, ValueError):
            clearance = DEFAULT_CLEARANCE
        clearance = min(max(clearance, LIMITS["clearance"][0]), LIMITS["clearance"][1])
        profile = cfg.get("profile", DEFAULT_PROFILE)
        return clearance, profile if profile in PROFILES else DEFAULT_PROFILE

    def _default_folder(self):
        return self._folder

    def execute(self):
        try:
            # plugin.storage() only works inside execute() (not in the page's message handler)
            self._folder = os.path.join(str(orca.host.plugin.storage()), "salidas")
            if self._win is not None:
                try:
                    if self._win.is_open():
                        self._win.close()
                except Exception:
                    pass
            self._token += 1
            token = self._token
            self._win = orca.host.ui.create_window(
                html=PAGE_HTML, title=PLUGIN_NAME, width=460, height=620,
                on_message=self._on_message, on_close=lambda *a, t=token: self._on_close(t))
        except Exception as err:  # never let an exception escape into OrcaSlicer
            return orca.ExecutionResult.failure(orca.PluginResult.RecoverableError, str(err))
        return orca.ExecutionResult.success("")

    def _on_close(self, token):
        """Only the current window clears the reference: a late close of an older one is ignored."""
        if token == self._token:
            self._win = None

    def _on_message(self, data):
        """Runs on OrcaSlicer's main thread."""
        win = self._win
        if win is None or not isinstance(data, dict):
            return
        try:
            if data.get("type") == "ready":
                self._lang = detect_lang()
                clearance, profile = self._config()
                win.post({"type": "init", "strings": ui_texts(self._lang),
                          "folder": self._default_folder(), "clearance": clearance, "profile": profile})
            elif data.get("type") == "generate":
                win.post(self._generate(data.get("data")))
        except Exception as err:
            try:
                win.post({"type": "error", "text": str(err)})
            except Exception:
                pass

    def _generate(self, raw):
        lang = self._lang
        try:
            req = sanitize_request(raw, lang)
            folder = str((raw or {}).get("folder") or "").strip() or self._default_folder()
            folder = os.path.expanduser(folder)
            if not os.path.isabs(folder):
                raise ThreadError("folder_relative")
            try:
                path = generate(req, folder, lang)
            except OSError as err:
                raise ThreadError("io", err=err)
        except ThreadError as err:
            return {"type": "error", "text": tr(lang, err.key, **err.fmt)}
        return {"type": "done", "path": path}


@orca.plugin
class ThreadMakerPlugin(orca.base):
    def register_capabilities(self):
        # No permissions requested: by default the file goes to the plugin's own
        # storage folder, which needs none.
        orca.register_capability(ThreadMaker)
