import boto3
from botocore.exceptions import ClientError
import time

# A script to create a Kinesis Data Stream using Boto3.

# --- Configuration ---
REGION = "us-east-1"
STREAM_NAME = "MyBoto3KinesisStream"
SHARD_COUNT = 1 # Number of shards for the stream

kinesis_client = boto3.client('kinesis', region_name=REGION)

def create_kinesis_stream():
    """Creates a Kinesis Data Stream."""
    print(f"--- Creating Kinesis Data Stream: {STREAM_NAME} with {SHARD_COUNT} shard(s) ---")
    try:
        kinesis_client.create_stream(
            StreamName=STREAM_NAME,
            ShardCount=SHARD_COUNT
        )
        print("Kinesis Data Stream created. Waiting for it to become active...")
        kinesis_client.get_waiter('stream_exists_v2').wait(StreamName=STREAM_NAME)
        print(f"Kinesis Data Stream '{STREAM_NAME}' is active.")
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceInUseException':
            print(f"Kinesis Data Stream '{STREAM_NAME}' already exists. Skipping creation.")
        else:
            print(f"Error creating Kinesis stream: {e}")
            raise

def get_stream_arn():
    """Retrieves the ARN of the Kinesis Data Stream."""
    try:
        response = kinesis_client.describe_stream(StreamName=STREAM_NAME)
        return response['StreamDescription']['StreamARN']
    except ClientError as e:
        print(f"Error describing stream: {e}")
        raise

def delete_kinesis_stream():
    """Deletes the Kinesis Data Stream."""
    print(f"\n--- Deleting Kinesis Data Stream: {STREAM_NAME} ---")
    try:
        kinesis_client.delete_stream(StreamName=STREAM_NAME)
        print("Waiting for stream to be deleted...")
        kinesis_client.get_waiter('stream_not_exists_v2').wait(StreamName=STREAM_NAME)
        print(f"Kinesis Data Stream '{STREAM_NAME}' deleted successfully.")
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print(f"Kinesis Data Stream '{STREAM_NAME}' not found, skipping deletion.")
        else:
            print(f"Error deleting Kinesis stream: {e}")
            raise

def main():
    try:
        create_kinesis_stream()
        stream_arn = get_stream_arn()

        print("\n--- Kinesis Data Stream Setup Complete! ---")
        print(f"Stream ARN: {stream_arn}")
        print("You can now put records into this stream.")

        input("Press Enter to delete the Kinesis Data Stream...")

    except ClientError as e:
        print(f"An AWS client error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        delete_kinesis_stream()
        print("\n--- Kinesis Data Stream demonstration and cleanup complete ---")

if __name__ == "__main__":
    main()
