#!/usr/bin/env nix-shell
#!nix-shell -i python -p python3

# NOTE: the colors are used to keep track of which letters have been
#       already substituted, and which are still unknown.

def green(s):
    return f"\033[42m{s}\033[0m"

def red(s):
    return f"\033[41m{s}\033[0m"

def substitute(cipher_text, substitution_map):
    for letter in cipher_text:
        if letter in substitution_map:
            print(green(substitution_map[letter]), end="")
        else:
            print(red(letter), end="")

with open('ciphertext', 'r') as file:
    enc = file.read()

# Here, I will be slowly substituting the letters in the ciphertext
# based on what I believe the words to be. I have commented out the
# invocations of substitute, and commented the newly found letters
# after each invocation.

# Starting off, "csds bh reod kzim" looks like "here is your flag"

substitution_map = {
    '-': '-',
    '_': '_',
    '\n': '\n',
    ' ': ' ',
    ',': ',',
    '.': '.',
    ';': ';',
    'c': 'h',
    's': 'e',
    'd': 'r',
    'b': 'i',
    'h': 's',
    'r': 'y',
    'e': 'o',
    'o': 'u',
    'k': 'f',
    'z': 'l',
    'i': 'a',
    'm': 'g',
}

# substitute(enc, substitution_map)

# found:   euro't'e, ligh'a', o'f'er, 'q'ri'a'ish
# suspect: euro p e, ligh t,  o v er,  b ri t ish

substitution_map['t'] = 'p'
substitution_map['a'] = 't'
substitution_map['f'] = 'v'
substitution_map['q'] = 'b'

# substitute(enc, substitution_map)

# found:   visite'n', british 'y'useu'y', sear'p'h, havi'x'g
# suspect: visite d , british  m useu m , sear c h, havi'n'g

substitution_map['n'] = 'd'
substitution_map['y'] = 'm'
substitution_map['p'] = 'c'
substitution_map['x'] = 'n'

# substitute(enc, substitution_map)

# found:   fre'g'uency, 'l'no'w'n, 'j'ust, e'v'act
# suspect: fre q uency,  k no w n,  j ust, e'x'act

substitution_map['g'] = 'q'
substitution_map['l'] = 'k'
substitution_map['w'] = 'w'
substitution_map['j'] = 'j'
substitution_map['v'] = 'x'

substitute(enc, substitution_map)

# still not sure about 'u'? But flag is found