import boto3
from botocore.exceptions import ClientError
import time

# A script to enable AWS GuardDuty and then clean up using Boto3.

# --- Configuration ---
REGION = "us-east-1"

guardduty_client = boto3.client('guardduty', region_name=REGION)

def create_guardduty_detector():
    """Creates a GuardDuty detector."""
    print("--- Creating GuardDuty Detector ---")
    try:
        response = guardduty_client.create_detector(Enable=True)
        detector_id = response['DetectorId']
        print(f"GuardDuty Detector created with ID: {detector_id}")
        return detector_id
    except ClientError as e:
        if e.response['Error']['Code'] == 'BadRequestException' and 'already exists' in str(e):
            print("GuardDuty Detector already exists. Fetching ID.")
            response = guardduty_client.list_detectors()
            if response['DetectorIds']:
                detector_id = response['DetectorIds'][0]
                print(f"Existing GuardDuty Detector ID: {detector_id}")
                return detector_id
            else:
                raise Exception("Could not find existing GuardDuty detector.")
        else:
            print(f"Error creating detector: {e}")
            raise

def delete_guardduty_detector(detector_id):
    """Deletes the GuardDuty detector."""
    print(f"\n--- Deleting GuardDuty Detector '{detector_id}' ---")
    try:
        guardduty_client.delete_detector(DetectorId=detector_id)
        print("GuardDuty Detector deleted.")
    except ClientError as e:
        if e.response['Error']['Code'] == 'BadRequestException' and 'does not exist' in str(e):
            print(f"GuardDuty Detector '{detector_id}' not found, skipping deletion.")
        else:
            print(f"Error deleting detector: {e}")
            raise

def main():
    detector_id = None
    try:
        detector_id = create_guardduty_detector()

        print("\n--- GuardDuty Enabled Successfully! ---")
        print(f"Detector ID: {detector_id}")
        print("GuardDuty is now monitoring your AWS account for malicious activity.")

        input("Press Enter to delete the GuardDuty Detector...")

    except ClientError as e:
        print(f"An AWS client error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        if detector_id:
            delete_guardduty_detector(detector_id)
        print("\n--- GuardDuty demonstration and cleanup complete ---")

if __name__ == "__main__":
    main()
