import random

plaintext = input("ENTER THE PLAINTEXT: ")
plainStorage = list(plaintext)
key = int(input("ENTER THE KEY: "))
storage = []  # Stores ciphertext

print("ENCRYPTED TEXT IS: ", end="")
for letter in plaintext:
    if letter == " ":  # print empty space, if whitespace is found in the plaintext.
        print(" ", end="")
        storage.append(letter)
        continue
    # 'cipherLetter' stores the Ascii value of the letter, and updates it with the key.
    cipherLetter = ord(letter)
    cipherLetter = cipherLetter + key

    if letter.isupper():
        model = 90  # Ascii of 'Z'
    else:
        model = 122  # Ascii of 'z'

    # checks if 'cipherLetter' is within the boundaries of the alphabet.
    if cipherLetter <= model:
        print(chr(cipherLetter), end='')
        storage.append(cipherLetter)

    # If cipherLetter is greater than the Ascii of 'z', recalculate the new cipherLetter.
    else:
        cipherLetter = (cipherLetter % model) + (model - 26)
        print(chr(cipherLetter), end='')
        storage.append(cipherLetter)
print("\n")

choice = input("DO YOU WANT TO DECRYPT, YES OR NO? ").upper()
if choice == 'YES':
    print("DECRYPTED TEXT IS: ", end="")
    flag = True
    while flag:  # Generates a random integer until the correct integer is found
        guessKey = random.randint(0, 26)
        storage2 = []
        for i in storage:
            if i == " ":
                storage2.append(i)
                continue

            plaintext = i - guessKey

            if chr(i).isupper():
                modelS = 65  # Ascii of 'A' I switched to 'A' because we want to retrace our steps backwards
            else:
                modelS = 97  # Ascii of 'a'

            # checks if 'plainLetter' is within the boundaries of the alphabet.
            if plaintext >= modelS:
                storage2.append(chr(plaintext))

            # If cipherLetter is greater than the Ascii of 'z', recalculate the new cipherLetter.
            else:
                plaintext = (modelS + 26) - (modelS % plaintext)
                storage2.append(chr(plaintext))

        if plainStorage == storage2:
            answer = ''.join(storage2)
            print(answer)
            flag = False
        else:
            continue

else:
    print("SAFELY ENCRYPTED!")