import math
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 mapping_found(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 main():
    crouch_action = load("/Game/Input/Actions/IA_Crouch")
    prone_action = load("/Game/Input/Actions/IA_Prone")
    context = load("/Game/Input/IMC_Default")
    character_bp = load("/Game/Agrarian/Blueprints/Characters/BP_AgrarianPlayerCharacter")
    character_cdo = unreal.get_default_object(character_bp.generated_class())

    missing = []
    for action, key_name in [
        (crouch_action, "C"),
        (crouch_action, "Gamepad_RightShoulder"),
        (prone_action, "Z"),
        (prone_action, "Gamepad_LeftShoulder"),
    ]:
        if not mapping_found(context, action, key_name):
            missing.append(f"missing mapping {action.get_name()} -> {key_name}")

    if character_cdo.get_editor_property("CrouchAction") != crouch_action:
        missing.append("BP_AgrarianPlayerCharacter CrouchAction is not IA_Crouch")
    if character_cdo.get_editor_property("ProneAction") != prone_action:
        missing.append("BP_AgrarianPlayerCharacter ProneAction is not IA_Prone")

    for property_name, expected in STANCE_DEFAULTS.items():
        actual = float(character_cdo.get_editor_property(property_name))
        if not math.isclose(actual, expected, rel_tol=0.0, abs_tol=0.01):
            missing.append(f"{property_name}: expected {expected}, got {actual}")

    if missing:
        raise RuntimeError("Stance input verification failed: " + "; ".join(missing))

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


main()
