"""A region quadtree that approximates an image by rectangular blocks of
uniform colour, splitting first the blocks whose division most reduces the
error, and encodes the approximation compactly."""

import heapq
import itertools
import struct

import numpy as np


class BlockStats:
    """Sums over rectangular blocks of an image, each found from summed-area
    tables in a time independent of the block's size. A block is a tuple
    (y0, x0, y1, x1): the rows y0 <= y < y1 and the columns x0 <= x < x1."""

    def __init__(self, image):
        a = np.atleast_3d(image).astype(np.int64)
        h, w, c = a.shape
        # S[y, x] is the sum of the values in the rows above row y and the
        # columns left of column x, in each channel; S2 is that of their
        # squares.
        self.S = np.zeros((h + 1, w + 1, c), np.int64)
        self.S2 = np.zeros((h + 1, w + 1, c), np.int64)
        self.S[1:, 1:] = a.cumsum(axis=0).cumsum(axis=1)
        self.S2[1:, 1:] = (a * a).cumsum(axis=0).cumsum(axis=1)

    @staticmethod
    def block_sum(table, block):
        y0, x0, y1, x1 = block
        return table[y1, x1] - table[y0, x1] - table[y1, x0] + table[y0, x0]

    def mean(self, block):
        """The mean colour of the block."""
        y0, x0, y1, x1 = block
        return self.block_sum(self.S, block) / ((y1 - y0) * (x1 - x0))

    def error(self, block):
        """The sum of the squared differences between the values in the
        block and its mean colour, over its pixels and channels."""
        y0, x0, y1, x1 = block
        n = (y1 - y0) * (x1 - x0)
        s = self.block_sum(self.S, block)
        return float(np.sum(self.block_sum(self.S2, block) - s * s / n))


def children(block):
    """The quadrants of a block, split at its middle row and column (rounded
    down), in the order nw, ne, sw, se, leaving out any that are empty: four,
    or two for a block one pixel high or wide, or none for a single pixel."""
    y0, x0, y1, x1 = block
    if y1 - y0 == 1 and x1 - x0 == 1:
        return []
    ym, xm = (y0 + y1) // 2, (x0 + x1) // 2
    quadrants = ((y0, x0, ym, xm), (y0, xm, ym, x1),
                 (ym, x0, y1, xm), (ym, xm, y1, x1))
    return [q for q in quadrants if q[0] < q[2] and q[1] < q[3]]


def split_order(image):
    """Split the image into blocks, splitting at each step the block whose
    division most reduces the error, until every block is a single pixel.
    Return the blocks in the order in which they were split, and arrays of
    the number of leaves and of the error before the first split and after
    each split."""
    stats = BlockStats(image)
    root = (0, 0, *image.shape[:2])
    count = itertools.count()   # to break ties without comparing blocks
    heap = []

    def push(block):
        kids = children(block)
        if kids:
            gain = stats.error(block) - sum(map(stats.error, kids))
            heapq.heappush(heap, (-gain, next(count), block, len(kids)))

    push(root)
    splits, n_leaves, errors = [], [1], [stats.error(root)]
    while heap:
        neg_gain, _, block, n_kids = heapq.heappop(heap)
        splits.append(block)
        n_leaves.append(n_leaves[-1] + n_kids - 1)
        errors.append(errors[-1] + neg_gain)
        for kid in children(block):
            push(kid)
    return splits, np.array(n_leaves), np.array(errors)


HEADER = struct.Struct(">HHB")  # the height, width and number of channels


def encode(image, split):
    """Encode the approximation of the image by the leaves of the quadtree
    in which the blocks in the set split have been split: a header, then one
    bit for each block that could be split, 1 if it was, then the mean colour
    of each leaf, one byte for each channel, both in depth-first order."""
    stats = BlockStats(image)
    h, w, c = stats.S.shape[0] - 1, stats.S.shape[1] - 1, stats.S.shape[2]
    bits, colours = [], []
    stack = [(0, 0, h, w)]
    while stack:
        block = stack.pop()
        kids = children(block)
        if kids:
            bits.append(block in split)
        if block in split:
            stack.extend(reversed(kids))
        else:
            colours.append(stats.mean(block))
    colours = np.clip(np.round(colours), 0, 255).astype(np.uint8)
    return (HEADER.pack(h, w, c) + np.packbits(bits).tobytes()
            + colours.tobytes())


def decode(data):
    """Decode bytes made by encode into an image."""
    h, w, c = HEADER.unpack_from(data)
    bits = np.unpackbits(np.frombuffer(data, np.uint8, offset=HEADER.size))
    leaves, n_bits = [], 0
    stack = [(0, 0, h, w)]
    while stack:
        block = stack.pop()
        kids = children(block)
        if kids:
            n_bits += 1
            if bits[n_bits - 1]:
                stack.extend(reversed(kids))
                continue
        leaves.append(block)
    offset = HEADER.size + (n_bits + 7) // 8
    colours = np.frombuffer(data, np.uint8, len(leaves) * c, offset)
    image = np.empty((h, w, c), np.uint8)
    for (y0, x0, y1, x1), colour in zip(leaves, colours.reshape(-1, c)):
        image[y0:y1, x0:x1] = colour
    return image if c > 1 else image[..., 0]
