"""Compare HDF5 chunk layouts with local files, using the same array and selectors."""
import io
import math
from pathlib import Path
from tempfile import TemporaryDirectory

import h5py
import numpy as np


class TraceReader(io.FileIO):
    """Record byte ranges requested by HDF5's Python file-object driver."""

    def __init__(self, path):
        super().__init__(path, "r")
        self.ranges = []

    def readinto(self, buffer):
        start = self.tell()
        count = super().readinto(buffer)
        if count:
            self.ranges.append((start, start + count))
        return count


def inspect_read(dataset, reader, selection, reference, chunks, expected_count):
    reader.ranges.clear()
    selected = dataset[selection]
    np.testing.assert_array_equal(selected, reference[selection])
    chunk_reads = 0
    payload_bytes = 0
    for chunk in chunks:
        start, end = chunk.byte_offset, chunk.byte_offset + chunk.size
        length = sum(max(0, min(right, end) - max(left, start)) for left, right in reader.ranges)
        if length:
            assert length == chunk.size, "Expected one full read of this compressed chunk"
            assert chunk.filter_mask == 0, "Compression filter was skipped"
            chunk_reads += 1
            payload_bytes += length
    assert chunk_reads == expected_count, (chunk_reads, expected_count)
    decoded_bytes = chunk_reads * math.prod(dataset.chunks) * dataset.dtype.itemsize
    return chunk_reads, selected.nbytes, decoded_bytes, payload_bytes


def measure(path, reference, shape, expected):
    with h5py.File(path, "w") as file:
        dataset = file.create_dataset("features", data=reference, chunks=shape,
                                      compression="gzip", compression_opts=4)
        file.flush()
        chunks = [dataset.id.get_chunk_info(i) for i in range(dataset.id.get_num_chunks())]
        assert len(chunks) == 64

    consecutive_rows = [("row360", 360, expected[0]), ("row361", 361, 0)]
    cold_column = [("column37", np.s_[:, 37], expected[1])]
    for readings in (consecutive_rows, cold_column):
        with TraceReader(path) as reader:
            with h5py.File(reader, "r", rdcc_nbytes=2 * 1024**2, rdcc_nslots=521) as file:
                dataset = file["features"]
                for label, selection, count in readings:
                    print(shape, label, *inspect_read(dataset, reader, selection, reference, chunks, count))


if __name__ == "__main__":
    print("h5py", h5py.__version__, "HDF5", h5py.version.hdf5_version, "NumPy", np.__version__)
    print("layout selection chunks_read returned_B decoded_B compressed_payload_B")
    source = np.random.default_rng(360).integers(0, 32, size=(1024, 1024), dtype=np.uint32)
    with TemporaryDirectory() as root:
        measure(Path(root) / "rows.h5", source, (16, 1024), (1, 64))
        measure(Path(root) / "tiles.h5", source, (256, 64), (16, 4))
