from collections import namedtuple


def extract_image_id_from_longitudinal_segmentation(freesurfer_id):
    """Extract image ID from longitudinal segmentation folder.

    This function will extract participant, session and longitudinal ID from `freesurfer_id`.

    Example:
        >>> from clinica.utils.freesurfer import extract_image_id_from_longitudinal_segmentation
        >>> extract_image_id_from_longitudinal_segmentation('sub-CLNC01_ses-M00')
        image_id(participant_id='sub-CLNC01', session_id='ses-M00', long_id='')
        >>> extract_image_id_from_longitudinal_segmentation('sub-CLNC01_long-M0018')
        image_id(participant_id='sub-CLNC01', session_id='', long_id='long-M0018')
        >>> extract_image_id_from_longitudinal_segmentation('sub-CLNC01_ses-M00.long.sub-CLNC01_long-M00M18')
        image_id(participant_id='sub-CLNC01', session_id='ses-M00', long_id='long-M00M18')
    """

    image_id = namedtuple("image_id", ["participant_id", "session_id", "long_id"])

    # Case 'sub-CLNC01_ses-M00.long.sub-CLNC01_long-M00M18'
    if ".long." in freesurfer_id:
        participant_id = freesurfer_id.split(".long.")[0].split("_")[0]
        session_id = freesurfer_id.split(".long.")[0].split("_")[1]
        long_id = freesurfer_id.split(".long.")[1].split("_")[1]
    # Case 'sub-CLNC01_long-M00M18'
    elif "long-" in freesurfer_id:
        participant_id = freesurfer_id.split("_")[0]
        session_id = ""
        long_id = freesurfer_id.split("_")[1]
    # Case 'sub-CLNC01_ses-M00'
    else:
        participant_id = freesurfer_id.split("_")[0]
        session_id = freesurfer_id.split("_")[1]
        long_id = ""

    return image_id(participant_id, session_id, long_id)