import json
from typing import Any, Dict, Union
from service.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 constraint(constraint_type, constraint_value):
    return {'constraint_type': str(constraint_type), 'constraint_value': str(constraint_value)}

def context_id(context_uuid):
    return {'context_uuid': {'uuid': context_uuid}}

def topology_id(topology_uuid, context_uuid=None):
    result = {'topology_uuid': {'uuid': topology_uuid}}
    if context_uuid is not None: result['context_id'] = context_id(context_uuid)
    return result

def device_id(device_uuid):
    return {'device_uuid': {'uuid': device_uuid}}

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

def endpoint(device_uuid, endpoint_uuid, endpoint_type, context_uuid=None, topology_uuid=None):
    return {
        'endpoint_id': endpoint_id(device_uuid, endpoint_uuid, context_uuid=context_uuid, topology_uuid=topology_uuid),
        'endpoint_type': endpoint_type,
    }
