from typing import Dict
from typing import List
import requests
import csv


def get_edam_ontology(version: str) -> Dict[str, List[str]]:
    """
    Parameters
    ----------
    version : str
        version of edam ontology to get.

    Returns
    -------
    Dict[str, List[str]]
        mapping between edam label to its parents, For example:
        {
            "Manual segmentation": [
                "Image segmentation",
                "Dense image annotation"
            ],
            "Semi-automatic segmentation": [
                "Image segmentation"
            ],
            "Sparse image annotation": [
                "Image annotation"
            ]
        }
    """
    version = f"_{version}" if version else version
    url = f'https://edamontology.org/EDAM-bioimaging{version}.csv'
    response = requests.get(url)
    if response.status_code != requests.codes.ok:
        response.raise_for_status()

    ontology = {
        category['Class ID']: {
            "label": category['Preferred Label'],
            "parents": category['Parents'].split("|")
        }
        for category in csv.DictReader(response.content.decode('utf-8').splitlines())
    }

    return {
        values['label']: [ontology[parent]['label'] for parent in values['parents'] if parent in ontology]
        for class_id, values in ontology.items()
    }