"""Perception track, version 1: the oracle. Renders every stimulus with cairosvg and measures it from the pixels.

Measurable figures: a ruler ignores fins, surrounds and rails, so the oracle renders the figure again with every
class="context" element removed and measures the targets' extents from that image (pixels darker than mid-grey).
For the contrast figures it locates each patch in that image and reads its mean grey from the full image. Every
measured length is also compared with the drawn value, as an instrument self-check (error must be within 1.5 px).

Bistable figures: the claim asks which depth reading is the true one. A line drawing carries a depth cue only
through occlusion, shading or unequal strokes, so the oracle checks the drawing has none: every edge is drawn in
one stroke width and colour, none is broken, and every edge's stroke is equally dark at its midpoint (darkest pixel within 2 px, equal within
12 levels).
If so, the drawing contains no fact that decides the claim: UNRESOLVED.
Usage: python3 measure.py <dir>   writes png/*.png and records.json
"""
import io, json, os, re, sys
import cairosvg
import PIL
from PIL import Image

TOL_PX, TOL_GREY = 1.0, 1.0
CONTEXT = re.compile(r'<(line|circle|rect)\s+class="context"[^>]*/>')
LINE = re.compile(r'<line class="target" x1="([\d.]+)" y1="([\d.]+)" x2="([\d.]+)" y2="([\d.]+)" stroke="(#[0-9a-f]+)" stroke-width="([\d.]+)"')


def render(svg_text):
    return Image.open(io.BytesIO(cairosvg.svg2png(bytestring=svg_text.encode()))).convert("L")


def dark_extent(img, box):
    x0, y0, x1, y1 = box
    xs = [x for x in range(x0, x1) for y in range(y0, y1) if img.getpixel((x, y)) < 128]
    return (max(xs) - min(xs) + 1) if xs else 0


def bbox_nonwhite(img, box):
    x0, y0, x1, y1 = box
    pts = [(x, y) for x in range(x0, x1, 1) for y in range(y0, y1, 1) if img.getpixel((x, y)) < 250]
    xs, ys = [p[0] for p in pts], [p[1] for p in pts]
    return min(xs), min(ys), max(xs), max(ys)


def mean_grey(img, b):
    x0, y0, x1, y1 = b; w, h = x1 - x0, y1 - y0
    vals = [img.getpixel((x, y)) for x in range(x0 + w // 4, x1 - w // 4) for y in range(y0 + h // 4, y1 - h // 4)]
    return sum(vals) / len(vals)


def measure(stim, text):
    kind = stim["kind"]
    if stim["class"] == "measurable":
        bare = render(CONTEXT.sub("", text)); full = render(text)
        if kind in ("muller_lyer", "ponzo"):
            a, b = dark_extent(bare, (0, 0, 600, 150)), dark_extent(bare, (0, 150, 600, 300))
            names, unit, tol = ("top", "bottom"), "px", TOL_PX
        elif kind == "ebbinghaus":
            a, b = dark_extent(bare, (0, 0, 300, 300)), dark_extent(bare, (300, 0, 600, 300))
            names, unit, tol = ("left", "right"), "px", TOL_PX
        else:
            a = mean_grey(full, bbox_nonwhite(bare, (0, 0, 300, 300))); b = mean_grey(full, bbox_nonwhite(bare, (300, 0, 600, 300)))
            names, unit, tol = ("left", "right"), "grey level", TOL_GREY
        m = {names[0]: round(a, 2), names[1]: round(b, 2)}
        if unit == "px":
            err = max(abs(m[n] - stim["true"][n]) for n in names)
            assert err <= 1.5, (stim["id"], m, stim["true"])
        else:
            err = max(abs(m[n] - stim["true"][n]) for n in names)
            assert err <= 1.0, (stim["id"], m, stim["true"])
        claimed = {"muller_lyer": ("top", "bottom"), "ponzo": ("top", "bottom"), "ebbinghaus": ("right", "left"), "contrast": ("left", "right")}[kind]
        diff = m[claimed[0]] - m[claimed[1]]
        verdict = "TRUE" if diff > tol else "FALSE" if diff < -tol else "WITHIN_TOLERANCE"  # equal at this resolution: the claimed difference is not shown
        return {"verdict": verdict, "holds": verdict == "TRUE", "measured": m, "unit": unit, "difference": round(diff, 2), "tolerance": tol, "instrument_error": round(err, 2)}
    lines = LINE.findall(text)
    widths, colours = {w for *_, c, w in lines}, {c for *_, c, w in lines}
    full = render(text)
    def stroke_dark(x, y):  # darkest pixel within 2 px of the point: a stroke's darkness, not one antialiased sample
        return min(full.getpixel((min(max(x + dx, 0), 599), min(max(y + dy, 0), 299))) for dx in range(-2, 3) for dy in range(-2, 3))
    mids = [stroke_dark(round((float(x1) + float(x2)) / 2), round((float(y1) + float(y2)) / 2)) for x1, y1, x2, y2, c, w in lines]
    uniform = len(widths) == 1 and len(colours) == 1 and (max(mids) - min(mids)) <= 12
    assert uniform, (stim["id"], widths, colours, min(mids), max(mids))
    return {"verdict": "UNRESOLVED", "holds": False, "edges": len(lines), "stroke_widths": sorted(widths), "stroke_colours": sorted(colours),
            "midpoint_darkness_range": [min(mids), max(mids)]}


def main(d):
    os.makedirs(f"{d}/png", exist_ok=True)
    stimuli = json.load(open(f"{d}/stimuli.json"))["stimuli"]
    records = []
    for s in stimuli:
        text = open(f"{d}/svg/{s['id']}.svg").read()
        cairosvg.svg2png(bytestring=text.encode(), write_to=f"{d}/png/{s['id']}.png")
        records.append({"id": s["id"], "kind": s["kind"], "class": s["class"], "claim": s["claim"], **{k: s[k] for k in ("scale", "delta") if k in s}, **measure(s, text)})
    meta = {"oracle": "cairosvg render, pixels measured with Pillow", "cairosvg": cairosvg.__version__, "pillow": PIL.__version__,
            "tolerance_px": TOL_PX, "tolerance_grey": TOL_GREY}
    json.dump({"meta": meta, "records": records}, open(f"{d}/records.json", "w"), indent=1)
    from collections import Counter
    print(Counter((r["class"], r["verdict"]) for r in records))


if __name__ == "__main__":
    main(sys.argv[1])
