from .base_agent import BaseAgent
from ..aws_connector import AWSConnector
import time

class CloudFrontAgent(BaseAgent):
    """
    An agent specialized in handling AWS CloudFront tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to CloudFront.
        """
        if command == 'smart_create_s3_distribution':
            bucket_name = kwargs.get('bucket_name', '')
            region = kwargs.get('region', '')
            print(f"You are about to smart-create a CloudFront distribution for S3 bucket '{bucket_name}' in {region}.")
            confirm = input("This will create a new CloudFront web distribution. Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._smart_create_s3_distribution(**kwargs)
            else:
                return {"status": "cancelled", "message": "Smart Create CloudFront distribution command cancelled by user."}
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by CloudFrontAgent.")

    def _smart_create_s3_distribution(self, region: str, bucket_name: str, default_root_object: str = 'index.html'):
        """
        Creates a CloudFront web distribution for an S3 bucket.
        """
        print(f"CloudFrontAgent: Smart creating S3 distribution for bucket '{bucket_name}' in region {region}...")
        try:
            cloudfront_client = AWSConnector.get_client('cloudfront', region_name=region)
            s3_client = AWSConnector.get_client('s3', region_name=region)

            # Check if S3 bucket exists
            try:
                s3_client.head_bucket(Bucket=bucket_name)
            except s3_client.exceptions.ClientError as e:
                if e.response['Error']['Code'] == '404':
                    return {"status": "error", "message": f"S3 bucket '{bucket_name}' not found in region {region}. Please create it first."}
                else:
                    raise

            # Get S3 bucket website endpoint for origin
            # Note: This assumes the S3 bucket is configured for static website hosting.
            # For a regular S3 bucket, the origin domain name would be bucket_name.s3.amazonaws.com
            # For simplicity, we'll use the regular S3 endpoint for now.
            s3_origin_domain = f'{bucket_name}.s3.{region}.amazonaws.com'

            # Create CloudFront distribution
            distribution_config = {
                'CallerReference': str(time.time()),
                'Comment': f'Distribution for S3 bucket {bucket_name}',
                'Enabled': True,
                'Origins': {
                    'Quantity': 1,
                    'Items': [
                        {
                            'Id': 'S3-Origin',
                            'DomainName': s3_origin_domain,
                            'S3OriginConfig': {
                                'OriginAccessIdentity': '' # No OAI for public S3, or use a specific one
                            }
                        },
                    ]
                },
                'DefaultCacheBehavior': {
                    'TargetOriginId': 'S3-Origin',
                    'ViewerProtocolPolicy': 'allow-all',
                    'TrustedSigners': {'Enabled': False, 'Quantity': 0},
                    'ForwardedValues': {'QueryString': False, 'Cookies': {'Forward': 'none'}},
                    'MinTTL': 0,
                    'AllowedMethods': {'Quantity': 2, 'Items': ['GET', 'HEAD']},
                    'SmoothStreaming': False,
                    'DefaultTTL': 86400,
                    'MaxTTL': 31536000,
                    'Compress': True,
                    'LambdaFunctionAssociations': {'Quantity': 0},
                    'FieldLevelEncryptionId': ''
                },
                'CacheBehaviors': {'Quantity': 0},
                'CustomErrorResponses': {'Quantity': 0},
                'PriceClass': 'PriceClass_100',
                'Restrictions': {'GeoRestriction': {'RestrictionType': 'none', 'Quantity': 0}},
                'ViewerCertificates': {'CloudFrontDefaultCertificate': True},
                'IsIPV6Enabled': True,
                'DefaultRootObject': default_root_object
            }

            create_dist_response = cloudfront_client.create_distribution(DistributionConfig=distribution_config)
            distribution_id = create_dist_response['Distribution']['Id']
            distribution_domain_name = create_dist_response['Distribution']['DomainName']

            return {"status": "success", "message": f"CloudFront distribution '{distribution_id}' created for S3 bucket '{bucket_name}'. Domain Name: {distribution_domain_name}", "distribution_id": distribution_id, "domain_name": distribution_domain_name}
        except Exception as e:
            print(f"Error during smart CloudFront distribution creation: {e}")
            return {"status": "error", "message": str(e)}
