# Merge every "mirrored twin" (LEFT/RIGHT) group found by metadata PART_NAME:
#   1. assign the "white plastic" material to all nodes of all qualifying groups;
#   2. run the "Scene Graph Flattening" processing action (default settings) once
#      PER qualifying group (each twin pair/group separately).
# Paste into the in-app Python Console. Everything lives inside a function, so no
# globals leak into the __main__ namespace shared with plugins.
#

def _merge_twins():
    import re
    import os
    import sys
    import copy
    import json
    import rpts

    # ------------------------------ CONFIG ------------------------------
    PROPERTY_NAME = "PART_NAME"
    SIDE_TOKENS = ("LEFT", "RIGHT")
    ALLOW_UNSIDED_TWIN = True   # sided member + unsided member of same base counts
    CASE_SENSITIVE = False
    DRY_RUN = False              # True = print the plan only, change NOTHING
    MATERIAL_NAME = "Plastic_White"   # library/scene material name (see candidates on failure)
    ASSIGN_MATERIAL = True
    FLATTEN = True
    FLATTEN_ACTION_NAME = "Scene Graph Flattening"   # meta.json "name"
    # --------------------------------------------------------------------

    flags = 0 if CASE_SENSITIVE else re.IGNORECASE
    side_re = re.compile(
        r'(?:^|[\s_-]+)(' + '|'.join(re.escape(t) for t in SIDE_TOKENS) + r')(?=$|[\s_-])',
        flags)

    def norm_side(s):
        return s if CASE_SENSITIVE else s.upper()

    def norm_base(s):
        s = re.sub(r'[\s_-]+', ' ', s).strip()
        return s if CASE_SENSITIVE else s.upper()

    def read_part_name(node):
        # Same read as rp_extensions._metadata_attributes, rp_extensions.py:1202-1229.
        md = getattr(node, "metadata", None)
        if md is None:
            return None
        try:
            attribs = list(md)
        except TypeError:
            attribs = [md[i] for i in range(len(md))]
        flat = None
        entry = None
        for attrib in attribs:
            entries = []
            for group in ("uints", "floats", "strings"):
                for sub in (getattr(attrib, group, None) or []):
                    entries.append((sub.title, sub.value))
            if attrib.title == PROPERTY_NAME and flat is None:
                # FLAT property: attribute TITLE = name (rp_extensions.py:1310-1316, 2307-2333).
                for k, v in entries:
                    if k == "":
                        flat = v
                        break
                else:
                    if len(entries) == 1:
                        flat = entries[0][1]
            if entry is None:
                for k, v in entries:
                    if k == PROPERTY_NAME:
                        entry = v
                        break
        val = flat if flat is not None else entry
        if val is None:
            return None
        val = str(val).strip()
        return val or None

    # ---- scene scan + detection (identical logic to select_mirrored_twins.py) ----
    def scan(quiet_errors=False):
        """Walks the CURRENT asset (fetched fresh: processing replaces it).
        Returns dict(groups, qualifying, total, members, skipped, children, mesh_index)
        or None if no model is loaded."""
        asset = rpts.get_asset()
        if asset is None:
            return None
        members = []
        skipped = []
        total = 0
        children = {}
        mesh_index = {}
        root = asset.root_node
        stack = [(root, True)]
        while stack:
            node, is_root = stack.pop()
            path = node.path
            children[path] = [node[i].path for i in range(len(node))]
            try:
                mesh_index[path] = node.mesh_index
            except Exception:
                mesh_index[path] = -1
            if not is_root:
                total += 1
                try:
                    pname = read_part_name(node)
                except Exception as e:
                    if not quiet_errors:
                        print("merge_twins: metadata read failed on %s: %s" % (path, e))
                    pname = None
                if pname is None:
                    skipped.append((path, node.name))
                else:
                    members.append((path, node.name, pname))
            for i in range(len(node) - 1, -1, -1):
                stack.append((node[i], False))

        groups = {}
        for path, name, pname in members:
            sides = [norm_side(m.group(1)) for m in side_re.finditer(pname)]
            base = norm_base(side_re.sub('', pname))
            side = sides[0] if sides else None
            groups.setdefault(base, []).append((side, path, name, pname))

        qualifying = []
        for base in sorted(groups):
            mem = groups[base]
            sided = set(s for s, _p, _n, _pn in mem if s)
            has_unsided = any(s is None for s, _p, _n, _pn in mem)
            if len(sided) >= 2 or (ALLOW_UNSIDED_TWIN and sided and has_unsided):
                qualifying.append(base)
        return {"groups": groups, "qualifying": qualifying, "total": total,
                "members": members, "skipped": skipped,
                "children": children, "mesh_index": mesh_index}

    def mesh_count(sc, paths):
        n = 0
        seen = set()
        stack = list(paths)
        while stack:
            p = stack.pop()
            if p in seen:
                continue
            seen.add(p)
            if sc["mesh_index"].get(p, -1) != -1:
                n += 1
            stack.extend(sc["children"].get(p, ()))
        return n

    # ---- material lookup (rp_extensions.py:4117-4142, 3238-3286) ----
    def norm_mat(s):
        return re.sub(r'[\s_-]+', ' ', str(s)).strip().lower()

    def resolve_material(name):
        """Returns (value_for_assign, description) or (None, error_text).
        Order: scene material by name, then library name/original_name. Exact match
        first, then case/space/underscore-insensitive. Never guesses between
        several different candidates."""
        scene = rpts.materials.list_scene_materials()      # rp_extensions.py:3265
        lib = rpts.materials.list_library()                # rp_extensions.py:3238
        if name.startswith("scene://"):
            return name, "scene path"
        for exact in (True, False):
            def same(a):
                return a == name if exact else norm_mat(a) == norm_mat(name)
            hits = []
            for m in scene:
                if same(m["name"]) and m["path"] not in [h[0] for h in hits]:
                    hits.append((m["path"], "scene material %r" % m["name"]))
            if not hits:
                for m in lib:
                    if (same(m["name"]) or same(m["original_name"])) \
                            and m["path"] not in [h[0] for h in hits]:
                        hits.append((m["path"], "library material %r (%s)" % (m["name"], m["path"])))
            if len(hits) == 1:
                return hits[0]
            if len(hits) > 1:
                return None, "ambiguous: %s" % "; ".join(h[1] for h in hits)
        cands = []
        for m in scene:
            if "plastic" in m["name"].lower():
                cands.append("scene:   %s  (%s)" % (m["name"], m["path"]))
        for m in lib:
            if "plastic" in m["name"].lower() or "plastic" in m["original_name"].lower():
                cands.append("library: %s  (%s)" % (m["name"], m["path"]))
        return None, ("material %r not found in scene or library. Candidates containing 'plastic':\n    %s"
                      % (name, "\n    ".join(cands) if cands else "<none>"))

    # ---- flattening config: the action's DEFAULTS + the panel's export override ----
    def flatten_config():
        """rpd_config.json of FLATTEN_ACTION_NAME (rp_extensions.py:64-92) with the
        panel's export override (rp_extensions.py:4273-4293); the raw file has
        "export": [] and the processed nodes would vanish."""
        from PySide6.QtCore import QCoreApplication
        app_dir = os.path.normpath(QCoreApplication.applicationDirPath())
        actions_dir = os.path.join(app_dir, "python_modules", "magic-actions", "actions")
        vers = [d for d in os.listdir(actions_dir)
                if re.match(r'^v\d+\.\d+\.\d+$', d) and os.path.isdir(os.path.join(actions_dir, d))]
        if not vers:
            raise RuntimeError("no versioned action folder in %s" % actions_dir)
        newest = max(vers, key=lambda v: tuple(int(x) for x in v[1:].split('.')))
        pdir = os.path.join(actions_dir, newest, "processing")
        for d in sorted(os.listdir(pdir)):
            mp = os.path.join(pdir, d, "meta.json")
            cp = os.path.join(pdir, d, "rpd_config.json")
            if not os.path.isfile(mp):
                continue
            with open(mp, encoding="utf-8") as f:
                if json.load(f).get("name") != FLATTEN_ACTION_NAME:
                    continue
            with open(cp, encoding="utf-8") as f:
                cfg = copy.deepcopy(json.load(f))
            try:
                from magic_actions import utils as action_utils
                action_utils.overrideExports(cfg, "fbx")
            except Exception:
                cfg.pop("export", None)
                cfg["export"] = [{
                    "fileName": "scene_file",
                    "format": {"fbx": {"3dsMaxPhysicalMaterial": {"textureFormat": {"default": "png"}}}},
                }]
            return cfg
        raise RuntimeError("processing action %r not found in %s" % (FLATTEN_ACTION_NAME, pdir))

    # ================================ MAIN ================================
    sc = scan()
    if sc is None:
        print("merge_twins: no model loaded.")
        return
    qualifying = sc["qualifying"]
    groups = sc["groups"]

    print("=" * 70)
    print("Merge mirrored twins by %s (%s)" % (PROPERTY_NAME, "DRY RUN" if DRY_RUN else "LIVE"))
    print("=" * 70)
    all_paths = []
    for base in qualifying:
        print("\n[%s]" % (base or "<empty base>"))
        for side, path, name, pname in groups[base]:
            print("  %-8s %s  (%s)  PART_NAME=%r" % (side or "-", name, path, pname))
            all_paths.append(path)
    print("\n" + "-" * 70)
    print("Nodes scanned (root excluded): %d" % sc["total"])
    print("Nodes with %s: %d in %d base name(s)" % (PROPERTY_NAME, len(sc["members"]), len(groups)))
    print("Qualifying groups: %d, nodes: %d" % (len(qualifying), len(all_paths)))
    print("Skipped (no %s): %d" % (PROPERTY_NAME, len(sc["skipped"])))
    print("Plan: assign material=%s (%r), flatten=%s (%r) once per group"
          % (ASSIGN_MATERIAL, MATERIAL_NAME, FLATTEN, FLATTEN_ACTION_NAME))

    if not qualifying:
        print("Nothing to do.")
        return

    # Resolve material and config up front so a bad name stops BEFORE anything changes.
    mat_value = None
    if ASSIGN_MATERIAL:
        mat_value, info = resolve_material(MATERIAL_NAME)
        if mat_value is None:
            print("\nERROR: %s\nStopping: nothing assigned, nothing flattened." % info)
            return
        print("Material resolved: %s" % info)
    cfg_json = None
    if FLATTEN:
        try:
            cfg_json = json.dumps(flatten_config())
        except Exception as e:
            print("\nERROR: cannot build the flattening config: %s\nStopping: nothing changed." % e)
            return
        print("Flatten config: default settings of %r (+ panel export override)" % FLATTEN_ACTION_NAME)

    if DRY_RUN:
        print("\nDRY_RUN: would assign material to %d node(s) (one undo step per group)," % len(all_paths))
        print("then flatten %d group(s) separately (%d undo steps)." % (len(qualifying), len(qualifying)))
        for base in qualifying:
            paths = [p for _s, p, _n, _pn in groups[base]]
            print("  %-30s meshes under nodes: %d" % (base or "<empty>", mesh_count(sc, paths)))
        print("DRY_RUN: scene unchanged.")
        return

    report = {b: {"nodes": [p for _s, p, _n, _pn in groups[b]], "material": "-", "flatten": "-"}
              for b in qualifying}
    previous_selection = []
    try:
        previous_selection = list(rpts.get_selection(as_paths=True))
    except Exception:
        pass

    # ---- 1. material: one call per group, each = ONE undo step (rp_extensions.py:3306-3351).
    # rpts.materials.assign expands non-mesh nodes to their mesh descendants itself.
    if ASSIGN_MATERIAL:
        print("\n--- assigning material ---")
        for base in qualifying:
            try:
                n = rpts.materials.assign(report[base]["nodes"], mat_value)
                report[base]["material"] = "ok (%s mesh binding(s) changed)" % n
            except Exception as e:
                report[base]["material"] = "ERROR: %s" % e
            print("[%s] material: %s" % (base, report[base]["material"]))

    # ---- 2. flatten once per group. Flattening replaces the asset and restructures the
    # tree, so precomputed paths of OTHER groups can be stale. Therefore after every
    # flatten the scene is re-scanned and the next group is re-detected by its base name
    # and its CURRENT paths are used. Already-processed bases are never re-run.
    if FLATTEN:
        print("\n--- flattening (one run per group) ---")
        done = set()
        for base in qualifying:
            try:
                cur = scan(quiet_errors=True)
                if cur is None:
                    report[base]["flatten"] = "SKIPPED: no model loaded"
                    print("[%s] flatten: %s" % (base, report[base]["flatten"]))
                    continue
                if base not in cur["qualifying"] or base in done:
                    report[base]["flatten"] = ("SKIPPED: group no longer detected after earlier "
                                               "flattening (merged/renamed/metadata lost)")
                    print("[%s] flatten: %s" % (base, report[base]["flatten"]))
                    continue
                paths = [p for _s, p, _n, _pn in cur["groups"][base]]
                nmesh = mesh_count(cur, paths)
                if nmesh == 0:
                    report[base]["flatten"] = "SKIPPED: no mesh nodes under the group"
                    print("[%s] flatten: %s" % (base, report[base]["flatten"]))
                    continue
                # Never process with an empty selection (= whole scene, RPScriptingAPI.cpp:213-216).
                rpts.set_selection(paths)      # propagates to subtrees; waits for selection change
                if not rpts.get_selection(as_paths=True):
                    report[base]["flatten"] = "ERROR: could not select the group; not processed"
                    print("[%s] flatten: %s" % (base, report[base]["flatten"]))
                    continue
                asset = rpts.get_asset()
                # Synchronous (RPScriptingAPI.cpp:229-240); one undo step (viewport.cpp:1383).
                ok = asset.process(cfg_json)
                if ok is None or ok is False:
                    report[base]["flatten"] = "ERROR: process returned %r" % (ok,)
                else:
                    done.add(base)
                    report[base]["flatten"] = "ok (%d node(s), %d mesh node(s))" % (len(paths), nmesh)
                print("[%s] flatten: %s" % (base, report[base]["flatten"]))
            except Exception as e:
                report[base]["flatten"] = "ERROR: %s" % e
                print("[%s] flatten: %s" % (base, report[base]["flatten"]))

    try:
        rpts.set_selection(previous_selection)   # best effort: paths may be gone
    except Exception:
        pass

    # ---- summary ----
    print("\n" + "=" * 70)
    print("SUMMARY")
    print("=" * 70)
    bad = 0
    for base in qualifying:
        r = report[base]
        print("[%s]  nodes=%d  material=%s  flatten=%s" % (base, len(r["nodes"]), r["material"], r["flatten"]))
        if r["material"].startswith("ERROR") or r["flatten"].startswith("ERROR"):
            bad += 1
    print("Groups: %d, with errors: %d" % (len(qualifying), bad))
    print("Undo: Ctrl+Z reverts one step at a time (one per material call, one per flatten).")


_merge_twins()
del _merge_twins
