import requests
import logging


def delete_peripheral(api_url: str, identifier: str, resource_id=None) -> dict:
    """ Deletes an existing peripheral from Nuvla, via the Agent API

    :param identifier: peripheral identifier (same as local filename)
    :param api_url: URL of the Agent API for peripherals
    :param resource_id: peripheral resource ID in Nuvla
    :return: Nuvla resource
    """

    if resource_id:
        url = f'{api_url}/{identifier}?id={resource_id}'
    else:
        url = f'{api_url}/{identifier}'

    try:
        r = requests.delete(url)
        r.raise_for_status()
        return r.json()
    except:
        logging.error(f'Cannot delete peripheral {identifier} from Nuvla. See agent logs for more info about the issue')
        # this will be caught by the calling block
        raise