import json
from pathlib import Path

import unreal


MAP_PATH = "/Game/Agrarian/Maps/L_GroundZeroTerrain_Test"
PROJECT_ROOT = Path(r"Z:\AgrarianGameBulid")
TILE_ID = "gz_us_ca_pacifica_utm10n_e544_n4160"
UNREAL_TERRAIN_ROOT = PROJECT_ROOT / "Data" / "Terrain" / "Unreal" / TILE_ID
HEIGHTMAP_PATH = UNREAL_TERRAIN_ROOT / f"{TILE_ID}_unreal_1009.r16"
METADATA_PATH = UNREAL_TERRAIN_ROOT / f"{TILE_ID}_unreal_heightmap_metadata.json"
LANDSCAPE_LABEL = "AGR_GroundZero_Landscape"


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


def remove_existing_landscape():
    for actor in unreal.EditorLevelLibrary.get_all_level_actors():
        if get_actor_label(actor) == LANDSCAPE_LABEL:
            unreal.EditorLevelLibrary.destroy_actor(actor)


def create_or_load_map():
    unreal.EditorAssetLibrary.make_directory("/Game/Agrarian/Maps")
    if unreal.EditorAssetLibrary.does_asset_exist(MAP_PATH):
        if not unreal.EditorLevelLibrary.load_level(MAP_PATH):
            raise RuntimeError(f"Could not load map: {MAP_PATH}")
        return

    level_subsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
    if hasattr(level_subsystem, "new_level"):
        if not level_subsystem.new_level(MAP_PATH):
            raise RuntimeError(f"Could not create map: {MAP_PATH}")
        return

    if hasattr(unreal.EditorLevelLibrary, "new_level"):
        if not unreal.EditorLevelLibrary.new_level(MAP_PATH):
            raise RuntimeError(f"Could not create map: {MAP_PATH}")
        return

    raise RuntimeError("No supported Unreal Python API found for creating a level")


def main():
    create_or_load_map()
    remove_existing_landscape()

    with METADATA_PATH.open("r", encoding="utf-8") as metadata_file:
        metadata = json.load(metadata_file)

    import_settings = metadata["unreal_landscape_import"]
    heightmap = metadata["heightmap"]
    result = unreal.AgrarianEditorAutomationLibrary.import_landscape_heightmap_into_editor_world(
        str(HEIGHTMAP_PATH),
        int(heightmap["width"]),
        int(heightmap["height"]),
        float(import_settings["x_scale_cm"]),
        float(import_settings["y_scale_cm"]),
        float(import_settings["z_scale_cm"]),
        LANDSCAPE_LABEL,
    )

    if not str(result).startswith("PASS:"):
        raise RuntimeError(str(result))

    unreal.log(str(result))
    unreal.EditorLevelLibrary.save_current_level()
    unreal.log(f"Ground Zero terrain map saved: {MAP_PATH}")


main()
