from ..base_gcp_agent import BaseGCPAgent
from ..gcp_connector import GCPConnector
from google.cloud import pubsub_v1

class PubSubAgent(BaseGCPAgent):
    """
    An agent specialized in handling GCP Cloud Pub/Sub tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to Pub/Sub.
        """
        if command == 'smart_create_topic':
            topic_name = kwargs.get('topic_name', '')
            print(f"You are about to smart-create a Pub/Sub topic '{topic_name}'.")
            confirm = input("Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._smart_create_topic(**kwargs)
            else:
                return {"status": "cancelled", "message": "Smart Create Pub/Sub topic command cancelled by user."}
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by PubSubAgent.")

    def _smart_create_topic(self, project_id: str, topic_name: str):
        """
        Creates a Pub/Sub topic.
        """
        print(f"PubSubAgent: Smart creating topic '{topic_name}' in project '{project_id}'...")
        try:
            client = GCPConnector.get_pubsub_client()
            topic_path = client.topic_path(project_id, topic_name)

            try:
                client.get_topic(request={"topic": topic_path})
                return {"status": "success", "message": f"Pub/Sub topic '{topic_name}' already exists.", "topic_name": topic_name}
            except Exception:
                # Topic does not exist, create it
                client.create_topic(request={"name": topic_path})
                return {"status": "success", "message": f"Pub/Sub topic '{topic_name}' created successfully.", "topic_name": topic_name}
        except Exception as e:
            print(f"Error creating Pub/Sub topic: {e}")
            return {"status": "error", "message": str(e)}