"""Re-measure the hologram capture DeepSeek V4 Flash cited as proof (SSE-2026-002).

Three things, printed as JSON:
  1. the agent's algorithm, re-implemented: inflate the PNG data, skip un-filtering, read the red byte of
     every fifth pixel on every fifth row. This reproduces the agent's 72.4 / 39.6.
  2. the PNG row-filter types, which is why (1) is not a brightness: most rows are stored as differences.
  3. standard brightness measures on the properly decoded image (Pillow).

Run:  python measure.py ../evidence/01-orion-hologram-bay.png
Needs Python 3.9+ and Pillow.
"""
import json
import struct
import sys
import zlib
from collections import Counter

from PIL import Image


def agent_algorithm(data: bytes):
    pos, w, h, idat = 8, None, None, []
    while pos < len(data):
        (length,) = struct.unpack(">I", data[pos : pos + 4])
        kind = data[pos + 4 : pos + 8]
        if kind == b"IHDR":
            w, h = struct.unpack(">II", data[pos + 8 : pos + 16])
        if kind == b"IDAT":
            idat.append(data[pos + 8 : pos + 8 + length])
        pos += 12 + length
    raw = zlib.decompress(b"".join(idat))
    bpp = 4 if len(raw) % (w * 4 + 1) == 0 else (3 if len(raw) % (w * 3 + 1) == 0 else 4)
    stride = w * bpp + 1
    values = [raw[y * stride + 1 + x * bpp] for y in range(0, h, 5) for x in range(0, w, 5)]
    filters = Counter(raw[y * stride] for y in range(h))
    names = {0: "None", 1: "Sub", 2: "Up", 3: "Average", 4: "Paeth"}
    return (
        {
            "mean": round(sum(values) / len(values), 1),
            "lit_pct": round(100 * sum(v > 40 for v in values) / len(values), 1),
            "samples": len(values),
        },
        {names[k]: v for k, v in sorted(filters.items())},
        (w, h, bpp),
    )


def decoded_measures(path: str):
    img = Image.open(path).convert("RGB")
    px = list(getattr(img, "get_flattened_data", img.getdata)())  # Pillow 12.1+ name, older fallback
    n = len(px)
    r = sum(p[0] for p in px) / n
    g = sum(p[1] for p in px) / n
    b = sum(p[2] for p in px) / n
    return {
        "luma_rec709": round(0.2126 * r + 0.7152 * g + 0.0722 * b, 1),
        "rgb_mean": round((r + g + b) / 3, 1),
        "luma_rec601": round(0.299 * r + 0.587 * g + 0.114 * b, 1),
        "hsl_lightness": round(sum((max(p) + min(p)) / 2 for p in px) / n, 1),
    }


if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "../evidence/01-orion-hologram-bay.png"
    data = open(path, "rb").read()
    agent, filters, (w, h, bpp) = agent_algorithm(data)
    print(
        json.dumps(
            {
                "file": path.replace("\\", "/").split("/")[-1],
                "size": f"{w}x{h}",
                "bytes_per_pixel": bpp,
                "agent_algorithm": agent,
                "png_row_filters": filters,
                "decoded_image": decoded_measures(path),
            },
            indent=2,
        )
    )
