import json
from copy import deepcopy
from typing import Any, Dict, Union
from device.proto.context_pb2 import ConfigActionEnum

def config_rule(action : ConfigActionEnum, resource_key : str, resource_value : Union[str, Dict[str, Any]]):
    if not isinstance(resource_value, str): resource_value = json.dumps(resource_value, sort_keys=True)
    return {'action': action, 'resource_key': resource_key, 'resource_value': resource_value}

def config_rule_set(resource_key : str, resource_value : Union[str, Dict[str, Any]]):
    return config_rule(ConfigActionEnum.CONFIGACTION_SET, resource_key, resource_value)

def config_rule_delete(resource_key : str, resource_value : Union[str, Dict[str, Any]]):
    return config_rule(ConfigActionEnum.CONFIGACTION_DELETE, resource_key, resource_value)

def endpoint_id(device_id, endpoint_uuid, topology_id=None):
    result = {'device_id': deepcopy(device_id), 'endpoint_uuid': {'uuid': endpoint_uuid}}
    if topology_id is not None: result['topology_id'] = deepcopy(topology_id)
    return result

def endpoint(device_id, endpoint_uuid, endpoint_type, topology_id=None):
    return {
        'endpoint_id': endpoint_id(device_id, endpoint_uuid, topology_id=topology_id),
        'endpoint_type': endpoint_type,
    }
