#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to set up advanced remarketing.

Creates a rule-based user list defined by an expression rule for users who have
either checked out in November, or December, OR visited the checkout page with
more than one item in their cart.
"""

import argparse
import sys
from uuid import uuid4

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
    """
    # Get the UserListService client.
    user_list_service = client.get_service("UserListService")

    # Creates the operation.
    user_list_operation = client.get_type("UserListOperation")

    # Creates a user list.
    user_list = user_list_operation.create
    user_list.name = f"My expression rule user list #{uuid4()}"
    user_list.description = (
        "Users who checked out in November or December OR visited the "
        "checkout page with more than one item in their cart"
    )
    user_list.membership_status = client.enums.UserListMembershipStatusEnum.OPEN
    user_list.membership_life_span = 90

    # Defines a representation of a user list that is generated by a rule.
    rule_based_user_list_info = user_list.rule_based_user_list
    rule_based_user_list_info.prepopulation_status = (
        client.enums.UserListPrepopulationStatusEnum.REQUESTED
    )

    # Creates an ExpressionRuleUserListInfo object, or a boolean rule that
    # defines this user list. The default rule_type for a UserListRuleInfo
    # object is OR of ANDs (disjunctive normal form). That is, rule items will
    # be ANDed together within rule item groups and the groups themselves will
    # be ORed together.
    expression_rule_user_list_info = (
        rule_based_user_list_info.expression_rule_user_list
    )

    # Creates a rule group that includes the checkout and cart size rules.
    # Combining the two rule items into a UserListRuleItemGroupInfo object
    # causes Google Ads to AND their rules together. To instead OR the rules
    # together, each rule should be placed in its own rule item group.
    checkout_and_cart_size_rule_group = client.get_type(
        "UserListRuleItemGroupInfo"
    )
    # Creates a rule targeting any user that visited the checkout page.
    # [START setup_advanced_remarketing]
    checkout_rule = client.get_type("UserListRuleItemInfo")

    # The rule variable name must match a corresponding key name fired from a
    # pixel. To learn more about setting up remarketing tags, visit:
    # https://support.google.com/google-ads/answer/2476688.
    #
    # To learn more about remarketing events and parameters, visit:
    # https://support.google.com/google-ads/answer/7305793.
    checkout_rule.name = "ecomm_pagetype"
    checkout_string_rule_item = checkout_rule.string_rule_item
    checkout_string_rule_item.operator = (
        client.enums.UserListStringRuleItemOperatorEnum.EQUALS
    )
    checkout_string_rule_item.value = "checkout"
    # [END setup_advanced_remarketing]

    # Creates a rule targeting any user that had more than one item in their
    # cart.
    # [START setup_advanced_remarketing_1]
    cart_size_rule = client.get_type("UserListRuleItemInfo")
    # The rule variable name must match a corresponding key name fired from a
    # pixel.
    cart_size_rule.name = "cart_size"
    cart_size_number_rule_item = cart_size_rule.number_rule_item
    cart_size_number_rule_item.operator = (
        client.enums.UserListNumberRuleItemOperatorEnum.GREATER_THAN
    )
    cart_size_number_rule_item.value = 1.0
    # [END setup_advanced_remarketing_1]

    # Creates a rule group targeting users who checked out between November
    # and December by using the start and end date rules. Combining the two
    # rule items into a UserListRuleItemGroupInfo object causes Google Ads to
    # AND their rules together. To instead OR the rules together, each rule
    # should be placed in its own rule item group.
    checkout_date_rule_group = client.get_type("UserListRuleItemGroupInfo")

    # Creates the rule item for checkout start date.
    # The tags and keys used below must have been in place in the past for the
    # date range specified in the rules.
    # [START setup_advanced_remarketing_3]
    start_date_rule = client.get_type("UserListRuleItemInfo")
    start_date_rule.name = "checkoutdate"
    start_date_rule_item = start_date_rule.date_rule_item
    # Available UserListDateRuleItemOperators can be found at:
    # https://developers.google.com/google-ads/api/reference/rpc/latest/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator
    user_list_data_rule_item_operator_enum = (
        client.enums.UserListDateRuleItemOperatorEnum
    )
    start_date_rule_item.operator = user_list_data_rule_item_operator_enum.AFTER
    start_date_rule_item.value = "20191031"
    # [END setup_advanced_remarketing_3]

    # Creates the rule item for checkout end date.
    # [START setup_advanced_remarketing_4]
    end_date_rule = client.get_type("UserListRuleItemInfo")
    end_date_rule.name = "checkoutdate"
    end_date_rule_item = end_date_rule.date_rule_item
    end_date_rule_item.operator = user_list_data_rule_item_operator_enum.BEFORE
    end_date_rule_item.value = "20200101"
    # [END setup_advanced_remarketing_4]

    # [START setup_advanced_remarketing_2]
    checkout_and_cart_size_rule_group.rule_items.extend(
        [
            checkout_rule,
            cart_size_rule,
        ]
    )
    # [END setup_advanced_remarketing_2]
    # [START setup_advanced_remarketing_5]
    checkout_date_rule_group.rule_items.extend(
        [
            start_date_rule,
            end_date_rule,
        ]
    )
    # [END setup_advanced_remarketing_5]
    # [START setup_advanced_remarketing_6]
    expression_rule_user_list_info.rule.rule_item_groups.extend(
        [
            checkout_and_cart_size_rule_group,
            checkout_date_rule_group,
        ]
    )
    # [END setup_advanced_remarketing_6]

    # Issue a mutate request to add the user list, then print the results.
    response = user_list_service.mutate_user_lists(
        customer_id=customer_id, operations=[user_list_operation]
    )
    print(
        "Created user list with resource name "
        f"'{response.results[0].resource_name}.'"
    )


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v12")

    parser = argparse.ArgumentParser(
        description="Creates a rule-based user list defined by an expression "
        "rule for users who have either checked out in November, "
        "or December, OR visited the checkout page with more than "
        "one item in their cart."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.customer_id)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)
