import uuid


def build_name(instance, orchestrate_metadata):
  """Returns an appropriate name for the instance.

  The name is determined in the following order:
  1. Use the one explicitly requested upon creation in the instance object.
  2. Construct one using the instance-name-pattern value in the requested
     template, if any.
  3. Generate a unique name based on the requested template and size.

  Args:
    instance: Instance creation parameters.
    orchestrate_metadata (dict): Orchestrate-specific metadata stored in the
      instanceTemplate object representing the Orchestrate template. The
      instance-name-pattern is stored here, if any.
  """
  # Example pattern: {type}-{region}-{gpu_count}x{gpu_type}-{user}
  instance_name_pattern = orchestrate_metadata.get('instance_name_pattern')
  default_pattern = '{template}-{size}-{id}'
  name_pattern = instance.name or instance_name_pattern or default_pattern
  unique_id = uuid.uuid4().hex[:5]
  gpu_count = orchestrate_metadata.get('gpu_count', 0)
  gpu_type = orchestrate_metadata.get('gpu_type', '')
  graphics_type = 'vws' if gpu_type.endswith('-vws') else 'gpu'
  gpu_name = gpu_type if not gpu_type.endswith('-vws') else gpu_type[:-4]
  region = '-'.join(instance.zone.split('-')[:2])
  name = name_pattern.format(
      template=instance.template,
      size=instance.size,
      region=region,
      zone=instance.zone,
      type=graphics_type,
      gpu_name=gpu_name,
      gpu_count=gpu_count,
      gpu_type=gpu_type,
      user=unique_id,
      id=unique_id,
      )
  return name