from .base_agent import BaseAgent
from ..aws_connector import AWSConnector

class SNSAgent(BaseAgent):
    """
    An agent specialized in handling AWS Simple Notification Service (SNS) tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to SNS.
        """
        if command == 'smart_create_topic_and_subscribe_email':
            topic_name = kwargs.get('topic_name', '')
            email_address = kwargs.get('email_address', '')
            region = kwargs.get('region', '')
            print(f"You are about to smart-create an SNS topic '{topic_name}' and subscribe '{email_address}' in {region}.")
            confirm = input("Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._smart_create_topic_and_subscribe_email(**kwargs)
            else:
                return {"status": "cancelled", "message": "Smart Create SNS topic and subscribe email command cancelled by user."}
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by SNSAgent.")

    def _smart_create_topic_and_subscribe_email(self, region: str, topic_name: str, email_address: str):
        """
        Creates an SNS topic and subscribes an email address to it.
        """
        print(f"SNSAgent: Smart creating topic '{topic_name}' and subscribing email '{email_address}' in region {region}...")
        try:
            sns_client = AWSConnector.get_client('sns', region_name=region)

            # 1. Create SNS Topic
            create_topic_response = sns_client.create_topic(Name=topic_name)
            topic_arn = create_topic_response['TopicArn']
            print(f"SNS Topic '{topic_name}' ({topic_arn}) created.")

            # 2. Subscribe Email to Topic
            subscribe_response = sns_client.subscribe(
                TopicArn=topic_arn,
                Protocol='email',
                Endpoint=email_address
            )
            subscription_arn = subscribe_response['SubscriptionArn']
            print(f"Email '{email_address}' subscribed to topic. Subscription ARN: {subscription_arn}. (Confirmation email sent)")

            return {"status": "success", "message": f"SNS topic '{topic_name}' created and email '{email_address}' subscribed. Confirmation email sent.", "topic_arn": topic_arn, "subscription_arn": subscription_arn}
        except Exception as e:
            print(f"Error during smart SNS topic creation and email subscription: {e}")
            return {"status": "error", "message": str(e)}
