from pathlib import Path


def _cope_names(input_dir, selected_cope=None):
    """Get COPE names from the first level analysis

    Parameters
    ----------
    input_dir:
        BIDS derivative - FSL feat first level outputs
        all feat directories should be derived from the same design
    selected_cope:
        A list of cope of interest, names matching the first level design


    Return
    ------
    selected_contrasts: List of tuple
        cope index and cope name
    """
    first_level = Path(input_dir)
    feat_dir = first_level.glob("sub-*/sub-*[0-9].feat/")
    con = list(feat_dir)[0] / "design.con"
    print(con)
    with open(con) as f:
        contrast_names = [
            line.split()[-1] for line in f.readlines() if "ContrastName" in line
        ]

    selected_contrasts = []
    for i, cn in enumerate(contrast_names):
        cope_idx = i + 1
        if type(selected_cope) is list:
            # check if names matches
            for sc in selected_cope:
                if sc in contrast_names:
                    if sc == cn:
                        selected_contrasts.append((cope_idx, cn))
                    else:
                        pass
                else:
                    print(f"selected contrast {sc} doesn't exisit. Typo?")
        else:
            selected_contrasts.append((cope_idx, cn))
    return selected_contrasts