"""imgcore.py - 零第三方依赖的 PNG 解码 / 编码与轻量图像度量。

设计目标：可复算、可审计。
  * 只使用 Python 标准库（zlib / struct / hashlib / math）。
  * PNG 解码支持 8-bit 非交错：灰度(0)/RGB(2)/调色板(3)/灰度+Alpha(4)/RGBA(6)。
  * 度量全部为确定性整数/浮点运算，无随机性、无外部模型。
运行环境：CPython 3.9+（本仓库在 3.14.2 上验收）。
"""

import hashlib
import math
import struct
import zlib

PNG_SIG = b"\x89PNG\r\n\x1a\n"


# --------------------------------------------------------------------------- #
# PNG 解码
# --------------------------------------------------------------------------- #
def _unfilter(raw, width, height, bpp):
    """还原 PNG scanline 过滤（0..4）。bpp = 每像素字节数。"""
    stride = width * bpp
    out = bytearray(height * stride)
    prior = bytearray(stride)
    pos = 0
    for y in range(height):
        ftype = raw[pos]
        pos += 1
        line = bytearray(raw[pos:pos + stride])
        pos += stride
        if ftype == 0:
            pass
        elif ftype == 1:  # Sub
            for i in range(bpp, stride):
                line[i] = (line[i] + line[i - bpp]) & 0xFF
        elif ftype == 2:  # Up
            for i in range(stride):
                line[i] = (line[i] + prior[i]) & 0xFF
        elif ftype == 3:  # Average
            for i in range(stride):
                left = line[i - bpp] if i >= bpp else 0
                line[i] = (line[i] + ((left + prior[i]) >> 1)) & 0xFF
        elif ftype == 4:  # Paeth
            for i in range(stride):
                a = line[i - bpp] if i >= bpp else 0
                b = prior[i]
                c = prior[i - bpp] if i >= bpp else 0
                p = a + b - c
                pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
                if pa <= pb and pa <= pc:
                    pred = a
                elif pb <= pc:
                    pred = b
                else:
                    pred = c
                line[i] = (line[i] + pred) & 0xFF
        else:
            raise ValueError("不支持的 PNG 过滤类型: %d" % ftype)
        out[y * stride:(y + 1) * stride] = line
        prior = line
    return out


def read_png(path):
    """返回 (width, height, rgb_bytes)，rgb_bytes 为 w*h*3 的 bytearray。"""
    with open(path, "rb") as fh:
        data = fh.read()
    if data[:8] != PNG_SIG:
        raise ValueError("不是 PNG 文件: %s" % path)
    pos = 8
    idat = []
    width = height = depth = ctype = None
    plte = None
    interlace = 0
    while pos + 8 <= len(data):
        (length,) = struct.unpack(">I", data[pos:pos + 4])
        ctag = data[pos + 4:pos + 8]
        chunk = data[pos + 8:pos + 8 + length]
        pos += 12 + length
        if ctag == b"IHDR":
            width, height, depth, ctype, _comp, _filt, interlace = struct.unpack(">IIBBBBB", chunk)
        elif ctag == b"PLTE":
            plte = chunk
        elif ctag == b"IDAT":
            idat.append(chunk)
        elif ctag == b"IEND":
            break
    if width is None:
        raise ValueError("PNG 缺少 IHDR: %s" % path)
    if interlace != 0:
        raise ValueError("本工具不支持隔行 PNG: %s" % path)
    if depth not in (8,):
        raise ValueError("本工具仅支持 8-bit PNG（收到 %d-bit）: %s" % (depth, path))

    channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(ctype)
    if channels is None:
        raise ValueError("不支持的 PNG color type: %d" % ctype)
    raw = zlib.decompress(b"".join(idat))
    flat = _unfilter(raw, width, height, channels)

    n = width * height
    rgb = bytearray(n * 3)
    if ctype == 2:
        rgb[:] = flat
    elif ctype == 6:
        for i in range(n):
            rgb[3 * i:3 * i + 3] = flat[4 * i:4 * i + 3]
    elif ctype == 0:
        for i in range(n):
            v = flat[i]
            rgb[3 * i] = rgb[3 * i + 1] = rgb[3 * i + 2] = v
    elif ctype == 4:
        for i in range(n):
            v = flat[2 * i]
            rgb[3 * i] = rgb[3 * i + 1] = rgb[3 * i + 2] = v
    elif ctype == 3:
        if plte is None:
            raise ValueError("调色板 PNG 缺少 PLTE: %s" % path)
        palette = [tuple(plte[i:i + 3]) for i in range(0, len(plte), 3)]
        for i in range(n):
            r, g, b = palette[flat[i]]
            rgb[3 * i] = r
            rgb[3 * i + 1] = g
            rgb[3 * i + 2] = b
    return width, height, rgb


def write_png(path, width, height, rgb):
    """写出 8-bit RGB 非交错 PNG（filter=0，deflate 级别 9）。输出确定可复现。"""
    stride = width * 3
    raw = bytearray()
    for y in range(height):
        raw.append(0)
        raw += rgb[y * stride:(y + 1) * stride]

    def chunk(tag, payload):
        return (struct.pack(">I", len(payload)) + tag + payload
                + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))

    ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
    body = (PNG_SIG + chunk(b"IHDR", ihdr)
            + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
            + chunk(b"IEND", b""))
    with open(path, "wb") as fh:
        fh.write(body)


# --------------------------------------------------------------------------- #
# 基础统计
# --------------------------------------------------------------------------- #
def sha256_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for blk in iter(lambda: fh.read(1 << 20), b""):
            h.update(blk)
    return h.hexdigest()


def pixel_digest(width, height, rgb):
    """解码后像素级摘要：区分"字节相同"与"像素相同但编码不同"。"""
    h = hashlib.sha256()
    h.update(struct.pack(">II", width, height))
    h.update(bytes(rgb))
    return h.hexdigest()


def to_gray(width, height, rgb):
    """BT.601 亮度，0..255 float。"""
    n = width * height
    g = [0.0] * n
    for i in range(n):
        r = rgb[3 * i]
        gg = rgb[3 * i + 1]
        b = rgb[3 * i + 2]
        g[i] = 0.299 * r + 0.587 * gg + 0.114 * b
    return g


def resize_area(gray, width, height, nw, nh):
    """面积平均缩放（box filter）。源/目标尺寸任意，确定性。"""
    out = [0.0] * (nw * nh)
    for ty in range(nh):
        y0 = ty * height / nh
        y1 = (ty + 1) * height / nh
        sy0 = int(math.floor(y0))
        sy1 = max(sy0 + 1, int(math.ceil(y1)))
        sy1 = min(sy1, height)
        for tx in range(nw):
            x0 = tx * width / nw
            x1 = (tx + 1) * width / nw
            sx0 = int(math.floor(x0))
            sx1 = max(sx0 + 1, int(math.ceil(x1)))
            sx1 = min(sx1, width)
            acc = 0.0
            cnt = 0
            for sy in range(sy0, sy1):
                base = sy * width
                for sx in range(sx0, sx1):
                    acc += gray[base + sx]
                    cnt += 1
            out[ty * nw + tx] = acc / cnt if cnt else 0.0
    return out


# --------------------------------------------------------------------------- #
# 感知哈希（全部 64 bit，十六进制输出，便于人工复核）
# --------------------------------------------------------------------------- #
def ahash(gray, width, height):
    """均值哈希：8x8 面积平均后与均值比较。对整体亮度平移不敏感。"""
    small = resize_area(gray, width, height, 8, 8)
    mean = sum(small) / 64.0
    bits = [1 if v >= mean else 0 for v in small]
    return bits


def dhash(gray, width, height):
    """差值哈希：9x8 面积平均后比较左右相邻像素。"""
    small = resize_area(gray, width, height, 9, 8)
    bits = []
    for y in range(8):
        row = y * 9
        for x in range(8):
            bits.append(1 if small[row + x] > small[row + x + 1] else 0)
    return bits


def _dct_matrix(n):
    """正交 DCT-II 矩阵（n x n），只算一次。"""
    mat = [[0.0] * n for _ in range(n)]
    for k in range(n):
        ck = math.sqrt(1.0 / n) if k == 0 else math.sqrt(2.0 / n)
        for i in range(n):
            mat[k][i] = ck * math.cos(math.pi * (2 * i + 1) * k / (2.0 * n))
    return mat


_DCT32 = _dct_matrix(32)


def _dct2(matrix, block, n):
    """分离式二维 DCT：rows 再 cols。block 为 n*n 的 row-major 列表。"""
    tmp = [0.0] * (n * n)
    for y in range(n):
        row = block[y * n:(y + 1) * n]
        base = y * n
        for k in range(n):
            mk = matrix[k]
            acc = 0.0
            for i in range(n):
                acc += mk[i] * row[i]
            tmp[base + k] = acc
    out = [0.0] * (n * n)
    for x in range(n):
        col = [tmp[y * n + x] for y in range(n)]
        for k in range(n):
            mk = matrix[k]
            acc = 0.0
            for i in range(n):
                acc += mk[i] * col[i]
            out[k * n + x] = acc
    return out


def phash(gray, width, height):
    """DCT 感知哈希：32x32 灰度 -> 2D DCT -> 取左上 8x8（去 DC）与中位数比较。"""
    small = resize_area(gray, width, height, 32, 32)
    coeffs = _dct2(_DCT32, small, 32)
    vals = []
    for y in range(8):
        for x in range(8):
            if x == 0 and y == 0:
                continue
            vals.append(coeffs[y * 32 + x])
    ordered = sorted(vals)
    m = len(ordered)
    median = (ordered[m // 2] if m % 2 else 0.5 * (ordered[m // 2 - 1] + ordered[m // 2]))
    bits = []
    for y in range(8):
        for x in range(8):
            if x == 0 and y == 0:
                bits.append(0)  # DC 位固定 0，不参与距离（见 hamming 的 mask 说明）
            else:
                bits.append(1 if coeffs[y * 32 + x] > median else 0)
    return bits


def bmvbhash(gray, width, height, blocks=16):
    """块均值哈希（block mean value hash, 16x16=256bit）。

    把图像等分为 blocks x blocks 块，取每块灰度均值，与全体块均值的平均比较。
    相比 DCT 哈希，它在"大面积平坦色块 + 少量像素改动"的合成图上更稳定
    （见 README 的 pHash 对比实验）。
    """
    if blocks > width or blocks > height:
        raise ValueError("blocks 大于图像尺寸")
    means = []
    for by in range(blocks):
        y0 = by * height // blocks
        y1 = (by + 1) * height // blocks
        for bx in range(blocks):
            x0 = bx * width // blocks
            x1 = (bx + 1) * width // blocks
            acc = 0.0
            cnt = 0
            for y in range(y0, y1):
                base = y * width
                for x in range(x0, x1):
                    acc += gray[base + x]
                    cnt += 1
            means.append(acc / cnt)
    avg = sum(means) / len(means)
    return [1 if v > avg else 0 for v in means]


def bits_to_hex(bits):
    val = 0
    for b in bits:
        val = (val << 1) | (1 if b else 0)
    return "%016x" % val


def hamming(a, b, ignore_index=None):
    """汉明距离；ignore_index 用于跳过 pHash 的 DC 位（固定 0 位）。"""
    d = 0
    for i, (x, y) in enumerate(zip(a, b)):
        if ignore_index is not None and i == ignore_index:
            continue
        if x != y:
            d += 1
    return d


# --------------------------------------------------------------------------- #
# 像素级差异
# --------------------------------------------------------------------------- #
def pixel_diff(width, height, rgb_a, rgb_b, tol=8):
    """返回 dict：mae / rmse / max_abs / pct_over_tol / diff_map(每像素最大通道差)。"""
    n = width * height
    ds = bytearray(n)
    total = 0
    sq = 0
    max_abs = 0
    over = 0
    first_delta = None
    uniform = True
    for i in range(n):
        base = 3 * i
        dr = rgb_b[base] - rgb_a[base]
        dg = rgb_b[base + 1] - rgb_a[base + 1]
        db = rgb_b[base + 2] - rgb_a[base + 2]
        if first_delta is None:
            first_delta = (dr, dg, db)
        elif uniform and (dr, dg, db) != first_delta:
            uniform = False
        d = abs(dr)
        d1 = abs(dg)
        d2 = abs(db)
        m = d if d >= d1 else d1
        if d2 > m:
            m = d2
        ds[i] = m
        total += d + d1 + d2
        sq += d * d + d1 * d1 + d2 * d2
        if m > max_abs:
            max_abs = m
        if m > tol:
            over += 1
    mae = total / (3.0 * n)
    rmse = math.sqrt(sq / (3.0 * n))
    return {
        "mae": mae,
        "rmse": rmse,
        "max_abs": max_abs,
        "pct_over_tol": 100.0 * over / n,
        "tol": tol,
        "diff_map": ds,
        "uniform_delta": list(first_delta) if uniform else None,
    }


def ssim_block(gray_a, gray_b, width, height, block=8):
    """分块 SSIM（均匀 8x8 窗，C1/C2 按 8-bit 动态范围取标准常数）。

    平坦块上若两者均值不同，亮度项会直接给出惩罚，不会误判为"完全一致"。
    """
    c1 = (0.01 * 255.0) ** 2
    c2 = (0.03 * 255.0) ** 2
    total = 0.0
    cnt = 0
    for by in range(0, height - block + 1, block):
        for bx in range(0, width - block + 1, block):
            sa = sb = saa = sbb = sab = 0.0
            m = block * block
            for y in range(by, by + block):
                base = y * width
                for x in range(bx, bx + block):
                    a = gray_a[base + x]
                    b = gray_b[base + x]
                    sa += a
                    sb += b
                    saa += a * a
                    sbb += b * b
                    sab += a * b
            ma = sa / m
            mb = sb / m
            va = saa / m - ma * ma
            vb = sbb / m - mb * mb
            cov = sab / m - ma * mb
            if va < 0:
                va = 0.0
            if vb < 0:
                vb = 0.0
            num = (2 * ma * mb + c1) * (2 * cov + c2)
            den = (ma * ma + mb * mb + c1) * (va + vb + c2)
            total += num / den
            cnt += 1
    return total / cnt if cnt else 0.0


def _mae_at(gray_a, gray_b, w, h, dx, dy, min_overlap=0.5):
    """在 (dx,dy) 平移下，重叠区域内灰度 MAE；重叠不足时返回 None。"""
    x0 = max(0, dx)
    x1 = min(w, w + dx)
    y0 = max(0, dy)
    y1 = min(h, h + dy)
    if (x1 - x0) * (y1 - y0) < min_overlap * w * h:
        return None
    acc = 0.0
    cnt = 0
    for y in range(y0, y1):
        ia = y * w + x0
        ib = (y - dy) * w + (x0 - dx)
        for i in range(x1 - x0):
            acc += abs(gray_a[ia + i] - gray_b[ib + i])
        cnt += x1 - x0
    return acc / cnt


def _search_shift(gray_a, gray_b, w, h, radius, step=1):
    best = None
    for dy in range(-radius, radius + 1, step):
        for dx in range(-radius, radius + 1, step):
            m = _mae_at(gray_a, gray_b, w, h, dx, dy)
            if m is not None and (best is None or m < best[0]):
                best = (m, dx, dy)
    return best


def best_shift_gray(gray_a, gray_b, width, height, radius=16):
    """金字塔粗到细的平移对齐搜索（灰度），返回对齐后 MAE 与位移。

    在 1/4、1/2、全分辨率三级上依次细化；重叠区域归一化，避免"平移越大重叠越小"的偏差。
    用途：说明"整体平移变体"的原始像素差异主要来自位移，而不是内容改变。
    """
    levels = []
    for div in (4, 2, 1):
        if width // div >= 16 and height // div >= 16:
            w2, h2 = width // div, height // div
            levels.append((div, w2, h2,
                           gray_a if div == 1 else resize_area(gray_a, width, height, w2, h2),
                           gray_b if div == 1 else resize_area(gray_b, width, height, w2, h2)))
    levels.sort(key=lambda t: -t[0])  # 从最粗开始
    cx = cy = 0
    step = 1
    for idx, (div, w2, h2, ga, gb) in enumerate(levels):
        if idx == 0:
            r = max(1, int(math.ceil(radius / float(div))))
        else:
            r = 2 if idx < len(levels) - 1 else 1
            cx *= 2
            cy *= 2
        best = _search_shift(ga, gb, w2, h2, r, step)
        if best is None:
            break
        cx += best[1]
        cy += best[2]
    # 全分辨率局部精修（+-2），消除金字塔粗层的舍入偏差
    fine = None
    for dy in range(cy - 2, cy + 3):
        for dx in range(cx - 2, cx + 3):
            m = _mae_at(gray_a, gray_b, width, height, dx, dy)
            if m is not None and (fine is None or m < fine[0] - 1e-12):
                fine = (m, dx, dy)
    if fine is not None:
        mae, cx, cy = fine
    else:
        mae = _mae_at(gray_a, gray_b, width, height, cx, cy)
    return {"mae": mae, "dx": cx, "dy": cy, "radius": radius}


def align_gray(gray, width, height, dx, dy, fill=0.0):
    """按 (dx,dy) 平移灰度图，用于制作对齐后的差异图。"""
    out = [fill] * (width * height)
    for y in range(height):
        sy = y - dy
        if sy < 0 or sy >= height:
            continue
        for x in range(width):
            sx = x - dx
            if sx < 0 or sx >= width:
                continue
            out[y * width + x] = gray[sy * width + sx]
    return out
