import sys, subprocess, json
sys.path.insert(0, __import__('os').path.dirname(__file__))
from wcag import *
def read_rgb(path, w, h):
    d = open(path, 'rb').read(); assert len(d) == w * h * 3, (len(d), w, h); return d
def band_best(d, w, y0, y1, bgref):
    """highest contrast against bgref among all pixels of the row band (the 'best reached' by any text pixel)"""
    best = 1.0; cache = {}
    for y in range(y0, y1):
        base = y * w * 3
        for x in range(w):
            px = d[base + x*3: base + x*3 + 3]
            r = cache.get(px)
            if r is None: r = cache[px] = ratio(tuple(px), bgref)
            if r > best: best = r
    return best
def bg_of(d, w, y0, y1):
    px = d[(y0 + (y1-y0)//2) * w * 3: (y0 + (y1-y0)//2) * w * 3 + 3]; return tuple(px)

def core_mask(src, w, y0, y1, bg, fg):
    """1 for source pixels that are exactly the text colour AND have all 8 neighbours non-background (stroke interior); bands only"""
    nb = bytes(bg); nf = bytes(fg); m = bytearray(w * (y1 - y0))
    isbg = lambda x, y: src[(y * w + x) * 3:(y * w + x) * 3 + 3] == nb
    rows = [[not isbg(x, y) for x in range(w)] for y in range(y0 - 1, y1 + 1)]
    isfg = lambda x, y: src[(y * w + x) * 3:(y * w + x) * 3 + 3] == nf
    for yy in range(1, y1 - y0 + 1):
        r0, r1, r2 = rows[yy - 1], rows[yy], rows[yy + 1]
        for x in range(1, w - 1):
            if isfg(x, y0 + yy - 1) and r1[x] and r0[x-1] and r0[x] and r0[x+1] and r1[x-1] and r1[x+1] and r2[x-1] and r2[x] and r2[x+1]:
                m[(yy - 1) * w + x] = 1
    return m
def mean_rgb(d, w, y0, pick):
    """mean colour of the pixels picked by pick(i_in_band, x, y)"""
    s = [0.0, 0.0, 0.0]; n = 0
    for (x, y) in pick:
        o = (y * w + x) * 3; s[0] += d[o]; s[1] += d[o+1]; s[2] += d[o+2]; n += 1
    return (tuple(v / n for v in s), n) if n else (None, 0)
