# /// script
# requires-python = ">=3.12"
# dependencies = ["numpy", "manifold3d"]
#
# [tool.orcaslicer.plugin]
# name = "Mold Maker Lío"
# description = "Builds a one-sided silicone mold kit from a part on your plate and saves it as a 3MF to drag onto the plate: base with the model fused to it + removable frame, and tells you how much silicone you need. Kit de molde de silicona en un 3MF para arrastrar a la placa: base con el modelo y marco, y cuánta silicona necesitas. Free and open source by Lío Impresión 3D (lio3d.com)."
# author = "Lío Impresión 3D"
# version = "1.1.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.
"""Mold Maker Lío: turns a part on the plate into a one-sided silicone mold kit.

Kit = "base with model" (plate + ridge + the model really fused to it) and
"frame" (the walls, removable, with a step that seats on the ridge). Both go
into one 3MF that the user drags onto the plate (OrcaSlicer plugins cannot add
objects to the plate). The geometry is plain Python (numpy + manifold3d) with no
dependency on OrcaSlicer, so it is tested on its own.
No network, no telemetry. It reads the selected parts and writes one 3MF into
the plugin's own folder (or one the user types).
"""

import math
import os
import re
import time
import zipfile

import numpy as np
from manifold3d import Manifold, Mesh, OpType

import orca

PLUGIN_NAME = "Mold Maker Lío"

EMBED = 0.2          # mm the model sinks into the base so the union is real
RIDGE_H = 2.0        # mm height of the ridge on the base
SEGMENTS = 96        # segments of a round mold
MAX_TRIANGLES = 2_000_000

DEFAULTS = {
    "shape": "rect",       # "rect" or "round"
    "margin": 10.0,        # mm between model and wall
    "cover": 10.0,         # mm of silicone above the model
    "wall": 2.4,           # mm wall thickness
    "clearance": 0.3,      # mm fit gap frame/base
    "base_thickness": 3.0, # mm
    "density": 1.1,        # g/ml
    "price_per_kg": 0.0,   # any currency; 0 = do not show a cost
}
LIMITS = {
    "margin": (3.0, 60.0),
    "cover": (3.0, 60.0),
    "wall": (2.0, 8.0),
    "clearance": (0.1, 0.8),
    "base_thickness": (1.2, 10.0),
    "density": (0.5, 3.0),
    "price_per_kg": (0.0, 1_000_000_000.0),
}

MESSAGES = {
    "es": {
        "title": "Moldes Lío",
        "pick": "Pieza del molde",
        "shape": "Forma",
        "rect": "Rectangular",
        "round": "Redonda",
        "margin": "Margen alrededor (mm)",
        "cover": "Silicona sobre la pieza (mm)",
        "more": "Más opciones",
        "wall": "Grosor de pared (mm)",
        "clearance": "Holgura del encaje (mm)",
        "base_thickness": "Grosor de la base (mm)",
        "density": "Densidad de la silicona (g/ml)",
        "price": "Precio por kg (opcional, cualquier moneda)",
        "make": "Crear molde",
        "cancel": "Cancelar",
        "hint": "Elige la pieza, crea el molde y arrastra el archivo 3MF a la placa.",
        "no_model": "No hay piezas en la placa. Pon la pieza de la que quieres el molde y vuelve a ejecutar.",
        "nothing": "No elegiste ninguna pieza.",
        "empty": "No pude leer la malla de la pieza.",
        "open": "La pieza no es una malla cerrada. Arréglala en OrcaSlicer (reparar) y vuelve a intentarlo.",
        "big": "La pieza tiene demasiados triángulos para este plugin.",
        "cost": "\nCosto estimado: {cost}",
        "io": "No pude guardar el archivo: {err}",
        "denied": "OrcaSlicer no dio permiso para guardar en esa carpeta; se guardó en la carpeta propia del plugin.",
        "param": "Revisa los valores: {err}",
        "details": "Base: {bw:.0f} x {bd:.0f} x {bh:.1f} mm\nMarco: {fw:.0f} x {fd:.0f} x {fh:.1f} mm\nSilicona: {ml:.0f} ml (unos {g:.0f} g con densidad {dens:g}). Prepara un poco más por el desperdicio.{cost}",
        "folder": "Carpeta donde guardar",
        "folder_hint": "Por defecto es la carpeta propia del plugin. Si eliges otra, OrcaSlicer te pedirá permiso.",
        "done_text": "Molde listo. Archivo guardado en:",
        "done_hint": "Arrástralo a la placa: trae la base con el modelo y el marco.",
        "copy": "Copiar ruta",
        "copied": "Ruta copiada",
        "close": "Cerrar",
        "refresh": "Actualizar lista",
        "base_part": "Base con modelo",
        "frame_part": "Marco",
        "need_folder": "OrcaSlicer no dio una carpeta propia al plugin. Escribe la ruta completa de una carpeta en «Más opciones».",
        "no_host": "No pude leer la placa de OrcaSlicer: {err}",
    },
    "en": {
        "title": "Mold Maker Lío",
        "pick": "Part for the mold",
        "shape": "Shape",
        "rect": "Rectangular",
        "round": "Round",
        "margin": "Margin around (mm)",
        "cover": "Silicone above the part (mm)",
        "more": "More options",
        "wall": "Wall thickness (mm)",
        "clearance": "Fit clearance (mm)",
        "base_thickness": "Base thickness (mm)",
        "density": "Silicone density (g/ml)",
        "price": "Price per kg (optional, any currency)",
        "make": "Create mold",
        "cancel": "Cancel",
        "hint": "Pick the part, create the mold and drag the 3MF file onto the plate.",
        "no_model": "There are no parts on the plate. Add the part you want a mold of and run again.",
        "nothing": "You did not pick any part.",
        "empty": "Could not read the part's mesh.",
        "open": "The part is not a closed mesh. Repair it in OrcaSlicer and try again.",
        "big": "The part has too many triangles for this plugin.",
        "cost": "\nEstimated cost: {cost}",
        "io": "Could not save the file: {err}",
        "denied": "OrcaSlicer did not allow saving to that folder; it was saved in the plugin's own folder.",
        "param": "Check the values: {err}",
        "details": "Base: {bw:.0f} x {bd:.0f} x {bh:.1f} mm\nFrame: {fw:.0f} x {fd:.0f} x {fh:.1f} mm\nSilicone: {ml:.0f} ml (about {g:.0f} g at density {dens:g}). Mix a little extra for waste.{cost}",
        "folder": "Folder to save in",
        "folder_hint": "By default the plugin's own folder. If you pick another one, OrcaSlicer will ask you for permission.",
        "done_text": "Mold ready. File saved to:",
        "done_hint": "Drag it onto the plate: it holds the base with the model and the frame.",
        "copy": "Copy path",
        "copied": "Path copied",
        "close": "Close",
        "refresh": "Refresh list",
        "base_part": "Base with model",
        "frame_part": "Frame",
        "need_folder": "OrcaSlicer gave the plugin no folder of its own. Type the full path of a folder under \"More options\".",
        "no_host": "Could not read the OrcaSlicer plate: {err}",
    },
    "pt": {
        "title": "Moldes Lío",
        "pick": "Peça do molde",
        "shape": "Forma",
        "rect": "Retangular",
        "round": "Redonda",
        "margin": "Margem ao redor (mm)",
        "cover": "Silicone sobre a peça (mm)",
        "more": "Mais opções",
        "wall": "Espessura da parede (mm)",
        "clearance": "Folga do encaixe (mm)",
        "base_thickness": "Espessura da base (mm)",
        "density": "Densidade do silicone (g/ml)",
        "price": "Preço por kg (opcional, qualquer moeda)",
        "make": "Criar molde",
        "cancel": "Cancelar",
        "hint": "Escolha a peça, crie o molde e arraste o arquivo 3MF para a mesa.",
        "no_model": "Não há peças na mesa. Coloque a peça de que quer o molde e execute de novo.",
        "nothing": "Você não escolheu nenhuma peça.",
        "empty": "Não consegui ler a malha da peça.",
        "open": "A peça não é uma malha fechada. Repare no OrcaSlicer e tente de novo.",
        "big": "A peça tem triângulos demais para este plugin.",
        "cost": "\nCusto estimado: {cost}",
        "io": "Não foi possível salvar o arquivo: {err}",
        "denied": "O OrcaSlicer não permitiu salvar nessa pasta; foi salvo na pasta do próprio plugin.",
        "param": "Confira os valores: {err}",
        "details": "Base: {bw:.0f} x {bd:.0f} x {bh:.1f} mm\nMoldura: {fw:.0f} x {fd:.0f} x {fh:.1f} mm\nSilicone: {ml:.0f} ml (uns {g:.0f} g com densidade {dens:g}). Prepare um pouco a mais pelo desperdício.{cost}",
        "folder": "Pasta onde salvar",
        "folder_hint": "Por padrão é a pasta do próprio plugin. Se escolher outra, o OrcaSlicer vai pedir permissão.",
        "done_text": "Molde pronto. Arquivo salvo em:",
        "done_hint": "Arraste para a mesa: traz a base com o modelo e a moldura.",
        "copy": "Copiar caminho",
        "copied": "Caminho copiado",
        "close": "Fechar",
        "refresh": "Atualizar lista",
        "base_part": "Base com modelo",
        "frame_part": "Moldura",
        "need_folder": "O OrcaSlicer não deu uma pasta própria ao plugin. Digite o caminho completo de uma pasta em «Mais opções».",
        "no_host": "Não consegui ler a mesa do OrcaSlicer: {err}",
    },
}


class MoldError(Exception):
    """Expected 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 detect_lang():
    """'es', 'pt' or 'en'. app_info() only works on the main thread: call this from the
    page's message handler. English if the host does not answer."""
    try:
        code = str(orca.host.app_info().get("language") or "").lower()
    except Exception:
        return "en"
    if code.startswith("es"):
        return "es"
    if code.startswith("pt"):
        return "pt"
    return "en"


# ------------------------------------------------------------ parameters

def sanitize_params(raw):
    """Clamp every value to its limits; unknown or bad values fall back to the default."""
    raw = raw if isinstance(raw, dict) else {}
    out = {}
    for key, default in DEFAULTS.items():
        if key == "shape":
            out[key] = raw.get(key) if raw.get(key) in ("rect", "round") else default
            continue
        try:
            v = float(str(raw.get(key, default)).replace(",", "."))
        except (TypeError, ValueError):
            v = default
        if math.isnan(v) or math.isinf(v):
            v = default
        lo, hi = LIMITS[key]
        out[key] = min(hi, max(lo, v))
    # the ridge must keep a usable width: clearance at most a third of the half wall
    out["clearance"] = min(out["clearance"], out["wall"] / 6.0)
    return out


# --------------------------------------------------------------- meshes

def world_vertices(vertices, matrix):
    """Apply a 4x4 matrix (row-vector convention of orca: v' = M @ [v,1])."""
    v = np.asarray(vertices, dtype=np.float64)
    m = np.asarray(matrix, dtype=np.float64)
    return (np.c_[v, np.ones(len(v))] @ m.T)[:, :3]


def manifold_from_arrays(vertices, triangles, mirrored=False):
    """Closed Manifold from a mesh. Raises MoldError('open'/'empty')."""
    tri = np.asarray(triangles, dtype=np.uint32)
    if len(tri) == 0:
        raise MoldError("empty")
    if len(tri) > MAX_TRIANGLES:
        raise MoldError("big")
    if mirrored:
        tri = tri[:, ::-1]
    mesh = Mesh(vert_properties=np.asarray(vertices, dtype=np.float32), tri_verts=np.ascontiguousarray(tri))
    mesh.merge()
    try:
        solid = Manifold(mesh)
    except Exception:
        raise MoldError("open")
    if solid.status().name != "NoError" or solid.is_empty() or solid.volume() <= 0:
        raise MoldError("open")
    return solid


def manifold_to_arrays(solid):
    mesh = solid.to_mesh()
    return (np.asarray(mesh.vert_properties, dtype=np.float64)[:, :3],
            np.asarray(mesh.tri_verts, dtype=np.int64))


# ------------------------------------------------------------- geometry

def build_mold(model, params):
    """model: Manifold in world mm. Returns dict(base, frame, silicone_mm3, ...).

    The base sits with its bottom at z=0 (plate z in 0..base_thickness, model on
    top, sunk EMBED mm into the plate). The frame is returned already flipped
    (rim that touches the base facing up), so it prints standing with no overhang.
    """
    p = sanitize_params(params)
    t, wall, clear = p["base_thickness"], p["wall"], p["clearance"]
    margin, cover = p["margin"], p["cover"]
    half = wall / 2.0

    x0, y0, z0, x1, y1, z1 = model.bounding_box()
    cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0
    placed = model.translate((-cx, -cy, t - EMBED - z0))
    height = (z1 - z0) - EMBED                       # model height above the plate
    fill_h = height + cover                           # silicone / frame height

    if p["shape"] == "round":
        verts, _ = manifold_to_arrays(placed)
        radius = float(np.hypot(verts[:, 0], verts[:, 1]).max()) + margin
        inner_w = inner_d = 2 * radius

        def prism(offset, h, z=0.0):
            return Manifold.cylinder(h, radius + offset, radius + offset, SEGMENTS).translate((0, 0, z))
    else:
        inner_w = (x1 - x0) + 2 * margin
        inner_d = (y1 - y0) + 2 * margin

        def prism(offset, h, z=0.0):
            return Manifold.cube((inner_w + 2 * offset, inner_d + 2 * offset, h), True).translate((0, 0, z + h / 2.0))

    outer = wall
    ridge_w = half - clear
    ridge = prism(ridge_w, RIDGE_H + 0.01, t - 0.01) - prism(0, RIDGE_H + 1, t - 0.5)
    plate = prism(outer, t)
    base = plate + ridge + placed

    rabbet_depth = RIDGE_H + clear
    frame = prism(outer, fill_h) - prism(0, fill_h + 2, -1) - prism(half, rabbet_depth + 1, -1)
    # (the rabbet is a step on the inner side, `half` wide, `rabbet_depth` deep)
    frame = frame.translate((0, 0, t))
    silicone = prism(0, fill_h, t) - placed

    frame_print = frame.rotate((180, 0, 0)).translate((0, 0, fill_h + t))   # flipped: rim up
    bx0, by0, bz0, bx1, by1, bz1 = base.bounding_box()
    fx0, fy0, fz0, fx1, fy1, fz1 = frame_print.bounding_box()
    # side by side on the plate, 10 mm apart, frame to the right of the base
    frame_print = frame_print.translate((bx1 + 10 - fx0, by0 - fy0, -fz0))
    base = base.translate((-bx0, -by0, -bz0))
    frame_print = frame_print.translate((-bx0, -by0, 0))

    return {
        "base": base,
        "frame": frame_print,
        "silicone_mm3": silicone.volume(),
        "model_mm3": placed.volume(),
        "inner": (inner_w, inner_d),
        "fill_height": fill_h,
        "params": p,
    }


def silicone_numbers(silicone_mm3, params):
    ml = silicone_mm3 / 1000.0
    grams = ml * params["density"]
    cost = grams / 1000.0 * params["price_per_kg"] if params["price_per_kg"] > 0 else None
    return ml, grams, cost


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

def _object_xml(oid, name, verts, tris):
    v = "".join('<vertex x="%.5f" y="%.5f" z="%.5f"/>' % tuple(r) for r in verts)
    t = "".join('<triangle v1="%d" v2="%d" v3="%d"/>' % tuple(r) for r in tris)
    return ('<object id="%d" name="%s" type="model"><mesh><vertices>%s</vertices><triangles>%s</triangles></mesh></object>'
            % (oid, name, v, t))


def write_3mf(path, objects):
    """objects: [(name, vertices, triangles)] in mm. Opens the file by path."""
    body = "".join(_object_xml(i + 1, re.sub(r'[<>&"]', "", n), v, t) for i, (n, v, t) in enumerate(objects))
    items = "".join('<item objectid="%d"/>' % (i + 1) for i in range(len(objects)))
    model = ('<?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">Mold Maker Lio</metadata>'
             '<resources>%s</resources><build>%s</build></model>' % (body, items))
    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>')
    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>')
    with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("[Content_Types].xml", types)
        z.writestr("_rels/.rels", rels)
        z.writestr("3D/3dmodel.model", model)


def make_kit(model, params, path, lang="en"):
    """Build and write the kit (part names in `lang`). Returns the stats dict."""
    r = build_mold(model, params)
    objs = []
    for name, key in ((tr(lang, "base_part"), "base"), (tr(lang, "frame_part"), "frame")):
        v, t = manifold_to_arrays(r[key])
        objs.append((name, v, t))
    write_3mf(path, objs)
    ml, grams, cost = silicone_numbers(r["silicone_mm3"], r["params"])
    bb = r["base"].bounding_box()
    fb = r["frame"].bounding_box()
    r.update(ml=ml, grams=grams, cost=cost,
             base_size=(bb[3] - bb[0], bb[4] - bb[1], bb[5] - bb[2]),
             frame_size=(fb[3] - fb[0], fb[4] - fb[1], fb[5] - fb[2]))
    return r


# --------------------------------------------------- reading the plate

def _flag(vol, name):
    """True/False for an attribute or method of the volume; None if it does not exist or fails."""
    if not hasattr(vol, name):
        return None
    flag = getattr(vol, name)
    try:
        return bool(flag() if callable(flag) else flag)
    except Exception:
        return None


_NOT_PARTS = ("is_modifier", "is_negative_volume", "is_support_blocker", "is_support_enforcer")


def _is_model_part(vol):
    """Only a volume that says it is a model part counts (OrcaSlicer 2.5.1 has is_model_part,
    is_modifier, is_negative_volume, is_support_blocker and is_support_enforcer). If the
    attribute does not exist we do not assume it is a part of the model."""
    if _flag(vol, "is_model_part") is not True:
        return False
    return not any(_flag(vol, name) is True for name in _NOT_PARTS)


def object_label(obj, index):
    name = getattr(obj, "name", "") or ""
    return str(name) or "Object %d" % (index + 1)


def collect_model(model, indexes):
    """Union (Manifold) of the chosen objects, every instance, in world mm."""
    solids = []
    objects = list(model.objects())
    for i in indexes:
        obj = objects[i]
        for k in range(len(obj.instances())):
            inst = obj.instance(k)
            for vol in obj.volumes():
                if not _is_model_part(vol):
                    continue
                mesh = vol.mesh()
                if mesh.is_empty():
                    continue
                m = np.asarray(inst.matrix(), dtype=np.float64) @ np.asarray(vol.matrix(), dtype=np.float64)
                mirrored = bool(np.linalg.det(m[:3, :3]) < 0)  # full matrix: instance x volume
                world = world_vertices(np.asarray(mesh.vertices()), m)
                solids.append(manifold_from_arrays(world, np.asarray(mesh.triangles()), mirrored))
    if not solids:
        raise MoldError("empty")
    return solids[0] if len(solids) == 1 else Manifold.batch_boolean(solids, OpType.Add)


def list_objects(model):
    out = []
    for i, obj in enumerate(model.objects()):
        try:
            bb = obj.instance(0).bounding_box() if hasattr(obj.instance(0), "bounding_box") else None
            size = tuple(bb.size) if bb is not None else None
        except Exception:
            size = None
        out.append({"index": i, "name": object_label(obj, i), "size": size})
    return out


# ------------------------------------------------------------------ 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() and the
# model can be read. The page is a plain shell that asks for its texts and the list of
# parts ("ready") and talks to the plugin with messages.
PAGE_HTML = """<!doctype html><html><head><meta charset="utf-8"><style>
body{margin:0;padding:16px;font-family:var(--orca-font);background:var(--orca-bg);color:var(--orca-fg);font-size:13px}
.m{color:var(--orca-muted)}.hint{color:var(--orca-muted);font-size:11px;line-height:1.4;margin-top:4px}
label{display:block;margin:8px 0 2px;color:var(--orca-muted)}label.r{color:var(--orca-fg);margin:3px 0}
input[type=number],input[type=text],select{width:100%;box-sizing:border-box;padding:4px}
input[type=checkbox]{margin-right:6px}
.g{display:grid;grid-template-columns:1fr 1fr;gap:0 12px}details{margin-top:10px}summary{cursor:pointer;color:var(--orca-muted)}
.bar{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
.hide{display:none}
#out{margin-top:14px;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}
#note{white-space:pre-wrap;margin-top:8px}
#msg.bad{border-left:3px solid var(--orca-accent);padding-left:10px;white-space:pre-wrap}
</style></head><body>
<label data-k="pick"></label><div id="rows"></div>
<div class="bar" style="margin-top:4px;justify-content:flex-start"><button id="refresh" data-k="refresh"></button></div>
<div class="g"><div><label data-k="shape"></label><select id="shape"><option value="rect" data-k="rect"></option><option value="round" data-k="round"></option></select></div>
<div><label data-k="margin"></label><input id="margin" type="number" step="1"></div>
<div><label data-k="cover"></label><input id="cover" type="number" step="1"></div>
<div><label data-k="price"></label><input id="price_per_kg" type="number" step="any" min="0"></div></div>
<details><summary data-k="more"></summary><div class="g">
<div><label data-k="wall"></label><input id="wall" type="number" step="0.1"></div>
<div><label data-k="clearance"></label><input id="clearance" type="number" step="0.05"></div>
<div><label data-k="base_thickness"></label><input id="base_thickness" type="number" step="0.5"></div>
<div><label data-k="density"></label><input id="density" type="number" step="0.05"></div></div>
<label data-k="folder"></label><input id="folder" type="text"><div class="hint" data-k="folder_hint"></div></details>
<div class="hint" data-k="hint" style="margin-top:12px"></div>
<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="hintdone"></div><div id="note"></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];});
}
function rows(list){
  const box=$("rows");box.textContent="";
  list.forEach((o,n)=>{
    const l=document.createElement("label");l.className="r";
    const c=document.createElement("input");c.type="checkbox";c.name="obj";c.value=o.index;c.checked=(n===0);
    l.appendChild(c);l.appendChild(document.createTextNode(o.name+" "));
    if(o.size){const s=document.createElement("span");s.className="m";s.textContent=o.size;l.appendChild(s);}
    box.appendChild(l);
  });
}
function fail(text){$("out").classList.remove("hide");$("msg").classList.add("bad");$("msg").textContent=text;
  $("path").classList.add("hide");$("hintdone").textContent="";$("note").textContent="";$("cp").classList.add("hide");}
orca.onMessage(d=>{
  if(d.type==="init"){S=d.strings;texts();rows(d.objects);
    if(!$("shape").dataset.set){$("shape").dataset.set=1;const v=d.defaults;
      ["margin","cover","wall","clearance","base_thickness","density"].forEach(k=>{$(k).value=v[k];});$("folder").value=d.folder;}
    if(!d.folder)$("folder").closest("details").open=true;
    if(d.error)fail(d.error);}
  if(d.type==="done"){$("out").classList.remove("hide");$("msg").classList.remove("bad");$("msg").textContent=S.done_text;
    $("path").textContent=d.path;$("path").classList.remove("hide");$("hintdone").textContent=S.done_hint;
    $("note").textContent=d.note;$("cp").classList.remove("hide");$("cp").textContent=S.copy;}
  if(d.type==="error")fail(d.text);
  $("go").disabled=false;
});
$("close").onclick=()=>orca.close();
$("refresh").onclick=()=>orca.postMessage({type:"ready"});
$("cp").onclick=()=>{try{navigator.clipboard.writeText($("path").textContent);$("cp").textContent=S.copied;}catch(e){}};
$("go").onclick=()=>{$("go").disabled=true;const f={};
  ["shape","margin","cover","wall","clearance","base_thickness","density","price_per_kg","folder"].forEach(k=>{f[k]=$(k).value;});
  f.objects=[].slice.call(document.querySelectorAll("input[name=obj]:checked")).map(e=>+e.value);
  orca.postMessage({type:"generate",data:f});};
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


def output_path(directory, stamp):
    return os.path.join(directory, "molde_%s.3mf" % stamp)


def _size_text(size):
    return "%.0f x %.0f x %.0f mm" % tuple(size) if size else ""


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

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

    def get_name(self):
        return PLUGIN_NAME

    def execute(self):
        try:
            # plugin.storage() only works inside execute() (not in the page's message handler);
            # it lives in the plugin's data folder, so writing there asks for no permission.
            # Without an Orca Cloud session it can fail: the window still opens and asks for a folder.
            try:
                self._folder = os.path.join(str(orca.host.plugin.storage()), "salidas")
            except Exception:
                self._folder = ""
            try:  # fallback in case the model cannot be read from the message handler
                self._exec_model = orca.host.model()
            except Exception:
                self._exec_model = None
            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=480, height=680,
                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 _read_model(self):
        """The plate is re-read every time (main thread); the snapshot from execute() is a fallback."""
        try:
            return orca.host.model()
        except Exception:
            if self._exec_model is not None:
                return self._exec_model
            raise

    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()
                win.post(self._init_message())
            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 _init_message(self):
        lang = self._lang
        msg = {"type": "init", "strings": ui_texts(lang), "folder": self._folder,
               "defaults": {k: DEFAULTS[k] for k in ("margin", "cover", "wall", "clearance",
                                                      "base_thickness", "density")},
               "objects": [], "error": ""}
        try:
            objects = list_objects(self._read_model())
        except Exception as err:
            msg["error"] = tr(lang, "no_host", err=err)
            return msg
        msg["objects"] = [{"index": o["index"], "name": o["name"], "size": _size_text(o["size"])}
                          for o in objects]
        if not objects:
            msg["error"] = tr(lang, "no_model")
        elif not self._folder:
            msg["error"] = tr(lang, "need_folder")
        return msg

    def _generate(self, raw):
        lang = self._lang
        raw = raw if isinstance(raw, dict) else {}
        try:
            model = self._read_model()
            count = len(list(model.objects()))
            if count == 0:
                raise MoldError("no_model")
            chosen = []
            for i in raw.get("objects") or []:
                try:
                    i = int(i)
                except (TypeError, ValueError):
                    continue
                if 0 <= i < count and i not in chosen:
                    chosen.append(i)
            if not chosen:
                raise MoldError("nothing")
            params = sanitize_params(raw)
            solid = collect_model(model, chosen)
            stamp = time.strftime("%Y%m%d_%H%M%S")
            note = ""
            directory = os.path.expanduser(str(raw.get("folder") or "").strip() or self._folder)
            if not directory or not os.path.isabs(directory):
                raise MoldError("need_folder")
            try:
                os.makedirs(directory, exist_ok=True)
                path = output_path(directory, stamp)
                stats = make_kit(solid, params, path, lang)
            except PermissionError:
                if directory == self._folder or not self._folder:
                    raise
                directory = self._folder
                os.makedirs(directory, exist_ok=True)
                path = output_path(directory, stamp)
                stats = make_kit(solid, params, path, lang)
                note = "\n\n" + tr(lang, "denied")
        except MoldError as err:
            return {"type": "error", "text": tr(lang, err.key, **err.fmt)}
        except OSError as exc:
            return {"type": "error", "text": tr(lang, "io", err=exc)}
        cost = tr(lang, "cost", cost="%.2f" % stats["cost"]) if stats["cost"] is not None else ""
        bw, bd, bh = stats["base_size"]
        fw, fd, fh = stats["frame_size"]
        text = tr(lang, "details", bw=bw, bd=bd, bh=bh, fw=fw, fd=fd, fh=fh, ml=stats["ml"],
                  g=stats["grams"], dens=stats["params"]["density"], cost=cost) + note
        return {"type": "done", "path": path, "note": text}


@orca.plugin
class MoldMakerLio(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(MoldMaker)
