#!/usr/bin/env python3
import os
from math import ceil

RESOURCES_DIR = os.path.join(
    os.path.dirname(os.path.realpath(__file__)),  # This scripts folder
    "..",
    "..",
    "..",
    "resources",
    "set01",
    "challenge08",
)

input = []
with open(os.path.join(RESOURCES_DIR, "input.txt")) as f:
    for l in f:
        input.append(bytes.fromhex(l.strip()))


class block_wrapper:
    def __init__(self, data, block_size):
        self.data = data
        self.block_size = block_size
        self.count = ceil(len(data) / block_size)

    def __getitem__(self, index):
        x = self.block_size * index
        y = x + self.block_size
        return self.data[x:y]

    def __iter__(self):
        return block_iter(self)


class block_iter:
    def __init__(self, blocks):
        self.current = -1
        self.blocks = blocks

    def __next__(self):
        self.current += 1
        if self.current < self.blocks.count:
            return self.blocks[self.current]
        raise StopIteration


def duplicate_block_count(d, s=16):
    f = {}
    w = block_wrapper(d, s)
    for b in w:
        f[b] = f.get(b, 0) + 1

    o = {}
    for b, c in f.items():
        if c > 1:
            o[b] = c
    return o


for i, l in enumerate(input):
    d = duplicate_block_count(input[i])
    if d:
        print("Line {} - {}".format(i + 1, l.hex()))
        for b, c in d.items():
            print("    {} - {}".format(b.hex(), c))
