import json
import boto3
from botocore.exceptions import ClientError
import logging
import urllib3

logger = logging.getLogger()
logger.setLevel(logging.INFO)

SUCCESS = "SUCCESS"
FAILED = "FAILED"

def send_response(event, context, response_status, response_data):
    """Send a response to CloudFormation"""
    response_body = {
        'Status': response_status,
        'Reason': f'See the details in CloudWatch Log Stream: {context.log_stream_name}',
        'PhysicalResourceId': context.log_stream_name,
        'StackId': event['StackId'],
        'RequestId': event['RequestId'],
        'LogicalResourceId': event['LogicalResourceId'],
        'Data': response_data
    }

    logger.info('Response body: %s', json.dumps(response_body))

    try:
        http = urllib3.PoolManager()
        response = http.request(
            'PUT',
            event['ResponseURL'],
            headers={'Content-Type': ''},
            body=json.dumps(response_body).encode('utf-8')
        )
        logger.info('Status code: %s', response.status)
        return True
    except Exception as e:
        logger.error('Error sending response: %s', str(e))
        return False

def lambda_handler(event, context):
    try:
        logger.info('Received event: %s', json.dumps(event))
        
        # Extract properties from the event
        properties = event['ResourceProperties']
        bucket_name = properties['BucketName']
        notification_config = properties['NotificationConfiguration']
        
        s3 = boto3.client('s3')
        
        if event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
            # Put bucket notification configuration
            logger.info('Configuring bucket notification for %s', bucket_name)
            s3.put_bucket_notification_configuration(
                Bucket=bucket_name,
                NotificationConfiguration=notification_config
            )
            logger.info('Successfully configured bucket notification')
            send_response(event, context, SUCCESS, {
                'Message': f'Successfully configured notification for bucket {bucket_name}'
            })
        
        elif event['RequestType'] == 'Delete':
            # Remove bucket notification configuration
            logger.info('Removing bucket notification from %s', bucket_name)
            s3.put_bucket_notification_configuration(
                Bucket=bucket_name,
                NotificationConfiguration={}
            )
            logger.info('Successfully removed bucket notification')
            send_response(event, context, SUCCESS, {
                'Message': f'Successfully removed notification from bucket {bucket_name}'
            })
            
    except Exception as e:
        logger.error('Error: %s', str(e))
        send_response(event, context, FAILED, {
            'Error': str(e)
        }) 