# Copyright (c) 2017 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

"""
Contains functions for creating CloudZero Relationship IDs (CZRELs).
CZRELs are used to unambiguously and uniquely identify explicit and derived relationships between resources and other
entities we extract from a cloud domain.
"""

from czid.czrel.validate import is_valid


def create_from_resources(subject=None, object=None, predicate=None):
    """
    Create a CZREL from CZRNs and a predicate

    Args:
        subject: (str) - a CZRN that acts as the "origin" or "source" of the relationship
        object: (str) - a CZRN that acts as the "target" or "destination" of the relationship
        predicate: (str) - A unique tag which indicates the nature of the relationship

    Returns:
        str - the new CZREL

    Raises:
        ValueError - if inputs are missing or invalid

    >>> create_from_resources(subject='czrn:aws:iam:cross-region:123456789012:aws-account:root', object='czrn:aws:health:us-east-1:public:event:AWS_EC2_EXAMPLE_ID', predicate='is-a-test-for')
    'czrel>czrn:aws:iam:cross-region:123456789012:aws-account:root>is-a-test-for>czrn:aws:health:us-east-1:public:event:AWS_EC2_EXAMPLE_ID'

    >>> create_from_resources(subject='foo', object='bar', predicate='is-a-test-for')
    Traceback (most recent call last):
    ...
    ValueError: Subject and object must be valid CZRNs - subject: foo, object: bar
    """
    if not all([subject, object, predicate]):
        raise ValueError(f'Subject, object, and predicate must be specified - subject: {subject}, '
                         f'object: {object}, predicate: {predicate}')
    czrel = f'czrel>{subject}>{predicate}>{object}'
    if not is_valid(czrel):
        raise ValueError(f'Subject and object must be valid CZRNs - subject: {subject}, object: {object}')
    return czrel
