# A script that takes in a CSC Contact Info spreadsheet as a .csv and generates the team pages

import argparse
import csv
import json

parser = argparse.ArgumentParser("updateTeam")
parser.add_argument("teamFile", help="The team file as a .csv")
args = parser.parse_args()
file = args.teamFile

# Relative path of team folder
team_dir = '../content/team'

# Read csv file rows
with open(file) as f:
  csv_reader = csv.reader(f)
  rows = [[val.strip() for val in row] for row in csv_reader]

header = [val.lower() for val in rows[0]]
body = rows[1:]

# Get column number of name, role, and team
name_index = header.index('name')
role_index = header.index('role')
team_index = header.index('team')

# Standardize the team name for lookup later
def format_team_name(team_name):
  return '-'.join(team_name.replace('\n', '').lower().split(' '))

# Map team names to their json file name
def team_name_to_file_name(team_name):
  file_name_map = {
    'bots': 'discord-team',
    'design': 'design-team',
    'class-profile': 'class-profile-committee',
    'discord-mods' : 'discord-mods-team',
    'events' : 'events-team',
    'external-affairs': 'external-affairs-team',
    'marketing': 'marketing-team',
    'photography': 'photography-team',
    'reps': 'representatives-team',
    'syscom': 'systerms-committee',
    'termcom': 'terminal-committee',
    'web': 'web-committee',
    'office-staff': 'office-staff' 
  }

  return file_name_map[team_name]

# For a list of rows of members, generate a list of each members name and role 
def generate_team_data(team_members_entries):
  return [
    { 'name': entry[name_index], 
      **({'role': entry[role_index]} if entry[role_index] else {})
    }
    for entry in filter(lambda entry: entry[name_index] != '', team_members_entries)
  ]

# Partition the rows by team
def sort_team_entries(entries):
  team_entries = {}
  curr_team = None
  prev_index = 0
  for i, entry in enumerate(entries):
    if entry[team_index] != "":
      curr_team = format_team_name(entry[team_index])
    
    if i + 1 >= len(entries) or entries[i+1][team_index] != "":
      team_entries[curr_team] = entries[prev_index:i+1]
      prev_index = i+1
  
  return team_entries

all_team_data = {}
sorted_team_entries = sort_team_entries(body)
for team, team_members_entries in sorted_team_entries.items():
  all_team_data[team] = generate_team_data(team_members_entries)

# Dump the member lists into the corresponding files
for team_name, team_data in all_team_data.items():
  file_name = team_name_to_file_name(team_name)

  print(file_name)
  with open(f"{team_dir}/{file_name}.json", 'w') as f:
    json.dump(team_data, f, indent=2)
    f.write('\n')