import re
from collections import Counter

"""
--- Day 4: Security Through Obscurity ---

Finally, you come across an information kiosk with a list of rooms. Of course, the list is encrypted and full of decoy
data, but the instructions to decode the list are barely hidden nearby. Better remove the decoy data first.

Each room consists of an encrypted name (lowercase letters separated by dashes) followed by a dash, a sector ID, and a
checksum in square brackets.

* A room is real (not a decoy) if the checksum is the five most common letters in the encrypted name, in order, with ties
  broken by alphabetization. For example:
* aaaaa-bbb-z-y-x-123[abxyz] is a real room because the most common letters are a (5), b (3), and then a tie between x, y,
  and z, which are listed alphabetically.
* a-b-c-d-e-f-g-h-987[abcde] is a real room because although the letters are all tied (1 of each), the first five are
  listed alphabetically.
* not-a-real-room-404[oarel] is a real room.
* totally-real-room-200[decoy] is not.

Of the real rooms from the list above, the sum of their sector IDs is 1514.

What is the sum of the sector IDs of the real rooms?

Your puzzle answer was 173787.

--- Part Two ---

With all the decoy data out of the way, it's time to decrypt this list and get moving.

The room names are encrypted by a state-of-the-art shift cipher, which is nearly unbreakable without the right software.
However, the information kiosk designers at Easter Bunny HQ were not expecting to deal with a master cryptographer like
yourself.

To decrypt a room name, rotate each letter forward through the alphabet a number of times equal to the room's sector ID.
A becomes B, B becomes C, Z becomes A, and so on. Dashes become spaces.

For example, the real name for qzmt-zixmtkozy-ivhz-343 is very encrypted name.

What is the sector ID of the room where North Pole objects are stored?

Your puzzle answer was 548.
"""


class Room:
    def __init__(self, name, sector, checksum):
        self.name = name
        self.sector = sector
        self.checksum = checksum

    @property
    def is_real(self):
        most_frequent = sorted(
            Counter(self.name.replace("-", "")).most_common(),
            key=lambda e: (e[1], -ord(e[0])),
            reverse=True)

        for index in range(len(self.checksum)):
            checksum_letter = self.checksum[index]
            most_frequent_letter = most_frequent[index][0]

            if checksum_letter != most_frequent_letter:
                return False

        return True

    @property
    def decrypted_name(self):
        result = ""
        for word in re.split(r"-", self.name):
            result += "".join(self._decrypt_letter(letter) for letter in word) + " "
        return result.strip()

    def _decrypt_letter(self, letter):
        letter_num = ord(letter) - ord("a")
        return chr((letter_num + self.sector) % 26 + ord("a"))


def room_parser(room_str):
    return Room(
        re.search(r"([\w+-]+)-\d+.*", room_str).group(1),
        int(re.search(r"(\d+)", room_str).group(1)),
        re.search(r"\[(\w+)\]$", room_str).group(1))


def count_sectors_of_real_rooms(rooms):
    real_rooms = filter(
        lambda r: r.is_real,
        (room_parser(room) for room in rooms))
    return sum(map(lambda r: r.sector, real_rooms))


def find_room_with_north_poles(rooms):
    return list(filter(
        lambda r: r.is_real and "northpole" in r.decrypted_name,
        (room_parser(room) for room in rooms)))[0]


if __name__ == "__main__":
    with open("_04_code.txt") as file:
        all_rooms = file.readlines()
        print(f"p1 = {count_sectors_of_real_rooms(all_rooms)}")
        print(f"p2 = {find_room_with_north_poles(all_rooms).sector}")
