File size: 27,421 Bytes
f69e256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
"""Arrow Chain Traversal (irregular scattered arrows).

Small arrows are scattered across an open canvas. Each arrow is enclosed
in its own circle, and points at the circle's center — so a ray extended
from the arrow through the centre exits the circle on the opposite side.
A handful of larger, labeled terminus circles sit among the arrows.

The traversal rule is pure first-hit ray casting:

  - Start at the green arrow S.
  - Draw a ray from the current arrow's centre along its pointing
    direction. The next step is the FIRST other circle the ray enters.
  - Continue until the ray enters a labeled terminus circle; report its
    label.

The design deliberately avoids a grid. The "next element" is a global,
ray-dependent matching problem over every circle on the canvas, so the
transition table can only be reconstructed by doing the same geometric
work as the task itself — for every arrow. Decoys are placed everywhere
except in corridors that would interfere with the intended chain.
"""
from __future__ import annotations

import argparse
import json
import math
import os
import random
import string
from pathlib import Path
from typing import Dict, List, Tuple

import matplotlib
matplotlib.use("Agg")
import matplotlib.image as mpimg
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage import rotate as _ndimage_rotate
from tqdm import tqdm

# Stamp pools: each is a list of (template-image, default-rotation-offset-deg)
# where default-rotation tells the renderer how to interpret the template's
# natural orientation. The original foot stamp uses an offset of +50° because
# the photo's toes are tilted ~50° CCW from straight-up. The fish and key
# grids were generated with stamps facing straight up, so offset = 0°.
_FOOT_TEMPLATE: np.ndarray | None = None
_FOOT_TEMPLATE_PATH = (
    Path(__file__).resolve().parents[2]
    / "visual_attribute_transfer/constellation_match_count/image.png"
)
_STAMP_POOLS: dict[str, tuple[list[np.ndarray], list[float]]] = {}

# Pool name read from $ARROW_CHAIN_STAMP (default "foot"). Options: foot, fish, key.
_STAMP_POOL_NAME = os.environ.get("ARROW_CHAIN_STAMP", "foot")


def _foot_template() -> np.ndarray:
    global _FOOT_TEMPLATE
    if _FOOT_TEMPLATE is None:
        _FOOT_TEMPLATE = mpimg.imread(str(_FOOT_TEMPLATE_PATH))
    return _FOOT_TEMPLATE


_BG_RGB = (0xf3 / 255.0, 0xef / 255.0, 0xe8 / 255.0)  # matches scene BG


def _chroma_key_to_alpha(rgb: np.ndarray, tol: float = 0.16) -> np.ndarray:
    """Convert HxWx3 to HxWx4 with the stamp's dominant CORNER colour
    keyed to alpha=0. Auto-detects whether the background is light (fish
    paper) or dark (key leather). Critical so the stamp doesn't carry a
    visible halo into the scene that gpt-image-2 would render as a
    container."""
    if rgb.ndim != 3 or rgb.shape[2] not in (3, 4):
        return rgb
    if rgb.shape[2] == 4:
        return rgb
    h, w = rgb.shape[:2]
    # Sample 4 corners to estimate background colour.
    corners = np.stack([rgb[0, 0], rgb[0, w-1], rgb[h-1, 0], rgb[h-1, w-1]])
    bg = corners.mean(axis=0)
    # Per-pixel distance to background colour (Euclidean in RGB).
    dist = np.linalg.norm(rgb - bg, axis=2)
    # Smooth alpha: fully transparent at dist <= tol*0.5, fully opaque at dist >= tol*1.5.
    lo = tol * 0.5
    hi = tol * 1.5
    alpha = np.clip((dist - lo) / max(hi - lo, 1e-6), 0.0, 1.0).astype(rgb.dtype)
    rgba = np.concatenate([rgb, alpha[..., None]], axis=2)
    return rgba


def _pad_to_square(arr: np.ndarray, fill: tuple[float, float, float] | None = None) -> np.ndarray:
    """Pad an HxWxC array to a square so scipy.ndimage.rotate operates
    isotropically. With RGBA arrays, padding is fully transparent."""
    h, w = arr.shape[:2]
    n = max(h, w)
    if h == w == n:
        return arr
    if arr.ndim == 3:
        c = arr.shape[2]
        pad = np.zeros((n, n, c), dtype=arr.dtype)
        if c == 4:
            pad[..., 3] = 0.0  # transparent
        elif fill is None:
            for k in range(3):
                pad[..., k] = _BG_RGB[k]
        else:
            for k in range(3):
                pad[..., k] = fill[k]
    else:
        pad = np.full((n, n), fill[0] if fill else 1.0, dtype=arr.dtype)
    y0 = (n - h) // 2
    x0 = (n - w) // 2
    pad[y0:y0+h, x0:x0+w] = arr
    return pad


def _stamp_pool(name: str) -> tuple[list[np.ndarray], list[float]]:
    """Return (list-of-templates, list-of-rotation-offsets-deg) for the pool."""
    if name in _STAMP_POOLS:
        return _STAMP_POOLS[name]
    base = Path(__file__).resolve().parent
    if name == "foot":
        templates = [_pad_to_square(_foot_template())]
        offsets = [50.0]  # foot photo tilted ~50° CCW vs straight-up
    elif name in ("fish", "key", "airplane", "bird", "leaf"):
        d = base / f"{name}_stamps"
        files = sorted(d.glob("*.png"))
        if not files:
            raise FileNotFoundError(f"no stamps in {d}")
        templates = [
            _pad_to_square(_chroma_key_to_alpha(mpimg.imread(str(f))))
            for f in files
        ]
        # Per-stamp offsets stored by the calibration page.
        offsets_path = d / "offsets.json"
        per_stamp = {}
        if offsets_path.exists():
            try:
                per_stamp = json.loads(offsets_path.read_text())
            except Exception:
                per_stamp = {}
        offsets = [float(per_stamp.get(f"{i:02d}", 0.0)) for i in range(len(templates))]
    else:
        raise ValueError(f"unknown stamp pool: {name}")
    _STAMP_POOLS[name] = (templates, offsets)
    return _STAMP_POOLS[name]


ARROW_COLOR = "#2d2d2d"
START_COLOR = "#1f9d55"
TERMINUS_COLORS = [
    "#c23030", "#1a6dba", "#c47a18", "#7a35a0",
    "#2d8e2d", "#b83280", "#0f766e", "#b45309",
]


def _wrap(a: float) -> float:
    return (a + math.pi) % (2 * math.pi) - math.pi


def _ray_circle_entry(
    origin: np.ndarray,
    direction_unit: np.ndarray,
    center: np.ndarray,
    radius: float,
) -> float | None:
    """Return the entry t along the ray into a circle, or None if it misses.

    t is the signed distance along the (unit) ray direction at which the
    ray first crosses the circle boundary. t < 0 or None → the circle is
    not hit forward from the origin.
    """
    to_c = center - origin
    proj = float(to_c[0] * direction_unit[0] + to_c[1] * direction_unit[1])
    to_c_sq = float(to_c[0] ** 2 + to_c[1] ** 2)
    perp_sq = max(0.0, to_c_sq - proj * proj)
    r_sq = radius * radius
    if perp_sq > r_sq:
        return None
    offset = math.sqrt(r_sq - perp_sq)
    t_entry = proj - offset
    if t_entry < 0.0:
        t_exit = proj + offset
        if t_exit < 0.0:
            return None
        return 0.0  # origin is already inside the circle
    return t_entry


def _ray_min_gap_to_circles(
    origin: np.ndarray,
    direction_angle: float,
    t_end: float,
    other_circles: List[Tuple[np.ndarray, float, object]],
) -> float:
    """Minimum gap between the ray segment [0, t_end] and each circle boundary.

    For each circle, computes the closest distance from the segment to the
    circle's center, subtracts the radius. Negative means the segment enters
    the circle. Returns the minimum over all circles (most threatening near-
    miss).
    """
    dv = np.array([math.cos(direction_angle), math.sin(direction_angle)])
    best = float("inf")
    for center, radius, _tag in other_circles:
        to_c = center - origin
        proj = float(to_c[0] * dv[0] + to_c[1] * dv[1])
        if proj < 0.0:
            t_clamp = 0.0
        elif proj > t_end:
            t_clamp = t_end
        else:
            t_clamp = proj
        closest = origin + t_clamp * dv
        d = float(math.hypot(center[0] - closest[0], center[1] - closest[1]))
        gap = d - radius
        if gap < best:
            best = gap
    return best


def _first_circle_hit(
    origin: np.ndarray,
    direction_angle: float,
    circles: List[Tuple[np.ndarray, float, object]],
    exclude_tag: object | None = None,
) -> Tuple[float, object] | None:
    """Return (t_entry, tag) of the first circle entered along the ray."""
    dv = np.array([math.cos(direction_angle), math.sin(direction_angle)])
    best = None
    for center, radius, tag in circles:
        if tag == exclude_tag:
            continue
        t = _ray_circle_entry(origin, dv, center, radius)
        if t is None:
            continue
        if best is None or t < best[0]:
            best = (t, tag)
    return best


def sample_instance(
    rng: random.Random,
    width: int,
    height: int,
    min_hops: int = 10,
    max_hops: int = 13,
    num_termini: int = 10,
    num_decoys_target: int = 28,
    arrow_radius: float = 22.0,
    terminus_radius: float = 30.0,
    step_length: float = 300.0,
    step_jitter: float = 200.0,
    max_attempts: int = 600,
) -> Dict | None:
    """Build a chain + decoys + termini; return a record dict or None."""
    edge_margin = 110
    min_center_gap = 2 * arrow_radius + 14  # min distance between arrow centres
    term_gap = arrow_radius + terminus_radius + 12
    term_term_gap = 2 * terminus_radius + 60
    # Required clearance (px) between any ray segment [origin → correct next
    # circle's boundary] and every OTHER circle on the canvas. This prevents
    # wrong circles from sitting ambiguously close to a ray that isn't meant
    # to hit them.
    clearance_px = 25.0

    for _ in range(max_attempts):
        # ── 1. Place termini around the canvas (spaced apart) ──
        termini_pts: List[np.ndarray] = []
        t_attempts = 0
        while len(termini_pts) < num_termini and t_attempts < 600:
            t_attempts += 1
            x = rng.uniform(edge_margin, width - edge_margin)
            y = rng.uniform(edge_margin, height - edge_margin)
            p = np.array([x, y])
            if all(float(np.linalg.norm(p - q)) > term_term_gap for q in termini_pts):
                termini_pts.append(p)
        if len(termini_pts) < num_termini:
            continue

        num_hops = rng.randint(min_hops, max_hops)

        # ── 2. Build chain of arrow (pos, direction) entries ──
        start_pos = np.array([
            rng.uniform(edge_margin + 40, width - edge_margin - 40),
            rng.uniform(edge_margin + 40, height - edge_margin - 40),
        ])
        start_dir = rng.uniform(0, 2 * math.pi)
        chain: List[Tuple[np.ndarray, float]] = [(start_pos, start_dir)]

        ok = True
        move_heading = start_dir
        for _hop in range(num_hops - 1):
            cur_pos, _ = chain[-1]

            cx_margin = min(cur_pos[0] - edge_margin, width - edge_margin - cur_pos[0])
            cy_margin = min(cur_pos[1] - edge_margin, height - edge_margin - cur_pos[1])
            bias_strength = 0.0
            bias_dir = 0.0
            if cx_margin < 220 or cy_margin < 220:
                to_center = np.array([width / 2 - cur_pos[0], height / 2 - cur_pos[1]])
                bias_dir = math.atan2(to_center[1], to_center[0])
                bias_strength = max(0.0, 1.0 - min(cx_margin, cy_margin) / 220.0)

            placed = False
            for _retry in range(30):
                turn = rng.uniform(-math.pi / 4, math.pi / 4)
                candidate_dir = move_heading + turn
                if bias_strength > 0:
                    cx = math.cos(candidate_dir) * (1 - 0.5 * bias_strength) + \
                         math.cos(bias_dir) * (0.5 * bias_strength)
                    cy = math.sin(candidate_dir) * (1 - 0.5 * bias_strength) + \
                         math.sin(bias_dir) * (0.5 * bias_strength)
                    candidate_dir = math.atan2(cy, cx)
                dvec = np.array([math.cos(candidate_dir), math.sin(candidate_dir)])
                pvec = np.array([-math.sin(candidate_dir), math.cos(candidate_dir)])
                step_len = step_length + rng.uniform(-step_jitter, step_jitter)
                perp = rng.uniform(-step_jitter, step_jitter)
                next_pos = cur_pos + step_len * dvec + perp * pvec
                if not (edge_margin < next_pos[0] < width - edge_margin and
                        edge_margin < next_pos[1] < height - edge_margin):
                    continue
                if any(float(np.linalg.norm(next_pos - t)) < term_gap for t in termini_pts):
                    continue
                if any(float(np.linalg.norm(next_pos - p)) < min_center_gap for p, _ in chain):
                    continue

                actual_dir = math.atan2(
                    next_pos[1] - cur_pos[1], next_pos[0] - cur_pos[0],
                )
                chain[-1] = (cur_pos, actual_dir)
                chain.append((next_pos, actual_dir))
                move_heading = actual_dir
                placed = True
                break
            if not placed:
                ok = False
                break

        if not ok or len(chain) < num_hops:
            continue

        # ── 3. Pick a terminus the last arrow can point at without blockage ──
        last_pos = chain[-1][0]
        other_arrow_circles = [
            (chain[j][0], arrow_radius, ("A", j)) for j in range(num_hops - 1)
        ]
        terminus_circles = [
            (termini_pts[k], terminus_radius, ("T", k)) for k in range(num_termini)
        ]
        feasible = []
        for k in range(num_termini):
            to_t = termini_pts[k] - last_pos
            dist = float(math.hypot(to_t[0], to_t[1]))
            if dist < arrow_radius + terminus_radius + 10:
                continue
            last_dir_k = math.atan2(to_t[1], to_t[0])
            hit = _first_circle_hit(
                last_pos, last_dir_k,
                other_arrow_circles + terminus_circles,
                exclude_tag=("A", num_hops - 1),
            )
            if hit is not None and hit[1] == ("T", k):
                feasible.append(k)
        if not feasible:
            continue
        chosen_term_idx = rng.choice(feasible)
        last_dir = math.atan2(
            termini_pts[chosen_term_idx][1] - last_pos[1],
            termini_pts[chosen_term_idx][0] - last_pos[0],
        )
        chain[-1] = (last_pos, last_dir)

        # ── 4. Verify chain integrity under the first-hit ray rule ──
        arrow_positions = [c[0] for c in chain]
        all_arrow_circles = [
            (arrow_positions[j], arrow_radius, ("A", j)) for j in range(num_hops)
        ]
        chain_valid = True
        for i in range(num_hops):
            hit = _first_circle_hit(
                arrow_positions[i], chain[i][1],
                all_arrow_circles + terminus_circles,
                exclude_tag=("A", i),
            )
            if hit is None:
                chain_valid = False
                break
            expected = ("T", chosen_term_idx) if i == num_hops - 1 else ("A", i + 1)
            if hit[1] != expected:
                chain_valid = False
                break

            # Clearance check: every OTHER circle must stay ≥ clearance_px
            # away from the ray segment [0, t_correct].
            t_correct = hit[0]
            other_circles = [
                c for c in (all_arrow_circles + terminus_circles)
                if c[2] not in (("A", i), expected)
            ]
            if other_circles:
                gap = _ray_min_gap_to_circles(
                    arrow_positions[i], chain[i][1], t_correct, other_circles,
                )
                if gap < clearance_px:
                    chain_valid = False
                    break
        if not chain_valid:
            continue

        # ── 5. Add decoys that do not break any chain transition ──
        decoys: List[Tuple[np.ndarray, float]] = []
        add_attempts = 0
        while len(decoys) < num_decoys_target and add_attempts < num_decoys_target * 30:
            add_attempts += 1
            dpos = np.array([
                rng.uniform(edge_margin, width - edge_margin),
                rng.uniform(edge_margin, height - edge_margin),
            ])
            if any(float(np.linalg.norm(dpos - p)) < min_center_gap for p in arrow_positions):
                continue
            if any(float(np.linalg.norm(dpos - t)) < term_gap for t in termini_pts):
                continue
            if any(float(np.linalg.norm(dpos - p)) < min_center_gap for p, _ in decoys):
                continue

            # A decoy circle is safe iff, for every chain ray, the ray
            # segment up to the correct next circle's entry stays at least
            # `clearance_px` away from the decoy boundary.
            broken = False
            for i in range(num_hops):
                origin = arrow_positions[i]
                dir_angle = chain[i][1]
                dv_unit = np.array([math.cos(dir_angle), math.sin(dir_angle)])
                if i < num_hops - 1:
                    correct_c = arrow_positions[i + 1]
                    correct_r = arrow_radius
                else:
                    correct_c = termini_pts[chosen_term_idx]
                    correct_r = terminus_radius
                t_correct = _ray_circle_entry(origin, dv_unit, correct_c, correct_r)
                if t_correct is None:
                    broken = True
                    break
                gap = _ray_min_gap_to_circles(
                    origin, dir_angle, t_correct,
                    [(dpos, arrow_radius, ("D", len(decoys)))],
                )
                if gap < clearance_px:
                    broken = True
                    break
            if broken:
                continue

            ddir = rng.uniform(0, 2 * math.pi)
            decoys.append((dpos, ddir))

        if len(decoys) < max(18, num_decoys_target - 8):
            continue

        # ── 6. Assemble record ──
        terminus_labels = list(string.ascii_uppercase[:num_termini])
        rng.shuffle(terminus_labels)
        answer = terminus_labels[chosen_term_idx]

        question = (
            f"The image shows many small footprints scattered across the canvas, "
            f"each footprint enclosed in its own circle, plus {num_termini} "
            f"larger labeled terminus circles "
            f"({', '.join(sorted(terminus_labels))}). The footprint inside the "
            f"GREEN circle is the starting point. From that footprint, follow "
            f"the direction its toes point: cast an infinitely thin ray (a "
            f"mathematical half-line with zero width) from the footprint's "
            f"circle centre along the toe-to-heel pointing direction, and the "
            f"next step is the FIRST other circle this zero-width ray enters. A "
            f"circle only counts if the ray actually crosses its boundary — "
            f"grazing nearby without entering does not count. Continue until "
            f"the ray enters a labeled terminus circle and report its label. "
            f"Answer with a single letter. "
            f"Provide your final answer enclosed in <answer>...</answer> tags."
        )

        return {
            "width": width,
            "height": height,
            "num_hops": num_hops,
            "num_decoys": len(decoys),
            "arrow_radius": arrow_radius,
            "terminus_radius": terminus_radius,
            "chain": [{"x": float(p[0]), "y": float(p[1]), "dir": float(d)}
                      for p, d in chain],
            "decoys": [{"x": float(p[0]), "y": float(p[1]), "dir": float(d)}
                       for p, d in decoys],
            "termini": [{"x": float(t[0]), "y": float(t[1]),
                         "label": terminus_labels[i]}
                        for i, t in enumerate(termini_pts)],
            "chosen_terminus_label": answer,
            "question": question,
            "answer": answer,
        }
    return None


# ── Rendering ──────────────────────────────────────────────────────

def _draw_arrow_in_circle(
    ax,
    cx: float,
    cy: float,
    direction: float,
    arrow_radius: float,
    circle_color: str,
    arrow_color: str,
    zorder: float = 2.0,
    circle_lw: float = 1.2,
    arrow_lw: float = 1.8,
    circle_fill: str = "none",
) -> None:
    """Stamp the foot template at (cx, cy), rotated so the toes point in
    ``direction`` (radians, screen convention: 0=right, π/2=down, -π/2=up).

    The template's natural orientation has toes "up" (data direction -π/2),
    so the rotation needed is direction + π/2 in display coords. scipy's
    ndimage.rotate uses degrees, positive = counter-clockwise in array
    coordinates (y-down). With imshow on inverted-y axes that visually
    matches counter-clockwise on screen, so we negate.
    """
    pool, offsets = _stamp_pool(_STAMP_POOL_NAME)
    # Pick a stamp from the pool. Use a process-stable hash of (cx, cy) so the
    # same cell always gets the same stamp across regenerations (within one
    # difficulty/seed combo).
    pick = int((cx * 91 + cy * 53)) % len(pool)
    template = pool[pick]
    rot_deg = -(math.degrees(direction) + 90.0) + offsets[pick]
    rotated = _ndimage_rotate(
        template, rot_deg, reshape=False, order=1, mode="constant", cval=1.0
    )
    # Match stamp visual radius to arrow_radius (the cell circle radius).
    stamp_radius = arrow_radius
    extent = (cx - stamp_radius, cx + stamp_radius,
              cy + stamp_radius, cy - stamp_radius)
    img_artist = ax.imshow(rotated, extent=extent, zorder=zorder + 0.1,
                            interpolation="bilinear")
    clip = mpatches.Circle((cx, cy), radius=stamp_radius, transform=ax.transData)
    img_artist.set_clip_path(clip)

    # Cell outline: only for the foot pool (fish/key cells get no outline so
    # the stamp is not visually cropped or boxed-in).
    if _STAMP_POOL_NAME == "foot":
        circle = mpatches.Circle(
            (cx, cy), radius=arrow_radius,
            facecolor="none", edgecolor=circle_color,
            linewidth=circle_lw, zorder=zorder + 0.2,
        )
        ax.add_patch(circle)
    elif circle_color != "#6b6b6b":
        # Non-foot pool but a special cell (e.g. green start ring): still
        # draw the outline so the start cell is identifiable.
        circle = mpatches.Circle(
            (cx, cy), radius=arrow_radius,
            facecolor="none", edgecolor=circle_color,
            linewidth=circle_lw, zorder=zorder + 0.2,
        )
        ax.add_patch(circle)


def render_instance(out_path: Path, record: Dict, noise_seed: int) -> None:
    width = int(record["width"])
    height = int(record["height"])
    arrow_radius = float(record["arrow_radius"])
    terminus_radius = float(record["terminus_radius"])

    fig = plt.figure(figsize=(width / 100, height / 100), dpi=100)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)
    ax.axis("off")
    ax.set_facecolor("#f3efe8")

    nrng = np.random.default_rng(noise_seed)
    noise = nrng.normal(0.0, 1.0, size=(height, width))
    noise = (noise - noise.min()) / max(noise.max() - noise.min(), 1e-6)
    ax.imshow(noise, cmap="Greys", alpha=0.06, extent=(0, width, height, 0),
              interpolation="bilinear")

    for d in record["decoys"]:
        _draw_arrow_in_circle(
            ax, d["x"], d["y"], d["dir"], arrow_radius,
            circle_color="#6b6b6b", arrow_color=ARROW_COLOR,
            zorder=2.0, circle_lw=1.1, arrow_lw=1.7,
        )

    for i, c in enumerate(record["chain"]):
        if i == 0:
            # Start cell: foot stamp inside a thicker GREEN circle (no "S" label).
            _draw_arrow_in_circle(
                ax, c["x"], c["y"], c["dir"], arrow_radius,
                circle_color=START_COLOR, arrow_color=START_COLOR,
                zorder=3.6, circle_lw=2.6, arrow_lw=2.4,
            )
        else:
            _draw_arrow_in_circle(
                ax, c["x"], c["y"], c["dir"], arrow_radius,
                circle_color="#6b6b6b", arrow_color=ARROW_COLOR,
                zorder=2.3, circle_lw=1.1, arrow_lw=1.8,
            )

    for i, t in enumerate(record["termini"]):
        color = TERMINUS_COLORS[i % len(TERMINUS_COLORS)]
        circle = mpatches.Circle(
            (t["x"], t["y"]), radius=terminus_radius,
            facecolor=color, edgecolor="white", linewidth=2.0, zorder=5.0,
        )
        ax.add_patch(circle)
        ax.text(t["x"], t["y"], t["label"],
                fontsize=20, fontweight="bold", color="white",
                ha="center", va="center", zorder=5.5)

    fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0)
    plt.close(fig)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--count", type=int, default=20)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--width", type=int, default=512)
    parser.add_argument("--height", type=int, default=512)
    parser.add_argument("--difficulty", type=int, default=5,
                        help="Integer difficulty >=0; scales termini/hops/decoys.")
    args = parser.parse_args()

    def _canvas_scale(n_d, n_0):
        import math
        return math.sqrt(max(1.0, n_d / n_0))
    d = max(0, int(args.difficulty))
    N_d = 15 + 8 * d
    N_0 = 15
    s = _canvas_scale(N_d, N_0)
    args.width  = int(round(args.width  * s))
    args.height = int(round(args.height * s))

    out_root = args.output_root
    img_dir = out_root / "images"
    img_dir.mkdir(parents=True, exist_ok=True)

    rng = random.Random(args.seed)
    records = []

    _num_termini = min(12, 5 + d)
    _min_hops = 5 + 2 * d
    _max_hops = 5 + 2 * d + 2
    _num_decoys_target = 10 + 6 * d

    pbar = tqdm(range(args.count), desc="Generating", unit="img")
    for idx in pbar:
        record = sample_instance(
            rng, args.width, args.height,
            min_hops=_min_hops, max_hops=_max_hops,
            num_termini=_num_termini,
            num_decoys_target=_num_decoys_target,
            step_length=200.0,
            step_jitter=100.0,  # ray step range = [100, 300]
            arrow_radius=26.0,
            terminus_radius=26.0,
        )
        if record is None:
            pbar.set_postfix(status="FAILED")
            continue

        name = f"arrow_chain_{idx:05d}.png"
        ns = rng.randint(0, 10 ** 9)
        render_instance(img_dir / name, record, noise_seed=ns)

        record["image"] = f"images/{name}"
        records.append(record)
        pbar.set_postfix(ok=len(records), hops=record["num_hops"],
                         decoys=record["num_decoys"], ans=record["answer"])

    with (out_root / "annotations.jsonl").open("w") as fh:
        for r in records:
            fh.write(json.dumps(r) + "\n")

    data_json = {
        "task": "arrow_chain",
        "category": "sequential_traversal",
        "count": len(records),
        "items": [
            {"image": r["image"], "question": r["question"], "answer": r["answer"]}
            for r in records
        ],
    }
    (out_root / "data.json").write_text(json.dumps(data_json, indent=2))
    print(f"Saved {len(records)} items to {out_root}")


if __name__ == "__main__":
    main()