"""Read an image's pixel dimensions from its header, with no image library.

A level's `mapwidth`/`mapheight` are the coordinate space every marker on it is
expressed in, so getting them wrong moves every marker relative to the drawing.
Reading them off the uploaded file removes the most likely way to get them
wrong, which is somebody typing what they remember.

Pillow would do this in one line and is not a dependency. Adding it would mean a
new cp314 win_amd64 wheel in the offline installer's hash-pinned wheelhouse -
built on Windows, verified against bundle-lock.json, shipped in a 240 MB
installer - to read two integers out of a header. This is the cheaper trade.

Returns (width, height), or (None, None) when the format is not one of these or
the header is truncated. A caller must treat None as "ask the operator" and
never as a default.
"""

import re
import struct


def png_size(data):
    # An IHDR chunk always follows the 8-byte signature, and its first two
    # fields are width and height as big-endian 32-bit integers.
    if len(data) < 24 or data[:8] != b'\x89PNG\r\n\x1a\n':
        return None, None
    if data[12:16] != b'IHDR':
        return None, None
    width, height = struct.unpack('>II', data[16:24])
    return width, height


def gif_size(data):
    if len(data) < 10 or data[:6] not in (b'GIF87a', b'GIF89a'):
        return None, None
    width, height = struct.unpack('<HH', data[6:10])
    return width, height


def webp_size(data):
    if len(data) < 30 or data[:4] != b'RIFF' or data[8:12] != b'WEBP':
        return None, None
    kind = data[12:16]
    if kind == b'VP8 ':
        width, height = struct.unpack('<HH', data[26:30])
        return width & 0x3FFF, height & 0x3FFF
    if kind == b'VP8L':
        bits = struct.unpack('<I', data[21:25])[0]
        return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
    if kind == b'VP8X':
        width = int.from_bytes(data[24:27], 'little') + 1
        height = int.from_bytes(data[27:30], 'little') + 1
        return width, height
    return None, None


def jpeg_size(data):
    """Walk the marker segments to the start-of-frame, which carries the size.

    JPEG has no fixed header offset - the dimensions live in whichever SOF
    marker the encoder used, after any number of application and comment
    segments of varying length. So this walks rather than indexes.
    """
    if len(data) < 4 or data[:2] != b'\xff\xd8':
        return None, None
    index = 2
    end = len(data)
    while index < end - 9:
        if data[index] != 0xFF:
            index += 1
            continue
        marker = data[index + 1]
        # SOF0 through SOF15, excluding the DHT/JPG/DAC markers interleaved
        # in that range, all carry height then width at the same offset.
        if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
                      0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
            height, width = struct.unpack('>HH', data[index + 5:index + 9])
            return width, height
        if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD9:
            index += 2
            continue
        segment = struct.unpack('>H', data[index + 2:index + 4])[0]
        index += 2 + segment
    return None, None


def svg_size(data):
    """SVG states a size in attributes, or implies one through viewBox.

    Width and height may carry units (mm, in, pt) or be percentages, and a
    percentage says nothing about pixels - so a unit that is not px falls back to
    the viewBox, which is unitless user space and is what a renderer scales to.
    """
    try:
        head = data[:4096].decode('utf-8', errors='replace')
    except Exception:
        return None, None
    if '<svg' not in head:
        return None, None

    def attribute(name):
        found = re.search(r'\b%s\s*=\s*["\']([^"\']+)["\']' % name, head)
        return found.group(1).strip() if found else None

    def pixels(value):
        if not value:
            return None
        match = re.match(r'^([0-9.]+)\s*(px)?$', value)
        return int(round(float(match.group(1)))) if match else None

    width = pixels(attribute('width'))
    height = pixels(attribute('height'))
    if width and height:
        return width, height

    viewbox = attribute('viewBox')
    if viewbox:
        parts = re.split(r'[\s,]+', viewbox.strip())
        if len(parts) == 4:
            try:
                return (int(round(float(parts[2]))),
                        int(round(float(parts[3]))))
            except ValueError:
                return None, None
    return None, None


def image_size(data):
    """Dimensions of PNG, JPEG, GIF, WEBP or SVG data. (None, None) otherwise."""
    for reader in (png_size, jpeg_size, gif_size, webp_size, svg_size):
        width, height = reader(data)
        if width and height:
            return width, height
    return None, None
