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


from typing import Mapping, Tuple, Optional


# Parse a GCP global_name into (service_type, region, account_id, resource)
# Here are some examples of global names:
# //compute.googleapis.com/project_commitments/1046088257743/regions/asia-southeast1/commitment/4227504504096917444
# //cloudfunctions.googleapis.com/projects/db-cm-dev/locations/us-central1/functions/siteanalytics-bigquery
# //appengine.googleapis.com/projects/db-cm-pro/locations/us-east1/services/default
# //compute.googleapis.com/projects/1056877253080/global/forwarding_rule/2442600577874703148
# //compute.googleapis.com/projects/1057946425622/regions/europe-west4/address/1001187661888191716
# //compute.googleapis.com/projects/498376270667/zones/us-west1-a/allocation/100399536662728269
# //compute.googleapis.com/projects/917571452258/zones/us-central1-f/instances/1003804357848473668
# //container.googleapis.com/projects/affirm-poc/locations/us-central1/clusters/blueshift-dev
# //firestore.googleapis.com/projects/db-cm-dev/databases/(default)
# //run.googleapis.com/projects/bugsnag-secrets-manager-poc/locations/us-west1/services/berglas-webhook
# //sqladmin.googleapis.com/projects/bp-ecom-int-qd/instances/bp-keycloak-blue-vu

def get_resource_global_name_components(lineitem_fields: Mapping) -> Tuple[str, Optional[str], str, str]:
    resource_id = lineitem_fields.get('lineitem_resourceid') or ''
    productcode = lineitem_fields.get('lineitem_productcode') or ''

    try:
        global_name_parts = resource_id[2:].split('/')[1:]
        project = global_name_parts[1]

        def resolve_region():
            next_part = global_name_parts[2]
            if next_part == 'global':
                return 'global', global_name_parts[3:]
            if next_part in ('regions', 'locations', 'zones'):
                return global_name_parts[3], global_name_parts[4:]
            return None, global_name_parts[2:]

        region, resource_parts = resolve_region()
        resource = '/'.join(resource_parts)

        return productcode, region, project, resource
    except IndexError as err:
        raise ValueError() from err
