import re


def parse_quast_result(path_to_quast_result):
    """
    Args:
        path_to_quast_result (str): Path to the QUAST result file.
    Returns:
        dict: Parsed QUAST report
        For example:
        {
            "contigs_count": 72,
            "largest_contig": 692871,
            "N50": 299446,
            "L50": 6,
            "N75": 123167,
            "L75": 12,
            "total_length": 5182695,
            "percent_GC": 51.75,
            "complete_busco_percent": 100.0,
            "partial_busco_percent": 100.0
        }
    """
    quast_output = []
    with open(path_to_quast_result, 'r') as quast_result:
        for line in quast_result:
            quast_output.append(line)

    def parse_quast_report_line(line):
        """
        Takes a line of the quast report and returns the specific data that we're interested in from that line.
        
        Collapse multiple spaces into a tab char ('\t'), then split the line on tabs and take the second item.
        Cast floats to floats and ints to ints.
        '# contigs        751   ' -> '# contigs\t751\t' -> ['# contigs', '751', ''] -> '751' -> 751
        """
        result_data = re.sub(' {2,}', '\t', line).split('\t')[1]
        if re.match('\d+\.\d+', result_data):
            return float(result_data)
        else:
            return int(result_data)

    # Associate a regex that can be used to identify the line of interest in the quast report
    # with a string to use as a key in the output dict.
    quast_report_parsing_regexes = {
        '^# contigs {2,}\d+': 'num_contigs',
        '^Largest contig {1,}\d+': 'largest_contig',
        '^N50 +\d+': 'N50',
        '^NG50 +\d+': 'NG50',
        '^L50 +\d+': 'L50',
        '^LG50 +\d+': 'LG50',
        '^N75 +\d+': 'N75',
        '^NG75 +\d+': 'NG75',
        '^L75 +\d+': 'L75',
        '^LG75 +\d+': 'LG75',
        '^Total length {2,}\d+': 'total_length',
        '^Reference length +\d+': 'reference_length',
        '^GC \(%\) +\d+\.\d+': 'percent_GC',
        '^Reference GC \(%\) +\d+\.\d+': 'reference_percent_GC',
        '^Genome fraction \(%\) +\d+\.\d+': 'genome_fraction_percent',
        '^Duplication ratio +\d+\.\d+': 'duplication_ratio',
        '^Complete BUSCO \(\%\) +\d+\.\d+': 'complete_busco_percent',
        '^Partial BUSCO \(\%\) +\d+\.\d+': 'partial_busco_percent',
    }
    
    quast_result = {}
    for line in quast_output:
        for regex, key in quast_report_parsing_regexes.items():
            if re.match(regex, line):
                quast_result[key] = parse_quast_report_line(line)
    
    return quast_result