import json


def check_app_running_on(expected_cluster, error_message):
    """Create a callable to verify the cluster on which an Application is
    running obtained as a response.

    To be used with the :meth:`run` function. The callable will raise an
    :class:`AssertionError` if the state of the Application is different
    from the given one.

    Args:
        expected_cluster (str): the name of the cluster on which the
            Application is expected to be running.
        error_message (str): the message that will be displayed if the
            check fails.

    Returns:
        callable: a condition that will check its given response against
            the parameters of the current function.

    """

    def validate(response):
        try:
            app_details = response.json
            running_on_dict = app_details["status"]["running_on"] or {}
            running_on = running_on_dict.get("name", None)
            scheduled_to_dict = app_details["status"]["scheduled_to"] or {}
            scheduled_to = scheduled_to_dict.get("name", None)
            msg = (
                error_message + f" App state: {app_details['status']['state']}, "
                f"App scheduled_to: {scheduled_to}, "
                f"App running_on: {running_on}"
            )
            assert running_on == expected_cluster, msg
        except (KeyError, json.JSONDecodeError):
            raise AssertionError(error_message)

    return validate