import re
import ast


def parse_spec(spec):
  """Parses a list of key values pairs.

  Args:
    spec: A comma separated list of strings of the form `<key>=<value>`.

  Raises:
    ValueError: If `spec` is malformed or contains duplicate keys.

  Returns:
    A dict.
  """
  params = {}
  if spec:
    # The regex represents a key-value pair.
    regex = r"""([^=,]+) # The key. Comma and = are excluded.
                =
                (\[[^\[\]=]*\] # The value as a list. Nested lists unsupported.
                 |[^=,\[\]]*) # Or a simple value.
                (,|$) # The end of a key-value pair.
            """
    tuples = re.findall(regex, spec, flags=re.X)
    if not tuples:
      raise ValueError('Spec "%s" doesn\'t contain any key value pair.' % spec)
    for item in tuples:
      key = item[0]
      value = item[1]
      if not value: raise ValueError('Empty value for key %s' % key)
      if key in params: raise ValueError('Duplicate key %s' % key)
      try:
        params[key] = ast.literal_eval(value)
      except ValueError:
        params[key] = value

  return params