import unreal


STANCE_DEFAULTS = {
    "CrouchSpeedMultiplier": 0.55,
    "ProneSpeedMultiplier": 0.25,
}


def load(path):
    asset = unreal.EditorAssetLibrary.load_asset(path)
    if not asset:
        raise RuntimeError(f"Could not load {path}")
    return asset


def create_input_action(path):
    existing = unreal.EditorAssetLibrary.load_asset(path)
    if existing:
        return existing

    template_path = "/Game/Input/Actions/IA_Interact"
    template = unreal.EditorAssetLibrary.load_asset(template_path)
    if not template:
        template_path = "/Game/Input/Actions/IA_Jump"
        template = unreal.EditorAssetLibrary.load_asset(template_path)
    if not template:
        raise RuntimeError("Could not load an input action template")

    action = unreal.EditorAssetLibrary.duplicate_asset(template_path, path)
    if not action:
        raise RuntimeError(f"Could not create {path}")
    return action


def set_boolean_value_type(action):
    action.set_editor_property("value_type", unreal.InputActionValueType.BOOLEAN)
    try:
        action.set_editor_property("triggers", [])
    except Exception as exc:
        unreal.log_warning(f"Could not clear stance triggers; keeping template defaults: {exc}")
    unreal.EditorAssetLibrary.save_loaded_asset(action)


def mapping_exists(context, action, key_name):
    mapping_data = context.get_editor_property("default_key_mappings")
    for mapping in list(mapping_data.get_editor_property("mappings")):
        mapping_key = mapping.get_editor_property("key")
        if (
            mapping.get_editor_property("action") == action
            and str(mapping_key.get_editor_property("key_name")) == key_name
        ):
            return True
    return False


def map_key(context, action, key_name):
    if mapping_exists(context, action, key_name):
        unreal.log(f"Mapping already exists: {action.get_name()} -> {key_name}")
        return

    key = unreal.Key()
    key.set_editor_property("key_name", key_name)

    mapping_data = context.get_editor_property("default_key_mappings")
    mappings = list(mapping_data.get_editor_property("mappings"))
    new_mapping = unreal.EnhancedActionKeyMapping()
    new_mapping.set_editor_property("action", action)
    new_mapping.set_editor_property("key", key)
    mappings.append(new_mapping)
    mapping_data.set_editor_property("mappings", mappings)
    context.set_editor_property("default_key_mappings", mapping_data)

    unreal.log(f"Added mapping: {action.get_name()} -> {key_name}")


def main():
    crouch_action = create_input_action("/Game/Input/Actions/IA_Crouch")
    prone_action = create_input_action("/Game/Input/Actions/IA_Prone")
    set_boolean_value_type(crouch_action)
    set_boolean_value_type(prone_action)

    context = load("/Game/Input/IMC_Default")
    map_key(context, crouch_action, "C")
    map_key(context, crouch_action, "Gamepad_RightShoulder")
    map_key(context, prone_action, "Z")
    map_key(context, prone_action, "Gamepad_LeftShoulder")
    unreal.EditorAssetLibrary.save_loaded_asset(context)

    character_bp = load("/Game/Agrarian/Blueprints/Characters/BP_AgrarianPlayerCharacter")
    character_cdo = unreal.get_default_object(character_bp.generated_class())
    character_cdo.set_editor_property("CrouchAction", crouch_action)
    character_cdo.set_editor_property("ProneAction", prone_action)
    for property_name, value in STANCE_DEFAULTS.items():
        character_cdo.set_editor_property(property_name, value)
    unreal.EditorAssetLibrary.save_loaded_asset(character_bp)

    unreal.log("Agrarian stance input setup complete.")


main()
