import textwrap


def build_partial_description(partial_spec):
  """Create the documentation lines for a specific partial.

  Generates something like this:

    # This is the partial's description, from spec.yml.
    # --build-arg ARG_NAME=argdefault
    #    this is one of the args.
    # --build-arg ANOTHER_ARG=(some|choices)
    #    another arg.

  Args:
    partial_spec: A dict representing one of the partials from spec.yml. Doesn't
      include the name of the partial; is a dict like { desc: ..., args: ... }.

  Returns:
    A commented string describing this partial.
  """

  # Start from linewrapped desc field
  lines = []
  wrapper = textwrap.TextWrapper(
      initial_indent='# ', subsequent_indent='# ', width=80)
  description = wrapper.fill(partial_spec.get('desc', '( no comments )'))
  lines.extend(['#', description])

  # Document each arg
  for arg, arg_data in partial_spec.get('args', dict()).items():
    # Wrap arg description with comment lines
    desc = arg_data.get('desc', '( no description )')
    desc = textwrap.fill(
        desc,
        initial_indent='#    ',
        subsequent_indent='#    ',
        width=80,
        drop_whitespace=False)

    # Document (each|option|like|this)
    if 'options' in arg_data:
      arg_options = ' ({})'.format('|'.join(arg_data['options']))
    else:
      arg_options = ''

    # Add usage sample
    arg_use = '# --build-arg {}={}{}'.format(arg,
                                             arg_data.get('default', '(unset)'),
                                             arg_options)
    lines.extend([arg_use, desc])

  return '\n'.join(lines)