import logging


def remediate_iam_policy(sa_iam_policy, sa_resource_name, risky_roles):
    """Remove risky IAM roles from the service account IAM policy.

    Args:
        sa_iam_policy ([dict]): The IAM policy attached to the sa_resource_name.
        sa_resource_name ([str]): The GCP service account full resource name.
        risky_roles ([list]): A list of risky roles to check current attached roles against.

    Returns:
        [dict]: An updated non-risky IAM policy. All risky roles removed.
    """

    # We iterate in reverse due to removing entries
    for binding in reversed(sa_iam_policy["bindings"]):
        if binding["role"] in risky_roles:
            role = binding["role"]
            logging.info(
                f"Removing risky role: {role} from {sa_resource_name}"
            )
            sa_iam_policy["bindings"].remove(binding)
        else:
            logging.info(f"IAM binding: {binding} does not contain risky role.")

    return sa_iam_policy