import csv


def parse_kraken_result(path_to_kraken_result):
    """
    Args:
        path_to_kraken_result (str): Path to the kraken report file.

    Returns:
        list(dict): Parsed kraken report with species-level results.
        For example:
        [
            { "fragment_percent": 84.08,
              "fragment_count_root": 195536,
              "fragment_count_taxon": 192561,
              "rank_code": "S",
              "ncbi_taxon_id": "562",
              "taxon_name": "Escherichia coli",
            },
            { "fragment_percent": 12.1,
              ...
            }
        ]
        See kraken manual for more detail on report fields:
        http://ccb.jhu.edu/software/kraken/MANUAL.html#sample-report-output-format
    """

    # Associate a field name with a function for parsing that field
    kraken_report_fields = {
        'fragment_percent': lambda x: float(x.strip()),
        'fragment_count_root': lambda x: int(x),
        'fragment_count_taxon': lambda x: int(x),
        'rank_code': lambda x: x,
        'ncbi_taxon_id': lambda x: x,
        'taxon_name': lambda x: x.strip()
    }
    
    with open(path_to_kraken_result) as krakenfile:
        reader = csv.DictReader(krakenfile, delimiter='\t', fieldnames=list(kraken_report_fields))
        parsed_kraken_result = []
        kraken_record = {}
        for row in reader:
            for field_name, parse in kraken_report_fields.items():
                kraken_record[field_name] = parse(row[field_name])
            parsed_kraken_result.append(kraken_record.copy())
    return parsed_kraken_result