import unreal

MATERIAL_PATHS = [
    "/Game/Agrarian/Materials/M_AGR_GZ_Tree_CoastalOak",
    "/Game/Agrarian/Materials/M_AGR_GZ_Shrub_CoyoteBrush",
    "/Game/Agrarian/Materials/M_AGR_GZ_Grass_DryCoastal",
]


def set_instanced_usage(material):
    applied = False
    for property_name in (
        "used_with_instanced_static_meshes",
        "bUsedWithInstancedStaticMeshes",
    ):
        try:
            material.set_editor_property(property_name, True)
            applied = True
        except Exception:
            pass

    return applied


dirty_assets = []
for material_path in MATERIAL_PATHS:
    material = unreal.EditorAssetLibrary.load_asset(material_path)
    if not material:
        raise RuntimeError(f"Missing material: {material_path}")

    if not set_instanced_usage(material):
        raise RuntimeError(f"Could not set instanced static mesh usage on {material_path}")

    unreal.MaterialEditingLibrary.recompile_material(material)
    dirty_assets.append(material_path)

for material_path in dirty_assets:
    if not unreal.EditorAssetLibrary.save_asset(material_path, only_if_is_dirty=False):
        raise RuntimeError(f"Failed to save updated material: {material_path}")

print("Updated instanced static mesh usage for Ground Zero foliage materials:")
for material_path in dirty_assets:
    print(f" - {material_path}")
