import unreal


MAP_PATH = "/Game/Agrarian/Maps/L_GroundZeroTerrain_Test"

PLACEMENTS = [
    {
        "label": "AGR_WoodResourceNode_01",
        "class_path": "/Game/Agrarian/Blueprints/Resources/BP_WoodResourceNode",
        "location": unreal.Vector(650.0, -150.0, 120.0),
        "rotation": unreal.Rotator(0.0, 15.0, 0.0),
    },
    {
        "label": "AGR_FiberResourceNode_01",
        "class_path": "/Game/Agrarian/Blueprints/Resources/BP_FiberResourceNode",
        "location": unreal.Vector(560.0, 140.0, 90.0),
        "rotation": unreal.Rotator(0.0, -10.0, 0.0),
    },
    {
        "label": "AGR_Campfire_01",
        "class_path": "/Game/Agrarian/Blueprints/Structures/BP_Campfire",
        "location": unreal.Vector(900.0, 120.0, 60.0),
        "rotation": unreal.Rotator(0.0, 0.0, 0.0),
    },
    {
        "label": "AGR_PrimitiveShelter_01",
        "class_path": "/Game/Agrarian/Blueprints/Structures/BP_PrimitiveShelter",
        "location": unreal.Vector(1200.0, -260.0, 140.0),
        "rotation": unreal.Rotator(0.0, -20.0, 0.0),
    },
    {
        "label": "AGR_RabbitWildlife_01",
        "class_path": "/Game/Agrarian/Blueprints/Wildlife/BP_RabbitWildlife",
        "location": unreal.Vector(450.0, 420.0, 100.0),
        "rotation": unreal.Rotator(0.0, 135.0, 0.0),
    },
]


def load_blueprint_class(path):
    generated_class = unreal.EditorAssetLibrary.load_blueprint_class(path)
    if not generated_class:
        raise RuntimeError(f"Could not load Blueprint class: {path}")
    return generated_class


def get_actor_label(actor):
    try:
        return actor.get_actor_label()
    except Exception:
        return actor.get_name()


def remove_existing_placed_actors(labels):
    for actor in unreal.EditorLevelLibrary.get_all_level_actors():
        if get_actor_label(actor) in labels:
            unreal.EditorLevelLibrary.destroy_actor(actor)


def set_actor_label(actor, label):
    try:
        actor.set_actor_label(label, mark_dirty=True)
    except TypeError:
        actor.set_actor_label(label)


def main():
    if not unreal.EditorLevelLibrary.load_level(MAP_PATH):
        raise RuntimeError(f"Could not load map: {MAP_PATH}")

    labels = {placement["label"] for placement in PLACEMENTS}
    remove_existing_placed_actors(labels)

    for placement in PLACEMENTS:
        actor_class = load_blueprint_class(placement["class_path"])
        actor = unreal.AgrarianEditorAutomationLibrary.spawn_actor_in_editor_world(
            actor_class,
            placement["location"],
            placement["rotation"],
            placement["label"],
        )
        if not actor:
            raise RuntimeError(f"Could not spawn {placement['class_path']}")

        unreal.log(f"Placed {placement['label']} at {placement['location']}")

    unreal.EditorLevelLibrary.save_current_level()
    unreal.log("Agrarian test map placement setup complete.")


main()
