import unreal


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

EXPECTED_RESOURCE_LABELS = {
    "wood": [
        "AGR_DemoWoodResource_01",
        "AGR_GZ_Wood_CoastalScrub_01",
        "AGR_GZ_Wood_CoastalScrub_02",
        "AGR_GZ_Wood_Hillside_03",
    ],
    "fiber": [
        "AGR_DemoFiberResource_01",
        "AGR_GZ_Fiber_Grassland_01",
        "AGR_GZ_Fiber_Grassland_02",
        "AGR_GZ_Fiber_Scrub_03",
        "AGR_GZ_Fiber_DrainageCandidate_04",
    ],
    "food": [
        "AGR_GZ_EdiblePlant_CoastalScrub_01",
        "AGR_GZ_EdiblePlant_Grassland_02",
        "AGR_GZ_EdiblePlant_DrainageCandidate_03",
    ],
    "stone": [
        "AGR_GZ_Stone_Slope_01",
        "AGR_GZ_Stone_Slope_02",
        "AGR_GZ_Stone_ExposedTerrain_03",
        "AGR_GZ_Stone_ValleyEdge_04",
    ],
}


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


def resource_item_id(actor):
    item_asset = actor.get_editor_property("yield_item_definition")
    definition = item_asset.get_editor_property("definition") if item_asset else None
    return str(definition.get_editor_property("item_id")) if definition else ""


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

    actors_by_label = {get_actor_label(actor): actor for actor in unreal.EditorLevelLibrary.get_all_level_actors()}
    failures = []

    for expected_item_id, labels in EXPECTED_RESOURCE_LABELS.items():
        for label in labels:
            actor = actors_by_label.get(label)
            if not actor:
                failures.append(f"{label} missing")
                continue

            actual_item_id = resource_item_id(actor)
            if actual_item_id != expected_item_id:
                failures.append(f"{label} expected {expected_item_id}, got {actual_item_id}")

            if actor.get_editor_property("remaining_harvests") <= 0:
                failures.append(f"{label} has no remaining harvests")

            persistence_node_id = str(actor.get_editor_property("persistence_node_id"))
            if persistence_node_id != label:
                failures.append(f"{label} persistence node id expected {label}, got {persistence_node_id}")

    if failures:
        raise RuntimeError("Ground Zero resource verification failed: " + "; ".join(failures))

    unreal.log(
        "Ground Zero resource verification complete: "
        f"{len(EXPECTED_RESOURCE_LABELS['wood'])} wood, "
        f"{len(EXPECTED_RESOURCE_LABELS['fiber'])} fiber, "
        f"{len(EXPECTED_RESOURCE_LABELS['food'])} edible plant, "
        f"{len(EXPECTED_RESOURCE_LABELS['stone'])} stone nodes."
    )


main()
