# /// script
# dependencies = []
#
# [tool.orcaslicer.plugin]
# name = "Wood Grain Lío"
# description = "Wood-grain stripes in wood-filled PLA: varies the nozzle temperature layer by layer (hotter = darker). 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.
"""Wood Grain Lío: post-processes the exported G-code and changes the nozzle
temperature layer by layer so wood-filled PLA shows grain stripes.

The G-code logic (layer detection, temperatures, rewriting) is plain Python
with no dependency on OrcaSlicer, so it can be tested on its own.
No network, no telemetry, no files other than the G-code being exported.
"""

import json
import math
import os
import re

import orca

PLUGIN_NAME = "Wood Grain Lío"
TAG = "; lio_vetas"  # marks the lines we add, so we never process twice
SEED = 20261115  # fixed: the same model always gets the same grain

DEFAULT_CONFIG = {
    "intensity": 70,         # % of the temperature span used (0-100)
    "grain_width_mm": 2.0,   # width of the stripes along Z, in mm
    "rings_percent": 0,      # 0 = only soft noise, 100 = only regular rings
    "skip_first_layers": 3,  # layers left exactly as the slicer wrote them
    "temp_min": 0,           # 0 = automatic (inside the filament range)
    "temp_max": 0,           # 0 = automatic (never above the filament max)
}

MIN_STEP_C = 1.0          # do not write a command if the change is smaller
AUTO_BELOW_C = 15         # automatic minimum: nominal temperature - 15
AUTO_ABOVE_C = 10         # automatic maximum: nominal temperature + 10
NO_RANGE_BELOW_C = 20     # if the profile has no range: nominal - 20 ...
USER_SPAN_C = 25            # with only one limit from the user, the other is 25 C away
NO_RANGE_ABOVE_C = 10     # ... and never more than nominal + 10

MESSAGES = {
    "es": {
        "ok": "Vetas aplicadas: {n} cambios de temperatura ({lo}-{hi} °C).",
        "clip": "Se ajustó {what} a {val} °C para respetar el rango del filamento ({lo}-{hi} °C).",
        "no_layers": "No reconozco el formato del G-code (no hay cambios de capa). Archivo sin cambios.",
        "no_temp": "No pude leer la temperatura ni el rango del filamento. Archivo sin cambios.",
        "narrow": "El rango de temperatura del filamento es demasiado estrecho para hacer vetas. Archivo sin cambios.",
        "badrange": "Tu temperatura mínima y máxima no dejan al menos 2 °C de diferencia dentro del rango del filamento ({lo}-{hi} °C). Archivo sin cambios.",
        "off": "Vetas apagadas (intensidad 0). Archivo sin cambios.",
        "none": "No hizo falta cambiar la temperatura (rango {lo}-{hi} °C). Archivo sin cambios.",
        "multi": "Hay varios filamentos o cambios de herramienta (AMS). Este plugin solo trabaja con un filamento. Archivo sin cambios.",
        "other_filament": "Se usa un solo filamento, pero no es el de las temperaturas leídas del perfil. Archivo sin cambios.",
        "by_object": "La impresión es objeto por objeto (la altura Z vuelve a bajar). Archivo sin cambios.",
        "done_before": "Este G-code ya tiene vetas aplicadas. Archivo sin cambios.",
        "few": "Hay muy pocas capas después de las {skip} primeras. Archivo sin cambios.",
        "io": "No se pudo escribir el G-code: {err}. Archivo sin cambios.",
        "min": "temperatura mínima",
        "max": "temperatura máxima",
    },
    "en": {
        "ok": "Wood grain applied: {n} temperature changes ({lo}-{hi} C).",
        "clip": "Adjusted {what} to {val} C to stay inside the filament range ({lo}-{hi} C).",
        "no_layers": "Unrecognized G-code format (no layer changes found). File left unchanged.",
        "no_temp": "Could not read the filament temperature or range. File left unchanged.",
        "narrow": "The filament temperature range is too narrow for wood grain. File left unchanged.",
        "badrange": "Your minimum and maximum temperatures leave less than 2 C of difference inside the filament range ({lo}-{hi} C). File left unchanged.",
        "off": "Wood grain is off (intensity 0). File left unchanged.",
        "none": "No temperature change was needed (range {lo}-{hi} C). File left unchanged.",
        "multi": "Several filaments or tool changes (AMS) found. This plugin only works with one filament. File left unchanged.",
        "other_filament": "Only one filament is used, but it is not the one whose temperatures were read from the profile. File left unchanged.",
        "by_object": "Print is object by object (Z goes back down). File left unchanged.",
        "done_before": "This G-code already has wood grain applied. File left unchanged.",
        "few": "Too few layers after the first {skip}. File left unchanged.",
        "io": "Could not write the G-code: {err}. File left unchanged.",
        "min": "minimum temperature",
        "max": "maximum temperature",
    },
    "pt": {
        "ok": "Veios aplicados: {n} mudanças de temperatura ({lo}-{hi} °C).",
        "clip": "Ajustei {what} para {val} °C para respeitar a faixa do filamento ({lo}-{hi} °C).",
        "no_layers": "Não reconheço o formato do G-code (sem trocas de camada). Arquivo inalterado.",
        "no_temp": "Não consegui ler a temperatura nem a faixa do filamento. Arquivo inalterado.",
        "narrow": "A faixa de temperatura do filamento é estreita demais para os veios. Arquivo inalterado.",
        "badrange": "Suas temperaturas mínima e máxima deixam menos de 2 °C de diferença dentro da faixa do filamento ({lo}-{hi} °C). Arquivo inalterado.",
        "off": "Veios desligados (intensidade 0). Arquivo inalterado.",
        "none": "Não foi preciso mudar a temperatura (faixa {lo}-{hi} °C). Arquivo inalterado.",
        "multi": "Há vários filamentos ou trocas de ferramenta (AMS). Este plugin só funciona com um filamento. Arquivo inalterado.",
        "other_filament": "Só um filamento é usado, mas não é aquele cujas temperaturas foram lidas do perfil. Arquivo inalterado.",
        "by_object": "A impressão é objeto por objeto (o Z volta a descer). Arquivo inalterado.",
        "done_before": "Este G-code já tem veios aplicados. Arquivo inalterado.",
        "few": "Poucas camadas depois das {skip} primeiras. Arquivo inalterado.",
        "io": "Não foi possível escrever o G-code: {err}. Arquivo inalterado.",
        "min": "temperatura mínima",
        "max": "temperatura máxima",
    },
}


class SkipFile(Exception):
    """The file must stay as it was. `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() fails on the slicing thread: fall back to English."""
    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"


# ---------------------------------------------------------------- config

def _num(value, default, lo, hi):
    try:
        v = float(value)
    except (TypeError, ValueError):
        return default
    if not math.isfinite(v):
        return default
    return max(lo, min(hi, v))


def sanitize_config(raw):
    """Returns a clean config dict, whatever the user typed."""
    raw = raw if isinstance(raw, dict) else {}
    d = DEFAULT_CONFIG
    return {
        "intensity": _num(raw.get("intensity"), d["intensity"], 0, 100),
        "grain_width_mm": _num(raw.get("grain_width_mm"), d["grain_width_mm"], 0.2, 50),
        "rings_percent": _num(raw.get("rings_percent"), d["rings_percent"], 0, 100),
        "skip_first_layers": int(_num(raw.get("skip_first_layers"), d["skip_first_layers"], 1, 100)),
        "temp_min": _num(raw.get("temp_min"), 0, 0, 500),
        "temp_max": _num(raw.get("temp_max"), 0, 0, 500),
    }


# ---------------------------------------------------------------- temperatures

def first_number(value, index=0):
    """Reads a number from what config_value returns: number, text, 'a;b' or a list."""
    if value is None:
        return None
    if isinstance(value, (list, tuple)):
        if not value:
            return None
        if index >= len(value):
            return None
        value = value[index]
        index = 0  # already picked: a text inside the list is just one number
    if isinstance(value, str):
        parts = [p for p in re.split(r"[;,\s]+", value.strip()) if p]
        if not parts:
            return None
        if index >= len(parts):
            return None
        value = parts[index]
    try:
        v = float(value)
    except (TypeError, ValueError):
        return None
    return v if v > 0 and math.isfinite(v) else None


def resolve_limits(base, low, high, cfg_min=0, cfg_max=0):
    """Returns (tmin, tmax, notes). `notes` is a list of (key, fmt) for the result message.

    Never goes above the filament maximum (or, with no range in the profile,
    above nominal + 10), never below the filament minimum, and always respects
    the user's own temp_min / temp_max (clipped into the filament range).
    """
    if base is None and (low is None or high is None):
        raise SkipFile("no_temp")
    if high is None:
        high = base + NO_RANGE_ABOVE_C
    if low is None:
        low = base - NO_RANGE_BELOW_C
    if base is None:
        base = (low + high) / 2.0
    if high - low < 2:
        raise SkipFile("narrow")
    notes = []
    clipped = {}
    for cfg, what in ((cfg_min, "min"), (cfg_max, "max")):
        if cfg and cfg > 0:
            value = max(low, min(high, cfg))
            if value != cfg:
                notes.append(("clip", {"what": what, "val": _fmt(value), "lo": _fmt(low), "hi": _fmt(high)}))
            clipped[what] = value
    if "min" in clipped and "max" in clipped:
        tmin, tmax = clipped["min"], clipped["max"]
    elif "max" in clipped:
        tmax = clipped["max"]
        tmin = max(low, tmax - USER_SPAN_C)
    elif "min" in clipped:
        tmin = clipped["min"]
        tmax = min(high, tmin + USER_SPAN_C)
    else:
        tmin = max(low, base - AUTO_BELOW_C)
        tmax = min(high, base + AUTO_ABOVE_C)
    lo_i, hi_i = math.ceil(tmin), math.floor(tmax)
    if hi_i - lo_i < 2:
        if clipped:
            raise SkipFile("badrange", lo=_fmt(low), hi=_fmt(high))
        raise SkipFile("narrow")
    return lo_i, hi_i, notes


def _fmt(v):
    return str(int(round(v)))


# ---------------------------------------------------------------- pattern

def _hash01(i, seed):
    x = (i * 374761393 + seed * 668265263) & 0xFFFFFFFF
    x = ((x ^ (x >> 13)) * 1274126177) & 0xFFFFFFFF
    x ^= x >> 16
    return x / 0xFFFFFFFF


def _smooth_noise(u, seed):
    i = math.floor(u)
    f = u - i
    s = f * f * (3 - 2 * f)
    a = _hash01(i, seed)
    b = _hash01(i + 1, seed)
    return a + (b - a) * s


def grain_value(z, width_mm, rings_percent=0, seed=SEED):
    """Grain at height z, between 0 (lightest) and 1 (darkest). Smooth and repeatable."""
    n = 0.7 * _smooth_noise(z / width_mm, seed) + 0.3 * _smooth_noise(z / (width_mm * 0.37), seed + 1)
    n = max(0.0, min(1.0, (n - 0.5) * 1.6 + 0.5))  # value noise is timid: stretch it
    r = rings_percent / 100.0
    ring = 0.5 + 0.5 * math.sin(2 * math.pi * z / (width_mm * 2.0))
    return (1 - r) * n + r * ring


def temperature_at(z, cfg, tmin, tmax):
    """Nozzle temperature (integer C) for a layer at height z. Always within [tmin, tmax]."""
    v = grain_value(z, cfg["grain_width_mm"], cfg["rings_percent"])
    k = 0.5 + (v - 0.5) * (cfg["intensity"] / 100.0)
    t = tmin + (tmax - tmin) * max(0.0, min(1.0, k))
    return int(round(max(tmin, min(tmax, t))))


# ---------------------------------------------------------------- G-code

_RE_ORCA_Z = re.compile(r"^;\s*Z:\s*(-?\d+(?:\.\d+)?)\s*$")
_RE_BAMBU_Z = re.compile(r"^;\s*Z_HEIGHT:\s*(-?\d+(?:\.\d+)?)\s*$")
_RE_TOOL = re.compile(r"^\s*T(\d+)(?=[\s;]|$)")
_RE_AMS = re.compile(r"^\s*M620\s+S(\d+)A\b")
_RE_TEMP_CMD = re.compile(r"^\s*M10[49]\b.*\bS(\d+)")
_RE_USED_MM = re.compile(r"^;\s*filament used \[mm\]\s*=\s*(.+?)\s*$", re.M)
_TAIL_BYTES = 64 * 1024
_RE_USED = re.compile(r"^;\s*filament:\s*(.+?)\s*$")
_NOT_A_TOOL = {255, 1000, 65535}  # Bambu uses these for start/end, not real filaments
_MAX_WAIT = 6  # lines allowed between the layer marker and its Z


def _real_tool(n):
    return n < 100 and n not in _NOT_A_TOOL


def used_filament_index(line):
    """Header '; filament: 1' (Bambu/Orca) -> 0-based index, or None. Raises SkipFile if several."""
    m = _RE_USED.match(line)
    if not m:
        return None
    ids = [p for p in re.split(r"[,;\s]+", m.group(1)) if p]
    if len(ids) > 1:
        raise SkipFile("multi")
    if ids and ids[0].isdigit() and int(ids[0]) >= 1:
        return int(ids[0]) - 1
    return None


def rewrite_lines(lines, emit, cfg, tmin, tmax, start_temp, expected_idx=0):
    """Copies every line to `emit` and adds `M104 S<t>` after each layer-change Z line.

    Layer change formats recognised:
      OrcaSlicer:        ';LAYER_CHANGE' then ';Z:<mm>'
      Bambu Studio/Orca: '; CHANGE_LAYER' then '; Z_HEIGHT: <mm>'
    Start/end G-code are never touched (nothing is added outside the layer changes),
    nor the first `skip_first_layers` layers, nor layers where the temperature
    changes less than 1 C. Raises SkipFile if the file must stay as it was.
    Returns a dict with the layer count, the commands written and the range used.
    """
    skip = cfg["skip_first_layers"]
    layer = 0
    last_z = None
    last_temp = float(start_temp)
    pending = None  # 'orca' or 'bambu' while we wait for the Z line
    waited = 0
    tools = set()
    written = 0
    used_lo = used_hi = None
    for line in lines:
        emit(line)
        if TAG in line:
            raise SkipFile("done_before")
        if pending:
            waited += 1
            if waited > _MAX_WAIT:
                pending = None
        if line.startswith(";"):
            stripped = line.rstrip("\r\n")
            if stripped.replace(" ", "") == ";LAYER_CHANGE":
                pending, waited = "orca", 0
                continue
            if stripped.replace(" ", "") == ";CHANGE_LAYER":
                pending, waited = "bambu", 0
                continue
            if pending:
                m = (_RE_ORCA_Z if pending == "orca" else _RE_BAMBU_Z).match(stripped)
                if m:
                    pending = None
                    z = float(m.group(1))
                    if last_z is not None and z < last_z - 1e-4:
                        raise SkipFile("by_object")
                    last_z = z
                    layer += 1
                    if layer <= skip:
                        continue
                    t = temperature_at(z, cfg, tmin, tmax)
                    if abs(t - last_temp) >= MIN_STEP_C:
                        eol = line[len(stripped):] or "\n"
                        emit("M104 S%d %s%s" % (t, TAG, eol))
                        last_temp = t
                        written += 1
                        used_lo = t if used_lo is None else min(used_lo, t)
                        used_hi = t if used_hi is None else max(used_hi, t)
                    continue
            continue
        if layer:
            mt = _RE_TEMP_CMD.match(line)
            if mt:
                last_temp = float(mt.group(1))
        m = _RE_TOOL.match(line) or _RE_AMS.match(line)
        if m and _real_tool(int(m.group(1))):
            tools.add(int(m.group(1)))
            if len(tools) > 1:
                raise SkipFile("multi")
    if tools and tools != {expected_idx}:
        raise SkipFile("multi")
    if layer == 0:
        raise SkipFile("no_layers")
    if layer <= skip:
        raise SkipFile("few", skip=skip)
    return {"layers": layer, "commands": written, "lo": used_lo, "hi": used_hi}


def process_file(path, cfg, tmin, tmax, start_temp, expected_idx=0):
    """Rewrites `path` through a temporary file in the same folder, replacing it only at the end.

    Every file is opened by its path (never through a file descriptor): OrcaSlicer's
    permission check only allows writes it can match to the G-code folder, and an
    fd-based open (tempfile.mkstemp + os.fdopen) has no path, so it is blocked.
    """
    path = os.path.abspath(path)
    tmp = os.path.join(os.path.dirname(path), ".%s.lio_vetas_%d.tmp" % (os.path.basename(path), os.getpid()))
    try:
        with open(tmp, "w", encoding="utf-8", errors="surrogateescape", newline="") as out, \
                open(path, "r", encoding="utf-8", errors="surrogateescape", newline="") as src:
            stats = rewrite_lines(src, out.write, cfg, tmin, tmax, start_temp, expected_idx)
        os.replace(tmp, path)
        return stats
    except BaseException:
        try:
            os.remove(tmp)
        except OSError:
            pass
        raise


def read_used_filament_index(path, max_lines=60):
    """Looks for '; filament: N' in the first lines. Raises SkipFile if several filaments are used."""
    with open(path, "r", encoding="utf-8", errors="surrogateescape", newline="") as f:
        for i, line in enumerate(f):
            if i >= max_lines:
                break
            idx = used_filament_index(line)
            if idx is not None:
                return idx
    return 0


def check_filament_used(path, idx):
    """Reads '; filament used [mm] = a,b,...' (OrcaSlicer writes it at the end, for every
    printer). Raises SkipFile('multi') if more than one filament is used, or if the only
    one used is not the one whose temperatures we read."""
    with open(path, "rb") as f:
        f.seek(0, os.SEEK_END)
        f.seek(max(0, f.tell() - _TAIL_BYTES))
        tail = f.read().decode("utf-8", errors="replace")
    found = _RE_USED_MM.findall(tail)
    if not found:
        return
    values = []
    for part in re.split(r"[,;\s]+", found[-1]):
        try:
            values.append(float(part))
        except ValueError:
            continue
    used = [i for i, v in enumerate(values) if v > 0]
    if len(used) > 1:
        raise SkipFile("multi")
    if len(used) == 1 and used[0] != idx:
        raise SkipFile("other_filament")


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

class WoodGrain(orca.slicing.SlicingPipelineCapabilityBase):
    def get_name(self):
        return PLUGIN_NAME

    def get_default_config(self):
        return dict(DEFAULT_CONFIG)

    def _config(self):
        try:
            return sanitize_config(json.loads(self.get_config()))
        except Exception:
            return sanitize_config(None)

    def execute(self, ctx):
        if ctx.step != orca.slicing.Step.psGCodePostProcess:
            return orca.ExecutionResult.success()
        lang = detect_lang()
        try:
            cfg = self._config()
            if cfg["intensity"] <= 0:
                raise SkipFile("off")
            idx = read_used_filament_index(ctx.gcode_path)
            base = first_number(ctx.config_value("nozzle_temperature"), idx)
            low = first_number(ctx.config_value("nozzle_temperature_range_low"), idx)
            high = first_number(ctx.config_value("nozzle_temperature_range_high"), idx)
            tmin, tmax, notes = resolve_limits(base, low, high, cfg["temp_min"], cfg["temp_max"])
            check_filament_used(ctx.gcode_path, idx)
            start = base if base is not None else (tmin + tmax) / 2.0
            stats = process_file(ctx.gcode_path, cfg, tmin, tmax, start, idx)
        except SkipFile as skip:
            fmt = dict(skip.fmt)
            if skip.key == "few":
                fmt.setdefault("skip", cfg["skip_first_layers"])
            return orca.ExecutionResult.skipped(tr(lang, skip.key, **fmt))
        except OSError as exc:
            return orca.ExecutionResult.failure(orca.PluginResult.RecoverableError, tr(lang, "io", err=exc))
        except Exception as exc:  # never let an exception escape into OrcaSlicer (it unloads the plugin)
            return orca.ExecutionResult.failure(orca.PluginResult.RecoverableError, str(exc))
        parts = []
        for key, fmt in notes:
            fmt = dict(fmt, what=tr(lang, fmt["what"]))
            parts.append(tr(lang, key, **fmt))
        if stats["commands"] == 0:
            parts.append(tr(lang, "none", lo=tmin, hi=tmax))
        else:
            parts.append(tr(lang, "ok", n=stats["commands"], lo=stats["lo"], hi=stats["hi"]))
        return orca.ExecutionResult.success(" ".join(parts))


@orca.plugin
class WoodGrainLio(orca.base):
    def register_capabilities(self):
        orca.register_capability(WoodGrain)
