import unreal


MATERIAL_FOLDER = "/Game/Agrarian/Characters/Materials"
CHARACTER_PROXY_MATERIALS = {
    "M_AGR_CharacterProxy_Workwear_Male": {
        "color": unreal.LinearColor(0.23, 0.20, 0.15, 1.0),
        "roughness": 0.88,
    },
    "M_AGR_CharacterProxy_Workwear_Female": {
        "color": unreal.LinearColor(0.20, 0.24, 0.18, 1.0),
        "roughness": 0.88,
    },
}


def ensure_character_proxy_materials():
    unreal.EditorAssetLibrary.make_directory(MATERIAL_FOLDER)
    asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
    created = []

    for asset_name, spec in CHARACTER_PROXY_MATERIALS.items():
        asset_path = f"{MATERIAL_FOLDER}/{asset_name}"
        material = unreal.EditorAssetLibrary.load_asset(asset_path)
        if not material:
            material = asset_tools.create_asset(asset_name, MATERIAL_FOLDER, unreal.Material, unreal.MaterialFactoryNew())
            if not material:
                raise RuntimeError(f"Could not create character proxy material: {asset_path}")

            base_color = unreal.MaterialEditingLibrary.create_material_expression(
                material, unreal.MaterialExpressionConstant3Vector, -420, -120
            )
            base_color.set_editor_property("constant", spec["color"])
            unreal.MaterialEditingLibrary.connect_material_property(
                base_color, "", unreal.MaterialProperty.MP_BASE_COLOR
            )

            roughness = unreal.MaterialEditingLibrary.create_material_expression(
                material, unreal.MaterialExpressionConstant, -420, 80
            )
            roughness.set_editor_property("r", spec["roughness"])
            unreal.MaterialEditingLibrary.connect_material_property(
                roughness, "", unreal.MaterialProperty.MP_ROUGHNESS
            )

            unreal.MaterialEditingLibrary.recompile_material(material)
            created.append(asset_path)

        unreal.EditorAssetLibrary.save_loaded_asset(material)

    return created


def main():
    created = ensure_character_proxy_materials()
    if created:
        for asset_path in created:
            unreal.log(f"Created MVP character proxy material: {asset_path}")
    else:
        unreal.log("MVP character proxy materials already exist.")


main()
