"""
Export all materials used in the current scene as a material library and copy
it into the STEP 3 mtl-lib folder.

rpts.materials.export_scene_as_library() always writes to the Twin Studio
material library root (it takes no target path), so the new library folder is
copied to TARGET afterwards. The original stays in the library root and shows
up there as its own category.

Run in the Twin Studio Python console / script editor (needs the in-app `rpts`).
"""

import os
import shutil

import rpts

LIB_NAME = "vehicle-workflow-material-lib-script-export"
TARGET = "F:/data/_DEMOS/_2026_Vehicle-Demo/STEPS/STEP_3_UV-gen_Materials/mtl-lib"

results = rpts.materials.export_scene_as_library(LIB_NAME)

ok = [r for r in results if r["success"]]
if ok:
    src = os.path.dirname(ok[0]["path"])  # folder the app wrote the library to
    dst = os.path.join(TARGET, LIB_NAME)
    shutil.copytree(src, dst, dirs_exist_ok=True)
    print(f"{len(ok)} materials exported to: {src}")
    print(f"copied to: {dst}")
else:
    print("No material was exported.")

for r in results:
    if not r["success"]:
        print("FAILED:", r["name"], r["error"])
