import glob


def find_bams(project, stats_base_dir):
    """
    Find all bams for a project and return a dictionary of "igo_id" -> "bam list"
    """
    
    bam_unix_regex = stats_base_dir + '/**/*_IGO_' + project + '_*.bam'
    print("Searching for all .bams for project {} starting in folder {} matching glob {}".format(project, stats_base_dir, bam_unix_regex))
    # search for all .bams named like /igo/staging/stats/DIANA_0479_BHM2NVDSX3/RNA/GA28_ot_IGO_12785_H_1.bam
    project_bams = glob.glob(bam_unix_regex, recursive=True)  # recurisive=True causes the search to be a bit slow (more than 1 min)
    print("Total bams found {}".format(len(project_bams)))

    bamdict = {}
    for bam in project_bams:
        igo_id = bam.split("_IGO_")[1]
        igo_id = igo_id.replace(".bam","")
        print("Adding IGO ID {} bam {} to bam dictionary".format(igo_id, bam))
        if igo_id in bamdict: # add the bam to the list of bams for that igoId
            bamdict[igo_id].append(bam)
        else:
            bamdict.update({igo_id:[bam]}) # add dictionary entry with 1 list item
    
    return bamdict