"""Synthetic pixels only. Native libheif/x265 encoding, never renamed PNGs."""
from functools import lru_cache
import io
import struct
import zlib
import pillow_heif
from PIL import Image


@lru_cache(maxsize=16)
def heif(kind='single'):
    size = (160, 96)
    image = Image.new('RGB', size, 'teal')
    image.paste('red', (0, 0, 80, 48))
    if kind in ('10bit', '12bit'):
        bits = int(kind[:-3])
        container = pillow_heif.from_bytes('RGB;' + str(bits), size,
                                          (512).to_bytes(2, 'little') * (size[0] * size[1] * 3))
    else:
        container = pillow_heif.from_bytes('RGB', size, image.tobytes())
    exif = Image.Exif()
    exif[270] = 'SYNTHETIC PRIVATE CAMERA NOTE'
    exif[34853] = {1: 'N', 2: (1., 2., 3.), 3: 'E', 4: (4., 5., 6.)}
    if kind == 'rotated':
        exif[274] = 6
    if kind == 'multi':
        container.add_frombytes('RGB', size, Image.new('RGB', size, 'blue').tobytes())
    options = {'tile_size': 64} if kind == 'grid' else {}
    out = io.BytesIO()
    container.save(out, quality=80, save_all=True, exif=exif.tobytes(),
                   xmp=b'<x:xmpmeta>SYNTHETIC PRIVATE XMP</x:xmpmeta>', **options)
    raw = out.getvalue()
    if kind == 'heif-brand':
        raw = raw[:8] + b'mif1' + raw[12:]
    return raw


def png_exact_size(size):
    """Valid PNG plus a legal private ancillary chunk to hit an exact boundary."""
    out = io.BytesIO()
    Image.new('RGB', (64, 40), 'purple').save(out, 'PNG')
    raw = out.getvalue()
    padding = b'\0' * (size - len(raw) - 12)
    chunk = b'npAD' + padding
    return raw[:-12] + struct.pack('>I', len(padding)) + chunk + struct.pack('>I', zlib.crc32(chunk)) + raw[-12:]


def heif_exact_size(size):
    """HEVC-coded still plus a legal ISO-BMFF free-space box, not junk bytes."""
    raw = heif()
    padding = size - len(raw)
    assert padding >= 8
    return raw + struct.pack('>I', padding) + b'free' + b'\0' * (padding - 8)
