import six


def canonicalize_trust(trusts):
  """Converts string constants representing trust direction into integers.

  Args:
    trusts: edgeworth_trusts or trapezoid_trusts hyperparameter of
      `tfl.layers.Lattice` layer.

  Returns:
    A list of trust constraint tuples of the form
    (feature_a, feature_b, direction) where direction can be -1 or 1, or the
    value None if trusts is None.

  Raises:
    ValueError: If one of trust constraints does not have 3 elements.
    ValueError: If one of trust constraints' direction is not in the set
      {-1, 1, 'negative', 'positive'}.
  """
  if trusts:
    canonicalized = []
    for trust in trusts:
      if len(trust) != 3:
        raise ValueError("Trust constraints must consist of 3 elements. Seeing "
                         "constraint tuple {}".format(trust))
      feature_a, feature_b, direction = trust
      if direction in [-1, 1]:
        canonicalized.append(trust)
      elif (isinstance(direction, six.string_types) and
            direction.lower() == "negative"):
        canonicalized.append((feature_a, feature_b, -1))
      elif (isinstance(direction, six.string_types) and
            direction.lower() == "positive"):
        canonicalized.append((feature_a, feature_b, 1))
      else:
        raise ValueError("trust constraint direction must be from: [-1, 1, "
                         "'negative', 'positive']. Given: {}".format(direction))
    return canonicalized
  return None