"""Perception track, version 1: generate the stimuli. Deterministic; no randomness.

Every figure is drawn from this file's own geometry: classic constructions (Mueller-Lyer, Ebbinghaus, Ponzo,
simultaneous contrast, Necker cube, Schroeder staircase), not copies of anyone's artwork. Measurable figures are
drawn with a set true difference, so the gap between how a figure looks and what it measures is chosen here, by
the author, not discovered. Elements a ruler would ignore (fins, surrounds, rails) carry class="context".
Usage: python3 generate.py <out_dir>   writes svg/*.svg and stimuli.json
"""
import json, os, sys

W, H = 600, 300
DELTAS = (-0.05, -0.02, 0.0, 0.02, 0.05)
SCALES = (160, 200, 240)
INK = "#111111"


def svg(body):
    return f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}"><rect width="{W}" height="{H}" fill="#ffffff"/>{body}</svg>'


def line(x1, y1, x2, y2, cls="target", w=3):
    return f'<line class="{cls}" x1="{x1:.2f}" y1="{y1:.2f}" x2="{x2:.2f}" y2="{y2:.2f}" stroke="{INK}" stroke-width="{w}" stroke-linecap="butt"/>'


def muller_lyer(L, d):
    top, bot = L * (1 + d), L
    cx, f = W / 2, 24
    b = []
    for y, length, outward in ((95, top, True), (205, bot, False)):
        x1, x2 = cx - length / 2, cx + length / 2
        b.append(line(x1, y, x2, y))
        s = -1 if outward else 1  # outward fins point away from the shaft
        for x, dirx in ((x1, 1), (x2, -1)):
            for dy in (-f, f):
                b.append(line(x, y, x + s * dirx * f, y + dy, "context", 3))
    return svg("".join(b)), {"targets": ["top", "bottom"], "true": {"top": top, "bottom": bot}}


def ebbinghaus(L, d):
    r_left, r_right = L / 8, L / 8 * (1 + d)
    b = []
    for cx, r, ring_r, n, rr in ((160, r_left, L / 8 * 2.6, 6, L / 8 * 1.25), (440, r_right, L / 8 * 1.7, 8, L / 8 * 0.42)):
        import math
        for k in range(n):
            a = 2 * math.pi * k / n
            b.append(f'<circle class="context" cx="{cx + ring_r * math.cos(a):.2f}" cy="{150 + ring_r * math.sin(a):.2f}" r="{rr:.2f}" fill="#8a8a8a"/>')
        b.append(f'<circle class="target" cx="{cx}" cy="150" r="{r:.2f}" fill="{INK}"/>')
    return svg("".join(b)), {"targets": ["left", "right"], "true": {"left": 2 * r_left, "right": 2 * r_right}}


def ponzo(L, d):
    top, bot = L * 0.6 * (1 + d), L * 0.6
    b = [line(300, 10, 150, 295, "context", 3), line(300, 10, 450, 295, "context", 3)]
    b.append(line(300 - top / 2, 90, 300 + top / 2, 90, "target", 5))
    b.append(line(300 - bot / 2, 240, 300 + bot / 2, 240, "target", 5))
    return svg("".join(b)), {"targets": ["top", "bottom"], "true": {"top": top, "bottom": bot}}


def contrast(L, d):
    g_left, g_right = round(128 + d * 160), 128  # d of +-0.05 -> +-8 grey levels
    s = L / 2
    b = ['<rect class="context" x="0" y="0" width="300" height="300" fill="#000000"/>', '<rect class="context" x="300" y="0" width="300" height="300" fill="#ffffff"/>']
    for cx, g in ((150, g_left), (450, g_right)):
        b.append(f'<rect class="target" x="{cx - s / 2:.2f}" y="{150 - s / 2:.2f}" width="{s:.2f}" height="{s:.2f}" fill="rgb({g},{g},{g})"/>')
    return svg("".join(b)), {"targets": ["left", "right"], "true": {"left": g_left, "right": g_right}}


def necker(s, ox, oy):
    x0, y0 = 300 - (s + ox) / 2, 150 - (s + oy) / 2
    A = [(x0, y0 + oy), (x0 + s, y0 + oy), (x0 + s, y0 + oy + s), (x0, y0 + oy + s)]
    B = [(x + ox, y - oy) for x, y in A]
    e = [(A[i], A[(i + 1) % 4]) for i in range(4)] + [(B[i], B[(i + 1) % 4]) for i in range(4)] + [(A[i], B[i]) for i in range(4)]
    return svg("".join(line(a[0], a[1], b[0], b[1], "target", 3) for a, b in e)), {"s": s, "ox": ox, "oy": oy}


def stair_profile(n, step, x0=170.0, y0=240.0):
    """Vertices of a stair profile: up one step, across one step, n times, then down the back and along the base."""
    pts = [(x0, y0)]
    x, y = x0, y0
    for _ in range(n):
        y -= step; pts.append((x, y)); x += step; pts.append((x, y))
    pts.append((x, y0))
    return pts


def schroeder(n, step, ox, oy):
    front = stair_profile(n, step)
    back = [(x + ox, y - oy) for x, y in front]
    b = []
    for prof in (front, back):
        for i in range(len(prof)):
            (x1, y1), (x2, y2) = prof[i], prof[(i + 1) % len(prof)]
            b.append(line(x1, y1, x2, y2, "target", 3))
    for (x1, y1), (x2, y2) in zip(front, back):
        b.append(line(x1, y1, x2, y2, "target", 3))
    return svg("".join(b)), {"n": n, "step": step, "ox": ox, "oy": oy}


CLAIMS = {
    "muller_lyer": "The shaft with outward-pointing fins (top) is longer than the shaft with arrowheads (bottom)",
    "ebbinghaus": "The centre disc among the small discs (right) is larger than the one among the large discs (left)",
    "ponzo": "The upper bar between the converging lines is longer than the lower bar",
    "contrast": "The grey square on the black surround (left) is lighter than the one on the white surround (right)",
    "necker": "The lower-left square is the front face of the cube",
    "schroeder": "The staircase is seen from above",
}


def main(out):
    os.makedirs(f"{out}/svg", exist_ok=True)
    stimuli = []
    k = 0
    for kind, fn in (("muller_lyer", muller_lyer), ("ebbinghaus", ebbinghaus), ("ponzo", ponzo), ("contrast", contrast)):
        for L in SCALES:
            for d in DELTAS:
                k += 1; sid = f"P-{k:03d}"
                text, meta = fn(L, d)
                open(f"{out}/svg/{sid}.svg", "w").write(text)
                stimuli.append({"id": sid, "kind": kind, "class": "measurable", "scale": L, "delta": d, "claim": CLAIMS[kind], **meta})
    for s, ox, oy in ((120, 60, 50), (140, 50, 60), (160, 70, 40), (120, 40, 40), (150, 60, 60), (130, 80, 45)):
        k += 1; sid = f"P-{k:03d}"
        text, meta = necker(s, ox, oy)
        open(f"{out}/svg/{sid}.svg", "w").write(text)
        stimuli.append({"id": sid, "kind": "necker", "class": "bistable", "claim": CLAIMS["necker"], **meta})
    for n, step, ox, oy in ((5, 30, 110, 40), (6, 26, 100, 35), (4, 36, 120, 45), (5, 32, 95, 30), (6, 24, 115, 38), (4, 34, 105, 36)):
        k += 1; sid = f"P-{k:03d}"
        text, meta = schroeder(n, step, ox, oy)
        open(f"{out}/svg/{sid}.svg", "w").write(text)
        stimuli.append({"id": sid, "kind": "schroeder", "class": "bistable", "claim": CLAIMS["schroeder"], **meta})
    json.dump({"stimuli": stimuli}, open(f"{out}/stimuli.json", "w"), indent=1)
    print(len(stimuli), "stimuli")


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