import csv


def cluster_keywords(input_file_path):
  """ Cluster keywords based on the shorted version of the keywords read from the input file.
  Args:
    input_file_path: the path to the tsv file containing keywords and their shortened version.
  Returns:
    shortened_keywords_list: a dictionary with shortened keywords as key, and list of keywords in that cluster as value
    total_keyword_counts: total number of keywords being clustered 
    model_name_list: a list of names of the LaserTagger models used for shortening keywords, as indicated in tsv file
  """
  shortened_keywords_list = []
  total_keyword_counts = 0

  with open(input_file_path) as f:
    read_tsv = csv.reader(f, delimiter="\t")
    model_name_list = next(read_tsv)[1:]
    for i in range(len(model_name_list)):
      shortened_keywords_list.append({})

    for line in read_tsv:
      total_keyword_counts += 1
      for index, shortened_keyword in enumerate(line[1:]):
        shortened_keyword = shortened_keyword.lower()
        if shortened_keyword == "":
          continue
        if shortened_keyword not in shortened_keywords_list[index]:
          shortened_keywords_list[index][shortened_keyword] = [line[0]]
        else:
          shortened_keywords_list[index][shortened_keyword].append(line[0])
  return shortened_keywords_list, total_keyword_counts, model_name_list