import copy


def _construct_channel_options(driver_config, endpoint_options=None):
    """
    Constructs gRPC channel initialization options
    :param driver_config: A driver config instance
    :param endpoint_options: Endpoint options
    :return: A channel initialization options
    """
    _max_message_size = 64 * 10**6
    _default_connect_options = [
        ("grpc.max_receive_message_length", _max_message_size),
        ("grpc.max_send_message_length", _max_message_size),
        ("grpc.primary_user_agent", driver_config.primary_user_agent),
        (
            "grpc.lb_policy_name",
            getattr(driver_config, "grpc_lb_policy_name", "round_robin"),
        ),
    ]
    if driver_config.grpc_keep_alive_timeout is not None:
        _default_connect_options.extend(
            [
                ("grpc.keepalive_time_ms", driver_config.grpc_keep_alive_timeout >> 3),
                ("grpc.keepalive_timeout_ms", driver_config.grpc_keep_alive_timeout),
                ("grpc.http2.max_pings_without_data", 0),
                ("grpc.keepalive_permit_without_calls", 0),
            ]
        )
    if endpoint_options is not None:
        if endpoint_options.ssl_target_name_override:
            _default_connect_options.append(
                (
                    "grpc.ssl_target_name_override",
                    endpoint_options.ssl_target_name_override,
                )
            )
    if driver_config.channel_options is None:
        return _default_connect_options
    channel_options = copy.deepcopy(driver_config.channel_options)
    custom_options_keys = set(i[0] for i in driver_config.channel_options)
    for item in filter(
        lambda x: x[0] not in custom_options_keys, _default_connect_options
    ):
        channel_options.append(item)
    return channel_options