import boto3
from botocore.exceptions import ClientError
import uuid
import json

# A script to create and configure an S3 bucket for static website hosting using Boto3.

# --- Configuration ---
REGION = "us-east-1"
# Bucket names must be globally unique.
BUCKET_NAME = f"my-static-website-bucket-boto3-{uuid.uuid4().hex[:8]}"
INDEX_DOC = "index.html"
ERROR_DOC = "error.html"

s3_client = boto3.client('s3', region_name=REGION)

def create_s3_bucket():
    """Creates an S3 bucket and configures it for static website hosting."""
    try:
        # --- 1. Create S3 Bucket ---
        print(f"Creating S3 bucket: {BUCKET_NAME}...")
        s3_client.create_bucket(
            Bucket=BUCKET_NAME,
            CreateBucketConfiguration={'LocationConstraint': REGION} if REGION != 'us-east-1' else {}
        )
        print("Bucket created successfully.")

        # --- 2. Disable Block Public Access ---
        print("Updating public access block settings...")
        s3_client.put_public_access_block(
            Bucket=BUCKET_NAME,
            PublicAccessBlockConfiguration={
                'BlockPublicAcls': False,
                'IgnorePublicAcls': False,
                'BlockPublicPolicy': False,
                'RestrictPublicBuckets': False
            }
        )
        print("Public access block settings updated.")

        # --- 3. Apply a Public-Read Bucket Policy ---
        print("Applying bucket policy...")
        policy = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Sid": "PublicReadGetObject",
                    "Effect": "Allow",
                    "Principal": "*",
                    "Action": "s3:GetObject",
                    "Resource": f"arn:aws:s3:::{BUCKET_NAME}/*"
                }
            ]
        }
        s3_client.put_bucket_policy(Bucket=BUCKET_NAME, Policy=json.dumps(policy))
        print("Bucket policy applied.")

        # --- 4. Configure Static Website Hosting ---
        print("Configuring static website hosting...")
        website_configuration = {
            'ErrorDocument': {'Key': ERROR_DOC},
            'IndexDocument': {'Suffix': INDEX_DOC},
        }
        s3_client.put_bucket_website(
            Bucket=BUCKET_NAME,
            WebsiteConfiguration=website_configuration
        )
        print("Static website hosting configured.")

        # --- 5. Upload Sample Files ---
        print("Uploading sample index.html and error.html...")
        index_content = "<html><body><h1>Welcome to the S3 Static Website! (Managed by Boto3)</h1></body></html>"
        error_content = "<html><body><h1>404 - Page Not Found (Managed by Boto3)</h1></body></html>"

        s3_client.put_object(
            Bucket=BUCKET_NAME,
            Key=INDEX_DOC,
            Body=index_content,
            ContentType='text/html'
        )
        s3_client.put_object(
            Bucket=BUCKET_NAME,
            Key=ERROR_DOC,
            Body=error_content,
            ContentType='text/html'
        )
        print("Sample files uploaded.")

        # --- 6. Output Website URL ---
        website_url = f"http://{BUCKET_NAME}.s3-website-{REGION}.amazonaws.com"
        print("\n--- Static website setup complete! ---")
        print(f"Bucket Name: {BUCKET_NAME}")
        print(f"Website URL: {website_url}")

    except ClientError as e:
        print(f"An error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    create_s3_bucket()
