# Rule set : Untitled
# Generated: RPTS rules export, 2026-11-25
# Source   : (rule set not loaded from a file)
#
# Run in the RPTS Script Editor or Python console. Each action is one undo step.
# Requires the scripting feature for processing actions.
#
# Export only: edit the rule set (.rprules.json / RULES dock) and export again, or edit
# this script by hand. Disabled rules/actions/filters are commented out and marked
# '(disabled)': uncomment them to re-enable. Rules run in order; filters are
# re-evaluated before every action; a failing rule does not stop the others.

import json
import copy
import os
import rpts


# ── Helpers ─────────────────────────────────────────────────────────────

def log(msg):
    print("[Rules script] " + str(msg))

def matches(filters, scope=None):
    """Paths matching ALL filters (AND), in scene order.
    Evaluated over the whole scene (scope is kept only for signature compatibility)."""
    return rpts.find_nodes(filters, as_paths=True)

def top_most(paths):
    """Order-preserving, de-duplicated paths that have no ancestor in the list."""
    wanted = set(paths)
    out, seen = [], set()
    for p in paths:
        if p in seen:
            continue
        seen.add(p)
        i = p.find("/", 1)
        covered = False
        while i != -1:
            if p[:i] in wanted:
                covered = True
                break
            i = p.find("/", i + 1)
        if not covered:
            out.append(p)
    return out

def scene_tree():
    """(root_path, children, parent, mesh_nodes) of the loaded scene, as plain data."""
    asset = rpts.get_asset()
    if asset is None:
        raise RuntimeError("No model loaded.")
    root = asset.root_node
    children, parent, mesh_nodes = {root.path: []}, {}, set()
    stack = [root]
    while stack:
        node = stack.pop()
        path = node.path
        children.setdefault(path, [])
        for i in range(len(node)):
            child = node[i]
            children[path].append(child.path)
            parent[child.path] = path
            try:
                if child.mesh_index != -1:
                    mesh_nodes.add(child.path)
            except Exception:
                pass
            stack.append(child)
    return root.path, children, parent, mesh_nodes


def ancestors_of(path, root, parent):
    """Ancestor paths of `path`, nearest first (the scene root is excluded)."""
    out = []
    p = parent.get(path)
    while p is not None and p != root:
        out.append(p)
        p = parent.get(p)
    return out

def resolve_material(name):
    """Material name -> value accepted by rpts.materials.assign, or None (logged).
    Order: scene:// path, scene materials by name, library name/original_name
    (ambiguous -> error), existing .mtlx file path."""
    if not name or not isinstance(name, str):
        log("assign_material: ERROR no material name given - skipped")
        return None
    if name.startswith("scene://"):
        return name
    for m in rpts.materials.list_scene_materials():
        if m["name"] == name:
            return m["path"]
    found = []
    for m in rpts.materials.list_library():
        if name in (m["name"], m["original_name"]) and m["path"] not in found:
            found.append(m["path"])
    if len(found) == 1:
        return found[0]
    if len(found) > 1:
        log("assign_material: ERROR ambiguous material name %r (%d library matches) - skipped"
            % (name, len(found)))
        return None
    if name.lower().endswith(".mtlx") and os.path.isfile(name):
        return name
    log("assign_material: ERROR material %r not found in scene or library - skipped" % (name,))
    return None


def assign_material(paths, name):
    """Assign a material (by name) to the mesh nodes under `paths`. One undo step."""
    material = resolve_material(name)    # resolved first, like the engine, even with 0 matches
    if material is None or not paths:
        return 0
    # rpts.materials.assign expands non-mesh nodes to their mesh descendants itself.
    return rpts.materials.assign(paths, material)

def process(paths, config):
    """Run a processing action on the mesh nodes under `paths` only (never the whole scene).
    One undo step. The asset is replaced by processing: re-run matches() afterwards."""
    if not paths:
        log("process: no matched nodes -> skipped")
        return False
    root, children, parent, mesh_nodes = scene_tree()
    meshes, stack = set(), list(paths)
    while stack:
        q = stack.pop()
        if q in mesh_nodes:
            meshes.add(q)
        stack.extend(children.get(q, ()))
    if not meshes:
        log("process: no mesh nodes among %d matches -> skipped" % len(paths))
        return False
    log("process: %d matched nodes (%d mesh nodes)" % (len(paths), len(meshes)))
    # Panel parity: the MODEL ACTIONS panel replaces the config's "export" with the FBX default.
    cfg = copy.deepcopy(config)
    try:
        from magic_actions import utils as action_utils
        action_utils.overrideExports(cfg, "fbx")
    except Exception:
        # Fallback copy of that block when magic_actions.utils cannot be imported.
        cfg.pop("export", None)
        cfg["export"] = [{
            "fileName": "scene_file",
            "format": {"fbx": {"3dsMaxPhysicalMaterial": {"textureFormat": {"default": "png"}}}},
        }]
    # process() works on the engine selection: select the matches temporarily.
    # (The engine uses an internal wait-for-selection call; the public set_selection is the
    # closest equivalent - the verification below catches a selection that did not apply.)
    asset = rpts.get_asset()
    previous = rpts.get_selection(as_paths=True)
    rpts.set_selection(list(paths))
    if not rpts.get_selection(as_paths=True):
        log("process: ERROR could not select the matched nodes - skipped")
        return False
    ok = None
    try:
        ok = asset.process(json.dumps(cfg))
    finally:
        try:
            rpts.set_selection(previous)    # best effort: paths may be gone after processing
        except Exception:
            pass
    if ok is None or ok is False:
        log("process: ERROR processing failed (returned %r)" % (ok,))
        return False
    return True


# ── Run ────────────────────────────────────────────────────────────────

FAILED = []


# ── Rule 1: apply shared mtl to SCREWs ────────────────────────────────
FILTERS_1 = [
    {
        'attribute': None,
        'case_sensitive': False,
        'enabled': True,
        'include_descendants': False,
        'invert': False,
        'key': 'COMPONENT_TYPE',
        'match': 'exact',
        'target': 'metadata',
        'value': 'SCREW',
    },
]
try:
    m = matches(FILTERS_1)
    log("'%s': %d matched" % ('apply shared mtl to SCREWs', len(m)))
    # action 1: assign_material 'Plastic_White'
    assign_material(m, 'Plastic_White')
except Exception as e:
    FAILED.append('apply shared mtl to SCREWs')
    log("'%s': ERROR %s" % ('apply shared mtl to SCREWs', e))


# ── Rule 2: Instance SCREWs ───────────────────────────────────────────
FILTERS_2 = [
    {
        'attribute': None,
        'case_sensitive': False,
        'enabled': True,
        'include_descendants': False,
        'invert': False,
        'key': 'COMPONENT_TYPE',
        'match': 'exact',
        'target': 'metadata',
        'value': 'SCREW',
    },
]
# process action: Instance Identical Meshes
CONFIG_2_1 = {
    '3dEdit': {'modelEdit': {'removeDuplicateMeshes': {'useNames': False, 'useVertexData': False}}},
    'export': [],
}
try:
    m = matches(FILTERS_2)
    log("'%s': %d matched" % ('Instance SCREWs', len(m)))
    # action 1: process 'Instance Identical Meshes'
    process(m, CONFIG_2_1)
except Exception as e:
    FAILED.append('Instance SCREWs')
    log("'%s': ERROR %s" % ('Instance SCREWs', e))


log("Finished: %d rule(s) run, %d failed." % (2, len(FAILED)))
