#==================================================
# Lecture 20: Codes & Codebreakers
#--------------------------------------------------

import math

ABC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

#--------------------------------------------------
# Round 1, the lock: Caesar's shift

def shift(msg, k):
    """Moves each letter k places along the alphabet."""
    out = ''
    for ch in msg:
        if ch in ABC:
            i = ABC.index(ch)
            out += ABC[(i + k) % 26]
        else:
            out += ch
    return out

# print(shift('ATTACK', 3))       # DWWDFN
# print(shift('DWWDFN', -3))      # ATTACK

#--------------------------------------------------
# You Try! Lock and unlock by hand

# print(shift('CAT', 3))          # FDW
# print(shift('KHOOR', -3))       # HELLO
# print(shift('ZOO', 3))          # CRR

#--------------------------------------------------
# Bug Hunt! The first try forgot to go round the wheel

def shift_buggy(msg, k):
    out = ''
    for ch in msg:
        if ch in ABC:
            i = ABC.index(ch)
            out += ABC[i + k]
        else:
            out += ch
    return out

# print(shift_buggy('HELLO', 3))  # KHOOR
# print(shift_buggy('ZOO', 3))    # IndexError: string index out of range

# print(28 % 26)                  # 2
# print(26 % 26)                  # 0
# print(-1 % 26)                  # 25

#--------------------------------------------------
# Round 1, the break: try every key

secret = 'WKH NHB LV XQGHU WKH PDW'
# for k in range(26):
#     print(k, shift(secret, -k))   # k = 3: THE KEY IS UNDER THE MAT

#--------------------------------------------------
# Round 2, the lock: mix the whole alphabet

KEY = 'QWERTYUIOPASDFGHJKLZXCVBNM'    # the top rows of a keyboard

def substitute(msg, key):
    """key: the 26 letters, mixed. A becomes key[0], B becomes key[1], ..."""
    out = ''
    for ch in msg:
        if ch in ABC:
            out += key[ABC.index(ch)]
        else:
            out += ch
    return out

# print(substitute('ATTACK', KEY))   # QZZQEA

#--------------------------------------------------
# Read & Explain: what does mystery do?

def mystery(secret, key):
    out = ''
    for ch in secret:
        if ch in key:
            out += ABC[key.index(ch)]
        else:
            out += ch
    return out

# print(mystery('QZZQEA', KEY))      # ATTACK: it unlocks a substitution

#--------------------------------------------------
# How many keys? 26 x 25 x ... x 1 = 26!

keys = math.factorial(26)
seconds = keys / 10_000_000                   # 10 million keys each second
years = seconds / (365 * 24 * 60 * 60)
# print(f'{keys:,}')                 # 403,291,461,126,605,635,584,000,000
# print(f'{seconds:.1e}')            # 4.0e+19 seconds
# print(f'{years:.2e}')              # 1.28e+12: about 1.3 trillion years
# print(years / 13.8e9)              # about 93 times the age of the universe
# print(years / 1000)                # 1,000 computers: still 1.3 billion years

#--------------------------------------------------
# Round 2, the break: Al-Kindi counts the letters

def count_letters(text):
    """A dictionary: letter -> how many times it appears."""
    counts = {}
    for ch in text:
        if ch in ABC:
            if ch in counts:
                counts[ch] += 1
            else:
                counts[ch] = 1
    return counts

def by_count(counts):
    """The letters, most common first (Lecture 19: key=)."""
    return sorted(counts, key=lambda ch: counts[ch], reverse=True)

# print(count_letters('SEE THE TREE'))
#     # {'S': 1, 'E': 5, 'T': 2, 'H': 1, 'R': 1}
# print(by_count(count_letters('SEE THE TREE')))
#     # ['E', 'T', 'S', 'H', 'R']

#--------------------------------------------------
# Counting breaks Caesar in one step

def crack_caesar(secret):
    """The most common letter of a long secret stands for E."""
    top = by_count(count_letters(secret))[0]
    k = (ABC.index(top) - ABC.index('E')) % 26
    return shift(secret, -k)

# You Try: the most common letter is J
# print((ABC.index('J') - ABC.index('E')) % 26)    # 5
# print(shift('MJQQT', -5))                       # HELLO

#--------------------------------------------------
# The locked letter from the start of the lecture

LETTER_KEY = 'TCVPZKBMUSEOWYGHADIRFXLJNQ'
letter = 'WZZR WZ TR RMZ MGFIZ GK LUIPGW TR IZXZY'

# print(by_count(count_letters(letter)))
#     # Z (7), R (4), then W, G, I (3 each) ...
# print(mystery(letter, LETTER_KEY))
#     # MEET ME AT THE HOUSE OF WISDOM AT SEVEN

#--------------------------------------------------
# Round 3, the lock fights back: many shifts (Vigenere)

def many_shifts(msg, word):
    """Letter number n is shifted by letter number n of word (A = 0, B = 1, ...)."""
    out = ''
    n = 0
    for ch in msg:
        if ch in ABC:
            k = ABC.index(word[n % len(word)])
            out += shift(ch, k)
            n += 1
        else:
            out += ch
    return out

# print(many_shifts('SEE THE TREE', 'LEMON'))  # DIQ HUP XDSR
#     # the five Es became I, Q, P, S, R

#--------------------------------------------------
# Exit ticket
# (a) most common letter K: k = 6.  shift('ZNK', -6) -> 'THE'
# (b) he never tried keys: he counted letters, one pass over the secret
