import csv


def get_consensus_sequence(seq_info): 
    """
    Determine the consensus sequence of an alignment.
    Definition of consensus: most common base represented at that position. 
    """
    def output_position_matrix(position_matrix): 
        output_file = open('position_matrix.csv', 'w', newline='')
        keys = position_matrix[0].keys()
        csvwriter = csv.DictWriter(output_file, keys)
        csvwriter.writeheader()
        csvwriter.writerows(position_matrix)
        output_file.close()  
    consensus_sequence = []
    position_matrix = []
    for position in seq_info: 
        #Ignore any ambiguous basecalls - accept A, T, C, G, and 'gap'
        base_counts = {
            'A':position['bases'].count('a'),
            'T':position['bases'].count('t'),
            'C':position['bases'].count('c'),
            'G':position['bases'].count('g'),
            '-':position['bases'].count('-'),
        }
        #print(base_counts)
        max_basecalls = [key for key, count in base_counts.items() if count == max(base_counts.values())]
        if len(max_basecalls) == 1: 
            consensus_sequence.append(max_basecalls[0])
        else: 
            consensus_sequence.append('N')
        #Assembling position_matrix
        position_matrix.append(base_counts)
    #Output position matrix
    output_position_matrix(position_matrix)
    return ''.join(consensus_sequence)