"""Compare equal-weight image reduction in encoded and linear-light sRGB."""

import argparse
import json
from math import floor, isclose
from struct import pack

from PIL import Image, ImageDraw, ImageFont, PngImagePlugin


def decode_srgb(sample):
    return sample / 12.92 if sample <= 0.04045 else ((sample + 0.055) / 1.055) ** 2.4


def encode_srgb(light):
    return 12.92 * light if light <= 0.0031308 else 1.055 * light ** (1 / 2.4) - 0.055


def quantize(sample):
    return floor(sample * 255 + 0.5)


def measure(size, pixels):
    encoded_image = Image.new("RGB", size)
    encoded_image.putdata(pixels)
    encoded_box = encoded_image.resize((1, 1), Image.Resampling.BOX).getpixel((0, 0))

    linear_channels = []
    for samples in zip(*pixels):
        decoded = [decode_srgb(value / 255) for value in samples]
        channel = Image.new("F", size)
        channel.putdata(decoded)
        mean_light = channel.resize((1, 1), Image.Resampling.BOX).getpixel((0, 0))
        assert isclose(mean_light, sum(decoded) / len(decoded), abs_tol=1e-7)
        linear_channels.append(mean_light)
    return {
        "source_size": size,
        "source_rgb": pixels,
        "encoded_box": encoded_box,
        "linear_box_encoded_as_srgb": [quantize(encode_srgb(c)) for c in linear_channels],
        "linear_box_channels_before_encoding": [round(c, 8) for c in linear_channels],
    }


def alpha_example():
    # One opaque white pixel, one fully transparent black pixel.
    alphas = (1.0, 0.0)
    colors = (1.0, 0.0)  # A single linear-light channel, identical for R, G, B.
    alpha = sum(alphas) / len(alphas)
    straight = sum(colors) / len(colors)
    premultiplied = sum(c * a for c, a in zip(colors, alphas)) / len(alphas)
    unpremultiplied = premultiplied / alpha
    return {
        "alpha_after_averaging": alpha,
        "linear_straight_channel_after_unweighting": unpremultiplied,
        "linear_straight_channel_if_alpha_ignored": straight,
        "over_black_premultiplied_srgb": quantize(encode_srgb(premultiplied)),
        "over_black_if_alpha_ignored_srgb": quantize(encode_srgb(straight * alpha)),
    }


def filter_checks():
    black_first = Image.new("L", (2, 1))
    black_first.putdata([0, 255])
    white_first = black_first.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
    nearest = [
        image.resize((1, 1), Image.Resampling.NEAREST).getpixel((0, 0))
        for image in (black_first, white_first)
    ]
    assert nearest == [255, 0]

    low_codes = Image.new("L", (4, 1))
    low_codes.putdata([0, 0, 0, 1])
    direct = low_codes.resize((1, 1), Image.Resampling.BOX).getpixel((0, 0))
    intermediate = low_codes.resize((2, 1), Image.Resampling.BOX)
    staged = intermediate.resize((1, 1), Image.Resampling.BOX).getpixel((0, 0))
    intermediate_codes = list(intermediate.get_flattened_data())
    assert (direct, intermediate_codes, staged) == (0, [0, 1], 1)
    return {
        "nearest_for_black_white_and_white_black": nearest,
        "direct_box_for_0_0_0_1": direct,
        "intermediate_box_for_0_0_0_1": intermediate_codes,
        "second_box_after_intermediate_rounding": staged,
    }


def draw_figure(path, cases, alpha):
    figure = Image.new("RGB", (1080, 620), "#ffffff")
    draw = ImageDraw.Draw(figure)
    ink = "#17283a"

    def label(x, y, words, size):
        draw.text((x, y), words, font=ImageFont.load_default(size=size), fill=ink, anchor="mm")

    def swatch(x, y, color):
        draw.rectangle((x, y, x + 260, y + 142), fill=tuple(color), outline="#263442", width=2)

    label(540, 37, "One output pixel, two averages", 34)
    for y, row in enumerate(((0, 255), (255, 0))):
        for x, value in enumerate(row):
            left = 49 + x * 130
            top = 92 + y * 72
            draw.rectangle((left, top, left + 129, top + 71), fill=(value,) * 3)
    draw.rectangle((49, 92, 309, 234), outline="#263442", width=2)
    checker = cases["checkerboard"]
    encoded = checker["encoded_box"]
    linear = checker["linear_box_encoded_as_srgb"]
    swatch(410, 92, encoded)
    swatch(772, 92, linear)
    label(179, 263, "Black and white", 23)
    label(540, 263, f"Encoded average: {encoded[0]}", 23)
    label(902, 263, f"Linear-light average: {linear[0]}", 23)

    draw.line((49, 311, 1032, 311), fill="#a4b2bd", width=2)
    label(540, 349, "Opaque white + transparent black", 31)
    for x, key, wording in [
        (229, "over_black_if_alpha_ignored_srgb", "Unweighted color"),
        (591, "over_black_premultiplied_srgb", "Premultiplied color"),
    ]:
        value = alpha[key]
        swatch(x, 394, (value,) * 3)
        label(x + 130, 562, f"{wording}: {value}", 23)
    label(540, 599, "Both composited on black in linear light", 18)

    metadata = PngImagePlugin.PngInfo()
    metadata.add(b"gAMA", pack(">I", 45455))
    metadata.add(b"sRGB", b"\x00")
    figure.save(path, pnginfo=metadata)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--figure", metavar="PNG", help="also save a comparison image")
    args = parser.parse_args()
    gray_cases = {
        "black_white": ((2, 1), [0, 255]),
        "checkerboard": ((2, 2), [0, 255, 255, 0]),
        "one_white_pixel": ((2, 2), [0, 0, 0, 255]),
        "two_grays": ((2, 1), [64, 192]),
        "equal_gray": ((2, 1), [128, 128]),
        "near_black": ((2, 1), [0, 10]),
    }
    cases = {
        name: measure(size, [(level,) * 3 for level in levels])
        for name, (size, levels) in gray_cases.items()
    }
    cases["red_green"] = measure((2, 1), [(255, 0, 0), (0, 255, 0)])
    alpha = alpha_example()
    encoded_twice = quantize(encode_srgb(128 / 255))
    assert encoded_twice == 188
    assert cases["black_white"]["encoded_box"] == (128, 128, 128)
    assert cases["checkerboard"]["linear_box_encoded_as_srgb"] == [188, 188, 188]
    assert cases["one_white_pixel"]["linear_box_encoded_as_srgb"] == [137, 137, 137]
    assert cases["equal_gray"]["linear_box_encoded_as_srgb"] == [128, 128, 128]
    assert cases["near_black"]["linear_box_encoded_as_srgb"] == [5, 5, 5]
    assert alpha["over_black_premultiplied_srgb"] == 188
    assert alpha["over_black_if_alpha_ignored_srgb"] == 137
    if args.figure:
        draw_figure(args.figure, cases, alpha)
    print(json.dumps({
        "cases": cases,
        "128_reencoded_as_if_linear": encoded_twice,
        "decoded_128_linear": round(decode_srgb(128 / 255), 8),
        "decoded_188_linear": round(decode_srgb(188 / 255), 8),
        "ideal_half_light_srgb_before_quantizing": round(encode_srgb(0.5) * 255, 8),
        "alpha_case": alpha,
        "filter_checks": filter_checks(),
    }, indent=2))


if __name__ == "__main__":
    main()
