import pathlib


def get_paths_to_patient_files(path_to_imgs, append_mask=True):
    """
    Get paths to all data samples, i.e., CT & PET images (and a mask) for each patient.

    Parameters
    ----------
    path_to_imgs : str
        A path to a directory with patients' data. Each folder in the directory must corresponds to a single patient.
    append_mask : bool
        Used to append a path to a ground truth mask.

    Returns
    -------
    list of tuple
        A list wherein each element is a tuple with two (three) `pathlib.Path` objects for a single patient.
        The first one is the path to the CT image, the second one - to the PET image. If `append_mask` is True,
        the path to the ground truth mask is added.
    """
    path_to_imgs = pathlib.Path(path_to_imgs)

    #patients = [p for p in os.listdir(path_to_imgs) if os.path.isdir(path_to_imgs / p)]
    
    patients = [f.name.split("_")[0] for f in path_to_imgs.rglob("*_ct*")]
    print(str(patients))
    paths = []
    for p in patients:
        path_to_ct = path_to_imgs / (p + '_ct.nii.gz')
        path_to_pt = path_to_imgs / (p + '_pt.nii.gz')

        if append_mask:
            path_to_mask = path_to_imgs / (p + '_gtvt.nii.gz')
            paths.append((path_to_ct, path_to_pt, path_to_mask))
        else:
            paths.append((path_to_ct, path_to_pt))
    return paths