# 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 efficiently validating a CZRN.
CZRNs are used to unambiguously and uniquely identify any resource from any cloud provider, and even covers cases
where a resource might be observed from the Internet, and resources which may not have explicit existence
in a cloud environment.
"""

import re

from czid.common.regions import ALL_REGION_IDS
from czid.common.service_types import ALL_SERVICE_TYPES


def is_valid(input_id):
    """
    Determine if a given ID is a valid Resource ID (CZRN)
    Args:
        input_id (str): The ID value to check

    Returns:
        True if the ID is a valid resource ID else False

    >>> is_valid(None)
    False

    >>> is_valid('czrn:aws:lambda:us-west-2:123456789012:function:my-function')
    True

    >>> is_valid('foobar')
    False
    """
    if not input_id:
        return False
    czrn_match = CZRN_CAPTURE_REGEX.fullmatch(input_id)
    return czrn_match is not None


def _build_regex_pattern():
    service = '|'.join(ALL_SERVICE_TYPES)
    region = '|'.join(ALL_REGION_IDS)
    provider = r'aws|aws-cn|aws-us-gov|cz-global'
    resource_type = r'[a-z0-9-]+'
    account = r'\d{12}|public|unknown-account'
    return f'czrn:(?:{provider}):({service}):({region}):({account})+:({resource_type}):(.+)'


CZRN_PATTERN = _build_regex_pattern()
CZRN_CAPTURE_REGEX = re.compile(f'^{CZRN_PATTERN}$')
