import unreal


RECIPE_FOLDER = "/Game/Agrarian/DataAssets/Recipes"

ITEM_DISPLAY = {
    "wood": ("Wood", 1.0),
    "stone": ("Stone", 1.5),
    "fiber": ("Fiber", 0.1),
    "hide": ("Hide", 0.7),
    "primitive_frame": ("Primitive Frame", 3.0),
    "primitive_wall_panel": ("Primitive Wall Panel", 4.0),
    "primitive_roof_panel": ("Primitive Roof Panel", 4.0),
    "campfire": ("Campfire", 12.0),
    "primitive_shelter": ("Primitive Shelter", 25.0),
    "simple_container": ("Simple Container", 8.0),
    "basic_tool": ("Basic Tool", 1.2),
    "bandage": ("Bandage", 0.1),
}

RECIPES = [
    {
        "asset": "DA_Recipe_Campfire",
        "recipe_id": "campfire",
        "display_name": "Campfire",
        "ingredients": [("wood", 5), ("stone", 8), ("fiber", 2)],
        "result": ("campfire", 1),
        "craft_seconds": 8.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_PrimitiveShelter",
        "recipe_id": "primitive_shelter",
        "display_name": "Primitive Shelter",
        "ingredients": [
            ("primitive_frame", 2),
            ("primitive_wall_panel", 4),
            ("primitive_roof_panel", 2),
            ("hide", 2),
            ("fiber", 6),
        ],
        "result": ("primitive_shelter", 1),
        "craft_seconds": 20.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_PrimitiveFrame",
        "recipe_id": "primitive_frame",
        "display_name": "Primitive Frame",
        "ingredients": [("wood", 4), ("fiber", 2)],
        "result": ("primitive_frame", 1),
        "craft_seconds": 8.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_PrimitiveWallPanel",
        "recipe_id": "primitive_wall_panel",
        "display_name": "Primitive Wall Panel",
        "ingredients": [("wood", 3), ("fiber", 2)],
        "result": ("primitive_wall_panel", 1),
        "craft_seconds": 6.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_PrimitiveRoofPanel",
        "recipe_id": "primitive_roof_panel",
        "display_name": "Primitive Roof Panel",
        "ingredients": [("wood", 3), ("fiber", 3)],
        "result": ("primitive_roof_panel", 1),
        "craft_seconds": 7.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_BasicTool",
        "recipe_id": "basic_tool",
        "display_name": "Basic Tool",
        "ingredients": [("wood", 1), ("stone", 2), ("fiber", 1)],
        "result": ("basic_tool", 1),
        "craft_seconds": 6.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_SimpleContainer",
        "recipe_id": "simple_container",
        "display_name": "Simple Container",
        "ingredients": [("wood", 3), ("fiber", 6), ("hide", 2)],
        "result": ("simple_container", 1),
        "craft_seconds": 10.0,
        "requires_campfire": False,
    },
    {
        "asset": "DA_Recipe_Bandage",
        "recipe_id": "bandage",
        "display_name": "Bandage",
        "ingredients": [("fiber", 3), ("hide", 1)],
        "result": ("bandage", 1),
        "craft_seconds": 4.0,
        "requires_campfire": False,
    },
]


def make_stack(item_id, quantity):
    display_name, unit_weight = ITEM_DISPLAY[item_id]
    stack = unreal.AgrarianItemStack()
    stack.set_editor_property("item_id", item_id)
    stack.set_editor_property("display_name", display_name)
    stack.set_editor_property("quantity", quantity)
    stack.set_editor_property("unit_weight", unit_weight)
    return stack


def set_requires_campfire(recipe, value):
    for property_name in ("requires_campfire", "b_requires_campfire"):
        try:
            recipe.set_editor_property(property_name, value)
            return
        except Exception:
            continue

    if value:
        raise RuntimeError("Could not set bRequiresCampfire on recipe asset")


def create_or_load_recipe_asset(asset_name):
    path = f"{RECIPE_FOLDER}/{asset_name}"
    existing = unreal.EditorAssetLibrary.load_asset(path)
    if existing:
        return existing

    factory = unreal.DataAssetFactory()
    factory.set_editor_property("data_asset_class", unreal.AgrarianRecipeDataAsset)
    asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
    asset = asset_tools.create_asset(asset_name, RECIPE_FOLDER, unreal.AgrarianRecipeDataAsset, factory)
    if not asset:
        raise RuntimeError(f"Could not create {path}")
    return asset


def apply_recipe(asset, recipe_data):
    recipe = unreal.AgrarianRecipe()
    recipe.set_editor_property("recipe_id", recipe_data["recipe_id"])
    recipe.set_editor_property("display_name", recipe_data["display_name"])
    recipe.set_editor_property(
        "ingredients",
        [make_stack(item_id, quantity) for item_id, quantity in recipe_data["ingredients"]],
    )
    result_id, result_quantity = recipe_data["result"]
    recipe.set_editor_property("result", make_stack(result_id, result_quantity))
    recipe.set_editor_property("craft_seconds", recipe_data["craft_seconds"])
    set_requires_campfire(recipe, recipe_data["requires_campfire"])
    asset.set_editor_property("recipe", recipe)
    unreal.EditorAssetLibrary.save_loaded_asset(asset)


def main():
    unreal.EditorAssetLibrary.make_directory(RECIPE_FOLDER)
    for recipe_data in RECIPES:
        asset = create_or_load_recipe_asset(recipe_data["asset"])
        apply_recipe(asset, recipe_data)
        unreal.log(f"Configured recipe: {recipe_data['recipe_id']} -> {RECIPE_FOLDER}/{recipe_data['asset']}")

    unreal.log("Agrarian recipe setup complete.")


main()
