<commit_before>"""Agent Resource functions."""

# Copyright 2021 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.

import logging
from typing import Dict, List
import requests
from google.cloud.dialogflowcx_v3beta1 import services
import google.cloud.dialogflowcx_v3beta1.types as types
from google.protobuf import field_mask_pb2

from dfcx_scrapi.core.scrapi_base import ScrapiBase

# logging config
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)-8s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)


class Agents(ScrapiBase):
    """Core Class for CX Agent Resource functions."""

    def __init__(
        self,
        creds_path: str = None,
        creds_dict: Dict = None,
        creds=None,
        scope=False,
        agent_id: str = None,
    ):
        super().__init__(
            creds_path=creds_path,
            creds_dict=creds_dict,
            creds=creds,
            scope=scope,
        )

        if agent_id:
            self.agent_id = agent_id
            self.client_options = self._set_region(agent_id)

    def list_agents(self, location_id: str) -> List[types.Agent]:
        """Get list of all CX agents in a given GCP project

        Args:
          location_id: The GCP Project/Location ID in the following format
              `projects/<GCP PROJECT ID>/locations/<LOCATION ID>
        Returns:
          agents: List of Agent objects
        """
        request = types.agent.ListAgentsRequest()
        request.parent = location_id

        client_options = self._set_region(location_id)
        client = services.agents.AgentsClient(
            credentials=self.creds, client_options=client_options
        )

        response = client.list_agents(request)

        agents = []
        for page in response.pages:
            for agent in page.agents:
                agents.append(agent)

        return agents

    def get_agent(self, agent_id: str) -> types.Agent:
        """Retrieves a single CX agent resource object."""
        request = types.agent.GetAgentRequest()
        request.name = agent_id

        client_options = self._set_region(agent_id)
        client = services.agents.AgentsClient(
            credentials=self.creds, client_options=client_options
        )

        response = client.get_agent(request)

        return response

    def create_agent(
        self,
        project_id: str,
        display_name: str,
        gcp_region: str = "global",
        obj: types.Agent = None,
        **kwargs,
    ):
        """Create a Dialogflow CX Agent with given display name.

        By default the CX Agent will be created in the project that the user
        is currently authenticated to
        If the user provides an existing Agent object, create a new CX agent
        based on this object.

        Args:
          project_id: GCP project id where the CX agent will be created
          display_name: Human readable display name for the CX agent
          gcp_region: GCP region to create CX agent. Defaults to 'global'
          obj: (Optional) Agent object to create new agent from

        Returns:<commit_msg>added func get_agent_by_display_name<commit_after>"""Agent Resource functions."""

# Copyright 2021 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.

import logging
from typing import Dict, List
import requests
from google.cloud.dialogflowcx_v3beta1 import services
import google.cloud.dialogflowcx_v3beta1.types as types
from google.protobuf import field_mask_pb2
from dfcx_scrapi.core.scrapi_base import ScrapiBase


class Agents(ScrapiBase):
    """Core Class for CX Agent Resource functions."""
    # logging config
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)-8s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )


    def __init__(
        self,
        creds_path: str = None,
        creds_dict: Dict = None,
        creds=None,
        scope=False,
        agent_id: str = None,
    ):
        super().__init__(
            creds_path=creds_path,
            creds_dict=creds_dict,
            creds=creds,
            scope=scope,
        )

        if agent_id:
            self.agent_id = agent_id
            self.client_options = self._set_region(agent_id)

    def list_agents(self, location_id: str) -> List[types.Agent]:
        """Get list of all CX agents in a given GCP project

        Args:
          location_id: The GCP Project/Location ID in the following format
              `projects/<GCP PROJECT ID>/locations/<LOCATION ID>
        Returns:
          agents: List of Agent objects
        """
        request = types.agent.ListAgentsRequest()
        request.parent = location_id

        client_options = self._set_region(location_id)
        client = services.agents.AgentsClient(
            credentials=self.creds, client_options=client_options
        )

        response = client.list_agents(request)

        agents = []
        for page in response.pages:
            for agent in page.agents:
                agents.append(agent)

        return agents

    def get_agent(self, agent_id: str) -> types.Agent:
        """Retrieves a single CX agent resource object."""
        request = types.agent.GetAgentRequest()
        request.name = agent_id

        client_options = self._set_region(agent_id)
        client = services.agents.AgentsClient(
            credentials=self.creds, client_options=client_options
        )

        response = client.get_agent(request)

        return response
    
    def get_agent_by_display_name(
        self, 
        location_id: str,
        display_name: str
    ) -> types.Agent:
        """Get CX agent in a given GCP project by its human readable 
            display name.

        Args:
          location_id: The GCP Project/Location ID in the following format
              `projects/<GCP PROJECT ID>/locations/<LOCATION ID>
          display_name: human readable display name string of CX agent
        Returns:
          Agents: CX agent resource object. If no agent is found,
              returns None.
        """ 
        request = types.agent.ListAgentsRequest()
        request.parent = location_id

        client_options = self._set_region(location_id)
        client = services.agents.AgentsClient(
            credentials=self.creds, client_options=client_options
        )
        response = client.list_agents(request)
        
        possibleAgent = None
        for page in response.pages:
            for agent in page.agents:
                if agent.display_name == display_name:
                    return agent
                elif agent.display_name.lower() == display_name.lower():
                    possibleAgent = agent
        
        if possibleAgent:
            logging.warning(
                "display_name is case-sensitive. Did you mean \"%s\"?",
                            possibleAgent.display_name
            )
            
        return None

    def create_agent(
        self,
        project_id: str,
        display_name: str,
        gcp_region: str = "global",
        obj: types.Agent = None,
        **kwargs,
    ):
        """Create a Dialogflow CX Agent with given display name.

        By default the CX Agent will be created in the project that the user
        is currently authenticated to
        If the user provides an existing Agent object, create a new CX agent
        based on this object.

        Args:
          project_id: GCP project id where the CX agent will be created
          display_name: Human readable display name for the CX agent
          gcp_region: GCP region to create CX agent. Defaults to 'global'
          obj: (Optional) Agent object to create new agent from

        Returns:
{'fraction_non_alphanumeric': 0.07424328954882924, 'fraction_numerical': 0.0031981724728726442, 'mean_word_length': 2.253808992939428, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 14, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '753218', 'n_tokens_mistral': 2416, 'n_tokens_neox': 2314, 'n_words': 780}