# Rule set : Motorbike metadata demo
# Source   : MTL-assignments.rprules.json (STEP 3, OpenPBR Silver Standard materials)
#
# Run in the RPTS Script Editor or Python console. Each action is one undo step.
# Assigns one SB_* material per MATERIAL_ID (all 2272 parts are covered), then
# selects the large parts. The SB_* materials must be in the scene or in a registered
# material library (MATERIALS/Sportbike_OpenPBR_Silver).

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)


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

FAILED = []
RUN = 0


# ── Rule 1: dark_steel -> SB_Gunmetal_BlackOxide_Steel ──────────────────
FILTERS_1 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "dark_steel",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_1)
    log("'%s': %d matched" % ('dark_steel -> SB_Gunmetal_BlackOxide_Steel', len(m)))
    assign_material(m, 'SB_Gunmetal_BlackOxide_Steel')
    RUN += 1
except Exception as e:
    FAILED.append('dark_steel -> SB_Gunmetal_BlackOxide_Steel')
    log("'%s': ERROR %s" % ('dark_steel -> SB_Gunmetal_BlackOxide_Steel', e))


# ── Rule 2: satin_metal -> SB_SatinSilver_Machined_Aluminium ────────────
FILTERS_2 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "satin_metal",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_2)
    log("'%s': %d matched" % ('satin_metal -> SB_SatinSilver_Machined_Aluminium', len(m)))
    assign_material(m, 'SB_SatinSilver_Machined_Aluminium')
    RUN += 1
except Exception as e:
    FAILED.append('satin_metal -> SB_SatinSilver_Machined_Aluminium')
    log("'%s': ERROR %s" % ('satin_metal -> SB_SatinSilver_Machined_Aluminium', e))


# ── Rule 3: black_plastic -> SB_Black_Matte_Engineering_Plastic ─────────
FILTERS_3 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "black_plastic",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_3)
    log("'%s': %d matched" % ('black_plastic -> SB_Black_Matte_Engineering_Plastic', len(m)))
    assign_material(m, 'SB_Black_Matte_Engineering_Plastic')
    RUN += 1
except Exception as e:
    FAILED.append('black_plastic -> SB_Black_Matte_Engineering_Plastic')
    log("'%s': ERROR %s" % ('black_plastic -> SB_Black_Matte_Engineering_Plastic', e))


# ── Rule 4: grey_satin_powder_coat -> SB_Grey_Satin_Powdercoat ──────────
FILTERS_4 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "grey_satin_powder_coat",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_4)
    log("'%s': %d matched" % ('grey_satin_powder_coat -> SB_Grey_Satin_Powdercoat', len(m)))
    assign_material(m, 'SB_Grey_Satin_Powdercoat')
    RUN += 1
except Exception as e:
    FAILED.append('grey_satin_powder_coat -> SB_Grey_Satin_Powdercoat')
    log("'%s': ERROR %s" % ('grey_satin_powder_coat -> SB_Grey_Satin_Powdercoat', e))


# ── Rule 5: black_rubber -> SB_Black_Matte_Rubber ───────────────────────
FILTERS_5 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "black_rubber",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_5)
    log("'%s': %d matched" % ('black_rubber -> SB_Black_Matte_Rubber', len(m)))
    assign_material(m, 'SB_Black_Matte_Rubber')
    RUN += 1
except Exception as e:
    FAILED.append('black_rubber -> SB_Black_Matte_Rubber')
    log("'%s': ERROR %s" % ('black_rubber -> SB_Black_Matte_Rubber', e))


# ── Rule 6: polished_chrome -> SB_Polished_Chrome ───────────────────────
FILTERS_6 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "polished_chrome",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_6)
    log("'%s': %d matched" % ('polished_chrome -> SB_Polished_Chrome', len(m)))
    assign_material(m, 'SB_Polished_Chrome')
    RUN += 1
except Exception as e:
    FAILED.append('polished_chrome -> SB_Polished_Chrome')
    log("'%s': ERROR %s" % ('polished_chrome -> SB_Polished_Chrome', e))


# ── Rule 7: acid_green_accent -> SB_AcidGreen_Gloss_Powdercoat ──────────
FILTERS_7 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "acid_green_accent",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_7)
    log("'%s': %d matched" % ('acid_green_accent -> SB_AcidGreen_Gloss_Powdercoat', len(m)))
    assign_material(m, 'SB_AcidGreen_Gloss_Powdercoat')
    RUN += 1
except Exception as e:
    FAILED.append('acid_green_accent -> SB_AcidGreen_Gloss_Powdercoat')
    log("'%s': ERROR %s" % ('acid_green_accent -> SB_AcidGreen_Gloss_Powdercoat', e))


# ── Rule 8: grey_gloss_paint -> SB_Grey_Gloss_Painted_ABS ───────────────
FILTERS_8 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "grey_gloss_paint",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_8)
    log("'%s': %d matched" % ('grey_gloss_paint -> SB_Grey_Gloss_Painted_ABS', len(m)))
    assign_material(m, 'SB_Grey_Gloss_Painted_ABS')
    RUN += 1
except Exception as e:
    FAILED.append('grey_gloss_paint -> SB_Grey_Gloss_Painted_ABS')
    log("'%s': ERROR %s" % ('grey_gloss_paint -> SB_Grey_Gloss_Painted_ABS', e))


# ── Rule 9: charcoal_synthetic_leather -> SB_Charcoal_Synthetic_Leather ───
FILTERS_9 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "charcoal_synthetic_leather",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_9)
    log("'%s': %d matched" % ('charcoal_synthetic_leather -> SB_Charcoal_Synthetic_Leather', len(m)))
    assign_material(m, 'SB_Charcoal_Synthetic_Leather')
    RUN += 1
except Exception as e:
    FAILED.append('charcoal_synthetic_leather -> SB_Charcoal_Synthetic_Leather')
    log("'%s': ERROR %s" % ('charcoal_synthetic_leather -> SB_Charcoal_Synthetic_Leather', e))


# ── Rule 10: clear_glass -> SB_Clear_Tempered_Glass ──────────────────────
FILTERS_10 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "MATERIAL_ID",
        "value": "clear_glass",
        "match": "exact",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_10)
    log("'%s': %d matched" % ('clear_glass -> SB_Clear_Tempered_Glass', len(m)))
    assign_material(m, 'SB_Clear_Tempered_Glass')
    RUN += 1
except Exception as e:
    FAILED.append('clear_glass -> SB_Clear_Tempered_Glass')
    log("'%s': ERROR %s" % ('clear_glass -> SB_Clear_Tempered_Glass', e))


# ── Rule 11: Select large parts (>= 100 mm) ──────────────────────────────
FILTERS_11 = [
    {
        "enabled": True,
        "target": "metadata",
        "attribute": "ON_UserStringList",
        "key": "DIMENSIONS",
        "value": "^[1-9][0-9]{2,}(\\.[0-9]+)?\\s*x",
        "match": "regex",
        "case_sensitive": False,
        "invert": False,
        "include_descendants": False
    }
]
try:
    m = matches(FILTERS_11)
    log("'%s': %d matched" % ('Select large parts (>= 100 mm)', len(m)))
    rpts.set_selection(m)
    for p in m[:20]:
        log("  " + p)
    if len(m) > 20:
        log("  ... and %d more" % (len(m) - 20))
    RUN += 1
except Exception as e:
    FAILED.append('Select large parts (>= 100 mm)')
    log("'%s': ERROR %s" % ('Select large parts (>= 100 mm)', e))


# ── Rule 12: Show only the engine ────────────────────────────────────────
# (disabled in the rule set - not run)


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