from typing import Tuple
from typing import Optional


def _parse_hp_template(template_name) -> Tuple[str, Optional[int]]:
  """Parses a template name as specified by the user.

  Template can versionned:
    "my_template@v5" -> Returns (my_template, 5)
  or non versionned:
    "my_template" -> Returns (my_template, None)

  Args:
    template_name: User specified template.

  Returns:
    Base template name and version.
  """

  malformed_msg = (f"The template \"{template_name}\" is malformed. Expecting "
                   "\"{template}@v{version}\" or \"{template}")

  if "@" in template_name:
    # Template with version.
    parts = template_name.split("@v")
    if len(parts) != 2:
      raise ValueError(malformed_msg)
    base_name = parts[0]
    try:
      version = int(parts[1])
    except:
      raise ValueError(malformed_msg)
    return base_name, version

  else:
    # Template without version?
    return template_name, None