# Copyright (c) 2020 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


"""
Notes

lineitem_productcode to get service, like AmazonS3
lineitem_resourceid to get the resource id, which is normally a ARN.... but....
vol, instances and buckets appear in billing as resource ID's without ARNs

"""

from czid.common.service_types import SERVICE_TRANSFORMS
from czid.czrn.internal.resource_ids import \
    get_resource_type_from_resource_string

# AWS has started assigning resource IDs to some service usage billing. If we
# see one of these, treat it as if the resource ID was None
INVALID_RESOURCE_IDS = {'AWSXRayTag'}


def get_billing_lineitem_components(lineitem_fields):
    service = _service_type_from_billing_fields(lineitem_fields)
    region = get_region_from_billing_fields(lineitem_fields)
    account_id = get_account_id_from_billing_fields(lineitem_fields)

    resource = lineitem_fields.get('lineitem_resourceid')

    if resource and resource not in INVALID_RESOURCE_IDS:
        resource = lineitem_fields.get('lineitem_resourceid').strip()
    elif lineitem_fields.get('lineitem_usagetype'):
        resource = f"usage/{lineitem_fields.get('lineitem_usagetype')}".strip()
    else:
        resource = None

    return service, region, account_id, resource


def resource_type_from_billing_fields(service_type, lineitem_fields):
    """
    Try and get the resource type from a non ARN resource id/service type combo

    Args:
        service_type (str):
        lineitem_fields (dict):

    Returns:
        str or None

    """
    return get_resource_type_from_resource_string(service_type, lineitem_fields.get('lineitem_resourceid', '').strip())


def _service_type_from_billing_fields(lineitem_fields):
    """
    Determine what service it belongs to using lineitem_productcode,

    Args:
        lineitem_fields (dict):

    Returns:
        str or None:
    """
    raw_productcode = lineitem_fields.get('lineitem_productcode') or ''
    try:
        # yes the double replace is faster than a regex
        service = raw_productcode.lower().replace('aws', '').replace('amazon', '')
    except AttributeError:
        # In the extremely unlikely scenario where productcode isn't a string
        return str(raw_productcode)

    return SERVICE_TRANSFORMS.get(service) or service


def get_region_from_billing_fields(lineitem_fields):
    # what region the resource is in using product_region.
    # noinspection PyBroadException
    try:
        region = lineitem_fields.get('product_region', '').lower().strip()
    except Exception:
        return None
    return region


def get_account_id_from_billing_fields(lineitem_fields):
    """
    The account id to which the resource belongs.
    using lineitem_usageaccountid

    Args:
        lineitem_fields (dict):

    Returns:
        str or None:
    """
    # noinspection PyBroadException
    try:
        account_id = lineitem_fields.get('lineitem_usageaccountid', '').strip() or None
    except Exception:
        return None
    return account_id
