"""
Rename parts and meshes from CAD metadata, inside RapidPipeline Twin Studio.

Same result as the RULES set "Rename from metadata":
  1. Every node carrying ON_UserStringList/ITEM_NUMBER is renamed to
         COMPONENT_GROUP_PART_NAME_ITEM_NUMBER_REVISION_PLM
     with spaces replaced by "_" (e.g. FRONT_END_FORK_LEG_UPPER_PART_1579205_G01).
  2. Every mesh node is renamed to "<parent name>_MESH".

Siblings that would end up with the same name are numbered: the first keeps the
name, the next ones get _2, _3, ...

Run it from Twin Studio's Python console / script editor (it needs the in-app
`rpts` module). Each step is one undo entry, so two Ctrl+Z undo everything.
Set DRY_RUN = True to only print the planned names.
"""

import rpts

DRY_RUN = False

ATTRIBUTE = "ON_UserStringList"
NAME_KEYS = ["COMPONENT_GROUP", "PART_NAME", "ITEM_NUMBER", "REVISION_PLM"]
MESH_SUFFIX = "_MESH"
PREVIEW_LINES = 10


def build_part_name(values):
    """Join the metadata values with "_"; spaces become "_" and "/" becomes "-".

    Returns None when a value is missing or empty, so the node is left alone.
    """
    parts = []
    for key in NAME_KEYS:
        value = values.get(key)
        if value is None or str(value).strip() == "":
            return None
        parts.append(str(value).strip())
    return "_".join(parts).replace(" ", "_").replace("/", "-")


def part_names():
    """{path: new_name} for every node that has the metadata, plus skipped paths."""
    paths = rpts.find_nodes_by_metadata(key=NAME_KEYS[2], attribute=ATTRIBUTE, as_paths=True)
    values = {key: rpts.get_metadata_values(paths, key, attribute=ATTRIBUTE) for key in NAME_KEYS}
    names, skipped = {}, []
    for path in paths:
        name = build_part_name({key: values[key].get(path) for key in NAME_KEYS})
        if name is None:
            skipped.append(path)
        else:
            names[path] = name
    return names, skipped


def mesh_paths():
    """Paths of all nodes that hold a mesh, in scene order."""
    asset = rpts.get_asset()
    found, stack = [], [asset.root_node]
    while stack:
        node = stack.pop()
        if node.mesh_index != -1:
            found.append(node.path)
        stack.extend(node[i] for i in reversed(range(len(node))))
    return found


def main():
    if rpts.get_asset() is None:
        print("No model loaded.")
        return

    names, skipped = part_names()
    meshes = mesh_paths()
    print("Parts with metadata: %d (skipped, missing values: %d)" % (len(names), len(skipped)))
    print("Mesh nodes: %d" % len(meshes))
    for path, name in list(names.items())[:PREVIEW_LINES]:
        print("  %s -> %s" % (path, name))
    if len(names) > PREVIEW_LINES:
        print("  ... and %d more" % (len(names) - PREVIEW_LINES))
    for path in skipped[:PREVIEW_LINES]:
        print("  skipped %s" % path)

    if DRY_RUN:
        print("DRY_RUN: nothing renamed.")
        return

    # Step 1: parts (one undo step). Duplicate names among siblings get _2, _3, ...
    renamed_parts = rpts.rename_nodes_map(names, label="Rename parts from metadata", duplicates="number")
    print("Parts renamed: %s" % renamed_parts)

    # Step 2: meshes take their (new) parent name + suffix (one undo step).
    renamed_meshes = rpts.rename_nodes_template(meshes, "{parent}" + MESH_SUFFIX,
                                                label="Rename meshes", duplicates="number")
    print("Meshes renamed: %s" % renamed_meshes)


main()
