# /// script
# requires-python = ">=3.12"
# dependencies = ["segno", "manifold3d", "numpy"]
#
# [tool.orcaslicer.plugin]
# name = "QR Lío"
# description = "Two-color QR plate for the AMS (link, Wi-Fi or WhatsApp): saves a 3MF with the base and the QR as separate parts, filaments 1 and 2 already assigned. Placa QR en dos colores para el AMS. 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.
"""QR Lío: builds a two-color QR plate (base + raised QR modules) and saves it
as a 3MF with two parts, ready to drag onto the OrcaSlicer plate.

orca.host is read-only (no way to add objects to the plate), so the plugin
saves the file to a fixed folder and tells the user where it is.

The QR, geometry and 3MF logic are plain functions with no OrcaSlicer
dependency, so they can be tested on their own. No network, no telemetry, and
no files other than the 3MF it writes in its own folder.
"""

import math
import os
import re
import zipfile
from xml.sax.saxutils import escape

import orca

PLUGIN_NAME = "QR Lío"

BASE_H = 2.4          # mm, light base
RELIEF_H = 0.8        # mm, QR modules on top
QUIET_MODULES = 4     # quiet zone around the code, in modules
WARN_MODULE_MM = 1.2  # below this the code is hard to print and to scan
MIN_MODULE_MM = 0.8   # below this we refuse (2 nozzle widths of 0.4)
SIZE_MIN, SIZE_MAX, SIZE_DEFAULT = 25.0, 150.0, 50.0
MAX_TEXT = 600
SSID_MAX_BYTES = 32  # the Wi-Fi standard limit
TAB_RADIUS, HOLE_RADIUS, TAB_OFFSET = 5.0, 2.25, 3.0  # keyring tab, mm
EPS = 0.01            # mm, makes diagonal neighbours overlap (always manifold)

DEFAULTS = {
    "kind": "link",        # link | wifi | whatsapp
    "text": "",
    "ssid": "",
    "password": "",
    "security": "WPA",     # WPA | WEP | nopass
    "phone": "",
    "size": SIZE_DEFAULT,
    "ecc": "M",            # M | H
    "hole": False,
}

MESSAGES = {
    "es": {
        "title": "QR Lío",
        "folder": "Carpeta donde guardar",
        "folder_hint": "Por defecto es la carpeta propia del plugin. Si eliges otra, OrcaSlicer te pedirá permiso.",
        "done_text": "Listo. Archivo guardado en:",
        "done_hint": "Arrastra el archivo a la placa de OrcaSlicer. El QR ya está en el filamento 2 y la base en el filamento 1.",
        "copy": "Copiar ruta",
        "copied": "Ruta copiada",
        "close": "Cerrar",
        "module_line": "Módulo: {m:.2f} mm.",
        "kind": "Qué quieres poner en el QR",
        "k_link": "Enlace o texto",
        "k_wifi": "Wi-Fi",
        "k_whatsapp": "WhatsApp",
        "text": "Enlace o texto",
        "text_ph": "https://example.com",
        "ssid": "Nombre de la red",
        "password": "Clave",
        "security": "Tipo de seguridad",
        "s_wpa": "WPA / WPA2 / WPA3",
        "s_wep": "WEP",
        "s_nopass": "Sin clave",
        "phone": "Número con indicativo",
        "phone_ph": "573001234567",
        "size": "Tamaño de la placa (mm)",
        "ecc": "Corrección de errores",
        "ecc_m": "M (recomendada)",
        "ecc_h": "H (más resistente, más módulos)",
        "hole": "Agujero para llavero",
        "create": "Crear placa",
        "cancel": "Cancelar",
        "hint": "Se guarda un 3MF con la base y el QR como partes separadas (filamento 1 y 2).",
        "err_text": "Escribe el enlace o el texto.",
        "err_ssid": "Escribe el nombre de la red.",
        "err_phone": "Escribe el número con indicativo del país, solo dígitos (de 7 a 15).",
        "err_size": "El tamaño debe estar entre {lo} y {hi} mm.",
        "err_long": "El texto es demasiado largo (máximo {n} caracteres).",
        "err_overflow": "El contenido no cabe en un código QR. Acórtalo.",
        "err_small": "Cada módulo del QR mediría {m:.2f} mm, demasiado pequeño para imprimirlo. Agranda la placa o acorta el texto.",
        "err_ssid_long": "El nombre de la red es demasiado largo: el Wi-Fi permite hasta 32 bytes (unos 32 caracteres sin tildes).",
        "err_password": "Escribe la clave de la red o elige «Sin clave».",
        "need_folder": "OrcaSlicer no dio una carpeta propia al plugin. Escribe la ruta completa de una carpeta.",
        "n_link": "enlace",
        "n_wifi": "wifi",
        "n_whatsapp": "whatsapp",
        "err_io": "No se pudo guardar el archivo: {err}",
        "warn_small": "Aviso: cada módulo mide {m:.2f} mm (lo recomendado es {w:.1f} mm o más). Agranda la placa o acorta el texto para que escanee bien.",
        "ok": "Listo: {path}\nArrastra el archivo a la placa de OrcaSlicer. El QR ya está en el filamento 2 y la base en el filamento 1. Módulo: {m:.2f} mm.",
        "ok_short": "Placa guardada en {path}",
    },
    "en": {
        "title": "QR Lío",
        "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": "Done. File saved to:",
        "done_hint": "Drag the file onto the OrcaSlicer plate. The QR is already on filament 2 and the base on filament 1.",
        "copy": "Copy path",
        "copied": "Path copied",
        "close": "Close",
        "module_line": "Module: {m:.2f} mm.",
        "kind": "What goes in the QR",
        "k_link": "Link or text",
        "k_wifi": "Wi-Fi",
        "k_whatsapp": "WhatsApp",
        "text": "Link or text",
        "text_ph": "https://example.com",
        "ssid": "Network name",
        "password": "Password",
        "security": "Security type",
        "s_wpa": "WPA / WPA2 / WPA3",
        "s_wep": "WEP",
        "s_nopass": "No password",
        "phone": "Number with country code",
        "phone_ph": "573001234567",
        "size": "Plate size (mm)",
        "ecc": "Error correction",
        "ecc_m": "M (recommended)",
        "ecc_h": "H (more robust, more modules)",
        "hole": "Keyring hole",
        "create": "Create plate",
        "cancel": "Cancel",
        "hint": "Saves a 3MF with the base and the QR as separate parts (filament 1 and 2).",
        "err_text": "Type the link or the text.",
        "err_ssid": "Type the network name.",
        "err_phone": "Type the number with country code, digits only (7 to 15).",
        "err_size": "The size must be between {lo} and {hi} mm.",
        "err_long": "The text is too long (maximum {n} characters).",
        "err_overflow": "The content does not fit in a QR code. Make it shorter.",
        "err_small": "Each QR module would be {m:.2f} mm, too small to print. Make the plate bigger or the text shorter.",
        "err_ssid_long": "The network name is too long: Wi-Fi allows up to 32 bytes (about 32 plain characters).",
        "err_password": "Type the network password or choose \"No password\".",
        "need_folder": "OrcaSlicer gave the plugin no folder of its own. Type the full path of a folder.",
        "n_link": "link",
        "n_wifi": "wifi",
        "n_whatsapp": "whatsapp",
        "err_io": "Could not save the file: {err}",
        "warn_small": "Warning: each module is {m:.2f} mm (recommended {w:.1f} mm or more). Make the plate bigger or the text shorter so it scans well.",
        "ok": "Done: {path}\nDrag the file onto the OrcaSlicer plate. The QR is already on filament 2 and the base on filament 1. Module: {m:.2f} mm.",
        "ok_short": "Plate saved to {path}",
    },
    "pt": {
        "title": "QR Lío",
        "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": "Pronto. Arquivo salvo em:",
        "done_hint": "Arraste o arquivo para a mesa do OrcaSlicer. O QR já está no filamento 2 e a base no filamento 1.",
        "copy": "Copiar caminho",
        "copied": "Caminho copiado",
        "close": "Fechar",
        "module_line": "Módulo: {m:.2f} mm.",
        "kind": "O que vai no QR",
        "k_link": "Link ou texto",
        "k_wifi": "Wi-Fi",
        "k_whatsapp": "WhatsApp",
        "text": "Link ou texto",
        "text_ph": "https://example.com",
        "ssid": "Nome da rede",
        "password": "Senha",
        "security": "Tipo de segurança",
        "s_wpa": "WPA / WPA2 / WPA3",
        "s_wep": "WEP",
        "s_nopass": "Sem senha",
        "phone": "Número com código do país",
        "phone_ph": "573001234567",
        "size": "Tamanho da placa (mm)",
        "ecc": "Correção de erros",
        "ecc_m": "M (recomendada)",
        "ecc_h": "H (mais resistente, mais módulos)",
        "hole": "Furo para chaveiro",
        "create": "Criar placa",
        "cancel": "Cancelar",
        "hint": "Salva um 3MF com a base e o QR como partes separadas (filamento 1 e 2).",
        "err_text": "Escreva o link ou o texto.",
        "err_ssid": "Escreva o nome da rede.",
        "err_phone": "Escreva o número com código do país, só dígitos (de 7 a 15).",
        "err_size": "O tamanho deve ficar entre {lo} e {hi} mm.",
        "err_long": "O texto é longo demais (máximo {n} caracteres).",
        "err_overflow": "O conteúdo não cabe em um código QR. Encurte-o.",
        "err_small": "Cada módulo do QR mediria {m:.2f} mm, pequeno demais para imprimir. Aumente a placa ou encurte o texto.",
        "err_ssid_long": "O nome da rede é longo demais: o Wi-Fi permite até 32 bytes (cerca de 32 caracteres sem acentos).",
        "err_password": "Escreva a senha da rede ou escolha «Sem senha».",
        "need_folder": "O OrcaSlicer não deu uma pasta própria ao plugin. Digite o caminho completo de uma pasta.",
        "n_link": "link",
        "n_wifi": "wifi",
        "n_whatsapp": "whatsapp",
        "err_io": "Não foi possível salvar o arquivo: {err}",
        "warn_small": "Aviso: cada módulo mede {m:.2f} mm (o recomendado é {w:.1f} mm ou mais). Aumente a placa ou encurte o texto para escanear bem.",
        "ok": "Pronto: {path}\nArraste o arquivo para a mesa do OrcaSlicer. O QR já está no filamento 2 e a base no filamento 1. Módulo: {m:.2f} mm.",
        "ok_short": "Placa salva em {path}",
    },
}


class QrError(Exception):
    """A problem the user can fix. `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"


# ---------------------------------------------------------------- content

def escape_wifi(value):
    """Escapes the characters the WIFI: format reserves: \\ ; , : and "."""
    return re.sub(r'([\\;,:"])', r"\\\1", value)


def wifi_payload(ssid, password, security="WPA"):
    if not ssid:
        raise QrError("err_ssid")
    if len(ssid.encode("utf-8")) > SSID_MAX_BYTES:
        raise QrError("err_ssid_long")
    if security not in ("WPA", "WEP", "nopass"):
        security = "WPA"
    if security != "nopass" and not password:
        raise QrError("err_password")
    if security == "nopass":
        return f"WIFI:T:nopass;S:{escape_wifi(ssid)};;"
    return f"WIFI:T:{security};S:{escape_wifi(ssid)};P:{escape_wifi(password)};;"


def whatsapp_payload(phone):
    digits = re.sub(r"\D", "", str(phone or ""))
    if not 7 <= len(digits) <= 15:
        raise QrError("err_phone")
    return f"https://wa.me/{digits}"


_DOMAIN = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+([a-z]{2,})([/?#:]\S*)?$", re.I)

# Text such as "Juan.Perez" is not a link: only a known ending (or a path after it) makes it one.
KNOWN_TLDS = frozenset("""com net org edu gov mil int info biz name pro app dev io co me tv ly cc
ai shop store online site website tech xyz page blog link live cloud design art studio agency
space club fun top vip one bio ink wiki news media email world life life today works
ar bo br cl cr cu do ec es gt hn mx ni pa pe pr py sv uy ve us ca uk de fr it pt nl be ch at se no
dk fi ie pl cz ru ua tr gr ro hu bg jp cn kr in au nz za ng eg ma ae sa il id my sg th vn ph""".split())


def link_payload(text):
    text = str(text or "").strip()
    if not text:
        raise QrError("err_text")
    if len(text) > MAX_TEXT:
        raise QrError("err_long", n=MAX_TEXT)
    if "://" not in text:
        m = _DOMAIN.match(text)
        if m and (m.group(1).lower() in KNOWN_TLDS or (m.group(2) or "").startswith("/")):
            return "https://" + text  # "example.com" -> "https://example.com"
    return text


def build_payload(cfg):
    kind = cfg.get("kind")
    if kind == "wifi":
        return wifi_payload(str(cfg.get("ssid", "")), str(cfg.get("password", "")), cfg.get("security", "WPA"))
    if kind == "whatsapp":
        return whatsapp_payload(cfg.get("phone", ""))
    return link_payload(cfg.get("text", ""))


def sanitize_config(raw):
    """Safe values from whatever the form sent."""
    cfg = dict(DEFAULTS)
    if isinstance(raw, dict):
        cfg.update({k: raw[k] for k in DEFAULTS if k in raw})
    if cfg["kind"] not in ("link", "wifi", "whatsapp"):
        cfg["kind"] = "link"
    if cfg["security"] not in ("WPA", "WEP", "nopass"):
        cfg["security"] = "WPA"
    if cfg["ecc"] not in ("M", "H"):
        cfg["ecc"] = "M"
    try:
        size = float(cfg["size"])
        if math.isnan(size):
            raise ValueError
    except (TypeError, ValueError):
        raise QrError("err_size", lo=SIZE_MIN, hi=SIZE_MAX)
    if not SIZE_MIN <= size <= SIZE_MAX:
        raise QrError("err_size", lo=SIZE_MIN, hi=SIZE_MAX)
    cfg["size"] = size
    cfg["hole"] = bool(cfg["hole"])
    for key in ("text", "ssid", "password", "phone"):
        cfg[key] = str(cfg[key] if cfg[key] is not None else "")
    return cfg


def qr_matrix(payload, ecc="M"):
    """Rows of 0/1 (1 = dark module), without quiet zone."""
    import segno

    try:
        qr = segno.make(payload, error=ecc.lower(), micro=False, boost_error=False, encoding="utf-8")
    except Exception as exc:  # segno.DataOverflowError and friends
        raise QrError("err_overflow") from exc
    return [[1 if v else 0 for v in row] for row in qr.matrix]


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

def merge_rectangles(matrix):
    """Greedy merge of dark modules into rectangles (col, row, width, height),
    so we do not make one cube per module."""
    open_rects = {}  # (col, width) -> [col, row0, width, height]
    done = []
    for r, row in enumerate(matrix):
        runs = []
        c = 0
        while c < len(row):
            if row[c]:
                start = c
                while c < len(row) and row[c]:
                    c += 1
                runs.append((start, c - start))
            else:
                c += 1
        current = {}
        for run in runs:
            if run in open_rects:
                rect = open_rects.pop(run)
                rect[3] += 1
                current[run] = rect
            else:
                current[run] = [run[0], r, run[1], 1]
        done.extend(open_rects.values())
        open_rects = current
    done.extend(open_rects.values())
    return [tuple(rect) for rect in done]


def module_size_mm(matrix, size):
    return size / (len(matrix) + 2 * QUIET_MODULES)


def plate_dimensions(size, hole):
    """(width, height) of the base in mm."""
    return size, size + (TAB_OFFSET + TAB_RADIUS if hole else 0.0)


def build_meshes(matrix, size, hole=False):
    """Returns (base, modules): each is (vertices Nx3, triangles Mx3) in mm.
    The plate square is centered on x/y = 0; the bottom is at z = 0."""
    import numpy as np
    from manifold3d import CrossSection, JoinType, Manifold, OpType

    mod = module_size_mm(matrix, size)
    radius = min(4.0, 0.1 * size)
    inner = size - 2 * radius
    outline = CrossSection.square((inner, inner)).translate((radius, radius))
    outline = outline.offset(radius, JoinType.Round, 2.0, 48)
    if hole:
        cx, cy = size / 2.0, size + TAB_OFFSET
        outline = outline + CrossSection.circle(TAB_RADIUS, 48).translate((cx, cy))
        outline = outline - CrossSection.circle(HOLE_RADIUS, 32).translate((cx, cy))
    base = Manifold.extrude(outline, BASE_H)

    n = len(matrix)
    rects = []
    for col, row, w, h in merge_rectangles(matrix):
        x0 = (QUIET_MODULES + col) * mod
        y1 = size - (QUIET_MODULES + row) * mod
        x1 = x0 + w * mod
        y0 = y1 - h * mod
        rects.append(
            CrossSection.square((x1 - x0 + 2 * EPS, y1 - y0 + 2 * EPS)).translate((x0 - EPS, y0 - EPS))
        )
    modules = Manifold.extrude(CrossSection.batch_boolean(rects, OpType.Add), RELIEF_H)
    modules = modules.translate((0, 0, BASE_H))

    shift = (-size / 2.0, -size / 2.0, 0.0)
    out = []
    for solid in (base, modules):
        solid = solid.translate(shift)
        mesh = solid.to_mesh()
        out.append((np.asarray(mesh.vert_properties, dtype=float)[:, :3], np.asarray(mesh.tri_verts, dtype=int)))
    return out[0], out[1]


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

def _mesh_xml(object_id, name, vertices, triangles):
    v = "\n".join(f'    <vertex x="{x:.5f}" y="{y:.5f}" z="{z:.5f}"/>' for x, y, z in vertices)
    t = "\n".join(f'    <triangle v1="{a}" v2="{b}" v3="{c}"/>' for a, b, c in triangles)
    return (
        f'  <object id="{object_id}" name="{escape(name)}" type="model">\n'
        f"   <mesh>\n   <vertices>\n{v}\n   </vertices>\n   <triangles>\n{t}\n   </triangles>\n   </mesh>\n"
        f"  </object>\n"
    )


def build_3mf(base, modules, name="QR"):
    """Bytes of a 3MF: one object (id 3) with two parts, Base (filament 1) and
    QR (filament 2), in the layout OrcaSlicer and Bambu Studio write."""
    safe = escape(name)
    model = (
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<model unit="millimeter" xml:lang="en-US" '
        'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" '
        'xmlns:BambuStudio="http://schemas.bambulab.com/package/2021">\n'
        ' <metadata name="Application">QR Lio plugin</metadata>\n'
        ' <metadata name="BambuStudio:3mfVersion">1</metadata>\n'
        f' <metadata name="Title">{safe}</metadata>\n'
               " <resources>\n"
        + _mesh_xml(1, "Base", *base)
        + _mesh_xml(2, "QR", *modules)
        + '  <object id="3" type="model">\n   <components>\n'
        '    <component objectid="1"/>\n    <component objectid="2"/>\n'
        "   </components>\n  </object>\n"
        " </resources>\n"
        ' <build>\n  <item objectid="3" printable="1"/>\n </build>\n'
        "</model>\n"
    )
    settings = (
        '<?xml version="1.0" encoding="UTF-8"?>\n<config>\n'
        '  <object id="3">\n'
        f'    <metadata key="name" value="{safe}"/>\n'
        '    <metadata key="extruder" value="1"/>\n'
        '    <part id="1" subtype="normal_part">\n'
        '      <metadata key="name" value="Base"/>\n'
        '      <metadata key="matrix" value="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1"/>\n'
        '      <metadata key="extruder" value="1"/>\n'
        "    </part>\n"
        '    <part id="2" subtype="normal_part">\n'
        '      <metadata key="name" value="QR"/>\n'
        '      <metadata key="matrix" value="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1"/>\n'
        '      <metadata key="extruder" value="2"/>\n'
        "    </part>\n"
        "  </object>\n</config>\n"
    )
    content_types = (
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n'
        ' <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\n'
        ' <Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>\n'
        ' <Default Extension="config" ContentType="text/xml"/>\n'
        "</Types>\n"
    )
    rels = (
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n'
        ' <Relationship Target="/3D/3dmodel.model" Id="rel-1" '
        'Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>\n'
        "</Relationships>\n"
    )
    import io

    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("[Content_Types].xml", content_types)
        z.writestr("_rels/.rels", rels)
        z.writestr("3D/3dmodel.model", model)
        z.writestr("Metadata/model_settings.config", settings)
    return buf.getvalue()


# ---------------------------------------------------------------- build

def make_plate(cfg, lang="en"):
    """Everything except saving. Returns dict(data, module_mm, warn, payload, name)."""
    cfg = sanitize_config(cfg)
    payload = build_payload(cfg)
    matrix = qr_matrix(payload, cfg["ecc"])
    mod = module_size_mm(matrix, cfg["size"])
    if mod < MIN_MODULE_MM:
        raise QrError("err_small", m=mod)
    base, modules = build_meshes(matrix, cfg["size"], cfg["hole"])
    name = f"QR {tr(lang, 'n_' + cfg['kind'])} {cfg['size']:g}mm"
    return {
        "data": build_3mf(base, modules, name),
        "module_mm": mod,
        "warn": mod < WARN_MODULE_MM,
        "payload": payload,
        "name": name,
        "modules": len(matrix),
    }


def file_name(cfg, folder):
    base = f"QR-{cfg['kind']}-{cfg['size']:g}mm"
    path = os.path.join(folder, base + ".3mf")
    n = 2
    while os.path.exists(path):
        path = os.path.join(folder, f"{base}-{n}.3mf")
        n += 1
    return path


def save_plate(cfg, folder, lang="en"):
    """Builds and writes the 3MF (opened by path). Returns (path, result)."""
    cfg = sanitize_config(cfg)
    result = make_plate(cfg, lang)
    try:
        if not os.path.isdir(folder):
            os.makedirs(folder)
        path = file_name(cfg, folder)
        with open(path, "wb") as fh:
            fh.write(result["data"])
    except OSError as exc:
        raise QrError("err_io", err=exc) from exc
    return path, result


# ---------------------------------------------------------------- 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). 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:16px 18px;font-family:var(--orca-font);background:var(--orca-bg);color:var(--orca-fg);font-size:13px}
label{display:block;color:var(--orca-muted);margin:12px 0 4px}
input[type=text],input[type=number],select{width:100%;box-sizing:border-box;padding:6px 8px}
.check{display:flex;gap:8px;align-items:center;margin-top:14px}
.check input{margin:0}
.hint{color:var(--orca-muted);margin-top:6px;font-size:11px;line-height:1.4}
.bar{display:flex;gap:10px;justify-content:flex-end;margin-top:16px}
.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}
#msg.bad{border-left:3px solid var(--orca-accent);padding-left:10px;white-space:pre-wrap}
</style></head><body>
<label data-k="kind" style="margin-top:0"></label>
<select id="kind"><option value="link" data-k="k_link"></option><option value="wifi" data-k="k_wifi"></option><option value="whatsapp" data-k="k_whatsapp"></option></select>
<div id="p_link"><label data-k="text"></label><input type="text" id="text" data-ph="text_ph"></div>
<div id="p_wifi" class="hide">
<label data-k="ssid"></label><input type="text" id="ssid">
<label data-k="password"></label><input type="text" id="password">
<label data-k="security"></label><select id="security"><option value="WPA" data-k="s_wpa"></option><option value="WEP" data-k="s_wep"></option><option value="nopass" data-k="s_nopass"></option></select>
</div>
<div id="p_whatsapp" class="hide"><label data-k="phone"></label><input type="text" id="phone" data-ph="phone_ph"></div>
<label data-k="size"></label><input type="number" id="size" min="25" max="150" step="1" value="50">
<label data-k="ecc"></label><select id="ecc"><option value="M" data-k="ecc_m"></option><option value="H" data-k="ecc_h"></option></select>
<div class="check"><input type="checkbox" id="hole"><span data-k="hole"></span></div>
<label data-k="folder"></label><input type="text" id="folder">
<div class="hint" data-k="folder_hint"></div>
<div class="hint" data-k="hint"></div>
<div class="bar"><button id="close" data-k="close"></button><button id="go" data-k="create" 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="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];});
  document.querySelectorAll("[data-ph]").forEach(e=>{if(S[e.dataset.ph]!==undefined)e.placeholder=S[e.dataset.ph];});
}
function show(){const k=$("kind").value;["link","wifi","whatsapp"].forEach(n=>$("p_"+n).classList.toggle("hide",n!==k));}
orca.onMessage(d=>{
  if(d.type==="init"){S=d.strings;$("folder").value=d.folder;$("size").value=d.size;texts();show();}
  if(d.type==="done"){$("out").classList.remove("hide");$("msg").textContent=S.done_text;$("path").textContent=d.path;$("path").classList.remove("hide");
    $("note").textContent=d.note;$("cp").classList.remove("hide");$("cp").textContent=S.copy;$("msg").classList.remove("bad");}
  if(d.type==="error"){$("out").classList.remove("hide");$("msg").classList.add("bad");$("msg").textContent=d.text;$("path").classList.add("hide");$("note").textContent="";$("cp").classList.add("hide");}
  $("go").disabled=false;
});
$("kind").onchange=show;
$("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,text:$("text").value,
  ssid:$("ssid").value,password:$("password").value,security:$("security").value,phone:$("phone").value,
  size:parseFloat($("size").value),ecc:$("ecc").value,hole:$("hole").checked,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 QrMaker(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 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 = ""
            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=700,
                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()
                win.post({"type": "init", "strings": ui_texts(self._lang),
                          "folder": self._folder, "size": SIZE_DEFAULT})
                if not self._folder:
                    win.post({"type": "error", "text": tr(self._lang, "need_folder")})
            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:
            raw = raw if isinstance(raw, dict) else {}
            folder = os.path.expanduser(str(raw.get("folder") or "").strip() or self._folder)
            if not folder or not os.path.isabs(folder):
                raise QrError("need_folder")
            path, result = save_plate(raw, folder, lang)
        except QrError as err:
            return {"type": "error", "text": tr(lang, err.key, **err.fmt)}
        note = tr(lang, "done_hint") + " " + tr(lang, "module_line", m=result["module_mm"])
        if result["warn"]:
            note = tr(lang, "warn_small", m=result["module_mm"], w=WARN_MODULE_MM) + "\n\n" + note
        return {"type": "done", "path": path, "note": note}


@orca.plugin
class QrLio(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(QrMaker)
