import json


def decode_extra_parameters(metadata):
    """Returns a dictionary parsed from the json string stored
    in extra_parameters

    Parameters
    ----------
    metadata
        A SolarForecastArbiter.datamodel class with an extra_parameters
        attribute

    Returns
    -------
    dict
        The extra parameters as a python dictionary

    Raises
    ------
    ValueError
        If parameters cannot be decoded or are None. Or if missing the
        required keys: network, network_api_id, network_api_abbreviation
        and observation_interval_length.
    """
    try:
        params = json.loads(metadata.extra_parameters)
    except (json.decoder.JSONDecodeError, TypeError):
        raise ValueError(f'Could not read extra parameters of {metadata.name}')
    required_keys = ['network', 'network_api_id', 'network_api_abbreviation',
                     'observation_interval_length']
    if not all([key in params for key in required_keys]):
        raise ValueError(f'{metadata.name} is missing required extra '
                         'parameters.')
    return params