from statistics import mean


def _merge_qc_stats(r1: dict, r2: dict) -> dict:
    """
    Merge appropriate metrics (e.g. coverage) for R1 and R2 FASTQs.

    Args:
        r1 (dict): parsed metrics associated with R1 FASTQ
        r2 (dict): parsed metrics associated with R2 FASTQ

    Returns:
        dict: the merged FASTQ metrics
    """
    merged = {
        'qc_stats': {},
        'r1_per_base_quality': r1['per_base_quality'],
        'r2_per_base_quality': r2['per_base_quality'],
        'r1_read_lengths': r1['read_lengths'],
        'r2_read_lengths': r2['read_lengths']
    }
    for key in r1['qc_stats']:
        if key in ['total_bp', 'coverage', 'read_total']:
            merged['qc_stats'][key] = r1['qc_stats'][key] + r2['qc_stats'][key] if r2 else r1['qc_stats'][key]
        else:
            val = mean([r1['qc_stats'][key], r2['qc_stats'][key]]) if r2 else r1['qc_stats'][key]
            merged['qc_stats'][key] = f'{val:.4f}' if isinstance(val, float) else val

    return merged