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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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
"""Traverse Ordering (two-curve variant).

Two smooth tangled curves cross each other multiple times (perimeter-anchored
turtle walks, same generator style as line_intersections). Labeled marks
(A, B, C, ...) are placed on BOTH curves at well-spaced arc-length positions,
avoiding crossings and close-strand regions. Exactly one curve additionally
has a green 'S' marker at one of its endpoints. The task: starting from S,
follow that curve to its other endpoint and list the labels of marks on the
S-curve in the order visited. Marks on the other curve are distractors.
"""
from __future__ import annotations

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

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm


LINE_COLOR = "#2f2f2f"
MARK_COLORS = [
    "#e63946", "#457b9d", "#2a9d8f", "#e9c46a", "#f4a261",
    "#264653", "#6a4c93", "#1982c4", "#8ac926", "#ff595e",
]
S_COLOR = "#1f9d3f"


# ── Perimeter-anchored turtle curve (from line_intersections) ──────

def _perimeter_point(s: float, width: int, height: int, margin: int
                     ) -> Tuple[np.ndarray, np.ndarray]:
    side = int(s) % 4
    t = s - int(s)
    if side == 0:
        x = margin + (width - 2 * margin) * t
        y = margin
        inward = np.array([0.0, 1.0])
    elif side == 1:
        x = width - margin
        y = margin + (height - 2 * margin) * t
        inward = np.array([-1.0, 0.0])
    elif side == 2:
        x = width - margin - (width - 2 * margin) * t
        y = height - margin
        inward = np.array([0.0, -1.0])
    else:
        x = margin
        y = height - margin - (height - 2 * margin) * t
        inward = np.array([1.0, 0.0])
    return np.array([x, y]), inward


def sample_perimeter_anchors(
    rng: random.Random,
    num_anchors: int,
    width: int,
    height: int,
    margin: int,
    min_gap: float | None = None,
    jitter_deg: float = 10.0,
    max_attempts: int = 300,
) -> List[Tuple[np.ndarray, np.ndarray]]:
    if min_gap is None:
        min_gap = (4.0 / num_anchors) * 0.5
    for _ in range(max_attempts):
        positions = sorted(rng.uniform(0.0, 4.0) for _ in range(num_anchors))
        ok = True
        for i in range(num_anchors):
            gap = (positions[(i + 1) % num_anchors] - positions[i]) % 4.0
            if gap < min_gap:
                ok = False
                break
        if ok:
            anchors = []
            for s in positions:
                pt, inward = _perimeter_point(s, width, height, margin)
                ang = math.atan2(inward[1], inward[0])
                ang += math.radians(rng.uniform(-jitter_deg, jitter_deg))
                inward = np.array([math.cos(ang), math.sin(ang)])
                anchors.append((pt, inward))
            return anchors
    return None


def _angle_diff(current: float, target: float) -> float:
    d = target - current
    return (d + math.pi) % (2 * math.pi) - math.pi


def build_anchored_curve(
    rng: random.Random,
    width: int,
    height: int,
    start_pos: np.ndarray,
    start_inward: np.ndarray,
    end_pos: np.ndarray,
    end_inward: np.ndarray,
    leader_length: float = 150.0,
    step_size: float = 3.3,
    max_turn: float = 0.028,
    drift_rate: float = 0.007,
    num_waypoints: int = 2,
    interior_margin: int = 260,
    max_steps: int = 1800,
) -> np.ndarray:
    pts: List[np.ndarray] = [start_pos.copy()]
    x, y = float(start_pos[0]), float(start_pos[1])
    theta = math.atan2(start_inward[1], start_inward[0])

    raw_wps: List[np.ndarray] = []
    for _ in range(num_waypoints):
        wx = rng.uniform(interior_margin, width - interior_margin)
        wy = rng.uniform(interior_margin, height - interior_margin)
        raw_wps.append(np.array([wx, wy]))
    direction = end_pos - start_pos
    dir_norm = direction / (np.linalg.norm(direction) + 1e-9)
    raw_wps.sort(key=lambda p: float(np.dot(p - start_pos, dir_norm)))

    funnel = end_pos + end_inward * 400.0
    lookahead = end_pos + (-end_inward) * 240.0
    waypoints: List[np.ndarray] = raw_wps + [funnel, lookahead]

    exit_theta = math.atan2(-end_inward[1], -end_inward[0])
    entry_steps = max(2, int(leader_length / step_size))

    wp_idx = 0
    drift = 0.0
    perp = np.array([-end_inward[1], end_inward[0]])

    for step_count in range(max_steps):
        sd = ((x - end_pos[0]) * end_inward[0]
              + (y - end_pos[1]) * end_inward[1])
        lat = abs((x - end_pos[0]) * perp[0] + (y - end_pos[1]) * perp[1])

        if sd <= 0.0:
            break

        if step_count < entry_steps:
            turn = 0.0
        elif sd < leader_length and lat < 40.0:
            head_err = _angle_diff(theta, exit_theta)
            turn = max(-max_turn, min(max_turn, head_err))
        else:
            is_final = (wp_idx == len(waypoints) - 1)
            if is_final:
                wx, wy = waypoints[-1]
                pull = 0.18
            else:
                wx, wy = waypoints[wp_idx]
                steer_dist = math.hypot(wx - x, wy - y)
                if steer_dist < 140.0:
                    wp_idx += 1
                    continue
                pull = 0.09

            drift += rng.gauss(0, drift_rate)
            drift = max(-max_turn * 0.7, min(max_turn * 0.7, drift))
            turn = drift + rng.gauss(0, max_turn * 0.12)
            target_ang = math.atan2(wy - y, wx - x)
            steer = _angle_diff(theta, target_ang)
            turn += steer * pull
            turn = max(-max_turn, min(max_turn, turn))

        theta += turn
        x += step_size * math.cos(theta)
        y += step_size * math.sin(theta)
        pts.append(np.array([x, y]))

    return np.array(pts)


# ── Intersection detection ─────────────────────────────────────────

def _segments_cross(p0, p1, q0, q1) -> bool:
    eps = 1e-8
    o1 = (p1[0]-p0[0])*(q0[1]-p0[1]) - (p1[1]-p0[1])*(q0[0]-p0[0])
    o2 = (p1[0]-p0[0])*(q1[1]-p0[1]) - (p1[1]-p0[1])*(q1[0]-p0[0])
    o3 = (q1[0]-q0[0])*(p0[1]-q0[1]) - (q1[1]-q0[1])*(p0[0]-q0[0])
    o4 = (q1[0]-q0[0])*(p1[1]-q0[1]) - (q1[1]-q0[1])*(p1[0]-q0[0])
    return ((o1 > eps and o2 < -eps) or (o1 < -eps and o2 > eps)) and \
           ((o3 > eps and o4 < -eps) or (o3 < -eps and o4 > eps))


def _crossing_angle(p0, p1, q0, q1) -> float:
    d1 = p1 - p0
    d2 = q1 - q0
    cos_a = np.dot(d1, d2) / (np.linalg.norm(d1) * np.linalg.norm(d2) + 1e-12)
    return math.degrees(math.acos(min(1.0, abs(cos_a))))


def _find_crossings(
    poly_a: np.ndarray,
    poly_b: np.ndarray,
    same_curve: bool = False,
    min_seg_gap: int = 10,
):
    na = len(poly_a) - 1
    nb = len(poly_b) - 1

    a_min_x = np.minimum(poly_a[:-1, 0], poly_a[1:, 0])
    a_max_x = np.maximum(poly_a[:-1, 0], poly_a[1:, 0])
    a_min_y = np.minimum(poly_a[:-1, 1], poly_a[1:, 1])
    a_max_y = np.maximum(poly_a[:-1, 1], poly_a[1:, 1])
    b_min_x = np.minimum(poly_b[:-1, 0], poly_b[1:, 0])
    b_max_x = np.maximum(poly_b[:-1, 0], poly_b[1:, 0])
    b_min_y = np.minimum(poly_b[:-1, 1], poly_b[1:, 1])
    b_max_y = np.maximum(poly_b[:-1, 1], poly_b[1:, 1])

    all_min_x = np.concatenate([a_min_x, b_min_x])
    all_max_x = np.concatenate([a_max_x, b_max_x])
    cell_size = max(np.median(all_max_x - all_min_x), 1.0) * 3

    grid_a = defaultdict(list)
    for i in range(na):
        cx0 = int(a_min_x[i] / cell_size); cx1 = int(a_max_x[i] / cell_size)
        cy0 = int(a_min_y[i] / cell_size); cy1 = int(a_max_y[i] / cell_size)
        for gx in range(cx0, cx1 + 1):
            for gy in range(cy0, cy1 + 1):
                grid_a[(gx, gy)].append(i)

    grid_b = defaultdict(list)
    for j in range(nb):
        cx0 = int(b_min_x[j] / cell_size); cx1 = int(b_max_x[j] / cell_size)
        cy0 = int(b_min_y[j] / cell_size); cy1 = int(b_max_y[j] / cell_size)
        for gx in range(cx0, cx1 + 1):
            for gy in range(cy0, cy1 + 1):
                grid_b[(gx, gy)].append(j)

    checked = set()
    worst_angle = 180.0
    details: List[Dict] = []
    for cell_key in grid_a:
        if cell_key not in grid_b:
            continue
        for i in grid_a[cell_key]:
            for j in grid_b[cell_key]:
                if same_curve:
                    ii, jj = min(i, j), max(i, j)
                    if jj - ii < min_seg_gap:
                        continue
                    key = (ii, jj)
                else:
                    key = (i, j)
                if key in checked:
                    continue
                checked.add(key)
                if a_max_x[i] < b_min_x[j] or b_max_x[j] < a_min_x[i] or \
                   a_max_y[i] < b_min_y[j] or b_max_y[j] < a_min_y[i]:
                    continue
                if same_curve:
                    si, sj = key
                    p0, p1 = poly_a[si], poly_a[si + 1]
                    q0, q1 = poly_b[sj], poly_b[sj + 1]
                else:
                    si, sj = i, j
                    p0, p1 = poly_a[si], poly_a[si + 1]
                    q0, q1 = poly_b[sj], poly_b[sj + 1]
                if not _segments_cross(p0, p1, q0, q1):
                    continue
                d1 = p1 - p0
                d2 = q1 - q0
                denom = d1[0] * d2[1] - d1[1] * d2[0]
                if abs(denom) < 1e-12:
                    continue
                ti = ((q0[0] - p0[0]) * d2[1] - (q0[1] - p0[1]) * d2[0]) / denom
                tj = ((q0[0] - p0[0]) * d1[1] - (q0[1] - p0[1]) * d1[0]) / denom
                px = float(p0[0] + ti * d1[0])
                py = float(p0[1] + ti * d1[1])
                angle = _crossing_angle(p0, p1, q0, q1)
                worst_angle = min(worst_angle, angle)
                details.append({
                    "i": int(si), "j": int(sj),
                    "ti": float(ti), "tj": float(tj),
                    "px": px, "py": py, "angle": float(angle),
                })
    return len(details), worst_angle, details


def _details_to_points(details: List[Dict]) -> np.ndarray:
    if not details:
        return np.zeros((0, 2))
    return np.array([[d["px"], d["py"]] for d in details])


def _curves_too_close(
    poly_a: np.ndarray,
    poly_b: np.ndarray,
    same_curve: bool = False,
    min_dist: float = 7.0,
    sample_step: int = 3,
    self_index_gap: int = 50,
    known_crossings: np.ndarray | None = None,
    crossing_exclude_radius: float = 30.0,
) -> bool:
    nb = len(poly_b) - 1
    b_pts = poly_b[:-1]
    b_vecs = poly_b[1:] - poly_b[:-1]
    b_lens_sq = np.maximum((b_vecs ** 2).sum(axis=1), 1e-12)
    has_crossings = known_crossings is not None and len(known_crossings) > 0
    for idx in range(0, len(poly_a), sample_step):
        px, py = poly_a[idx]
        p = np.array([px, py])
        dp = p - b_pts
        t = (dp * b_vecs).sum(axis=1) / b_lens_sq
        t = np.clip(t, 0.0, 1.0)
        proj = b_pts + t[:, None] * b_vecs
        dists = np.sqrt(((p - proj) ** 2).sum(axis=1))
        if same_curve:
            mask = np.abs(np.arange(nb) - idx) < self_index_gap
            dists[mask] = 9999.0
        if dists.min() < min_dist:
            if has_crossings:
                cross_dists = np.sqrt(((p - known_crossings) ** 2).sum(axis=1))
                if cross_dists.min() < crossing_exclude_radius:
                    continue
            return True
    return False


# ── Mark placement ─────────────────────────────────────────────────

def place_marks_on_curve(
    rng: random.Random,
    polyline: np.ndarray,
    other_polyline: np.ndarray,
    num_marks: int,
    avoid_points: List[np.ndarray],
    existing_marks: List[Tuple[np.ndarray, int]] | None = None,
    min_arc_frac: float = 0.10,
    min_pixel_to_crossing: float = 70.0,
    min_pixel_to_other_strand: float = 36.0,
    min_pixel_between_marks: float = 90.0,
    endpoint_arc_margin_frac: float = 0.08,
    max_iter: int = 1200,
    extra_polylines: List[np.ndarray] | None = None,
) -> List[int]:
    """Place `num_marks` indices along `polyline`, avoiding crossing points,
    regions where the OTHER curve passes close, and existing marks on either
    curve. Endpoints are reserved (for the S marker).
    """
    n = len(polyline)
    diffs = np.diff(polyline, axis=0)
    seg_lens = np.sqrt((diffs ** 2).sum(axis=1))
    arc = np.concatenate([[0.0], np.cumsum(seg_lens)])
    total_len = arc[-1]
    min_arc_dist = total_len * min_arc_frac
    margin_arc = total_len * endpoint_arc_margin_frac

    # Precompute other curve's segments for fast distance queries.
    op = other_polyline
    o_pts = op[:-1]
    o_vecs = op[1:] - op[:-1]
    o_lens_sq = np.maximum((o_vecs ** 2).sum(axis=1), 1e-12)

    def dist_to_other(pt: np.ndarray) -> float:
        dp = pt - o_pts
        t = (dp * o_vecs).sum(axis=1) / o_lens_sq
        t = np.clip(t, 0.0, 1.0)
        proj = o_pts + t[:, None] * o_vecs
        return float(np.sqrt(((pt - proj) ** 2).sum(axis=1)).min())

    extra_bundles = []
    for ep in (extra_polylines or []):
        e_pts = ep[:-1]
        e_vecs = ep[1:] - ep[:-1]
        e_lens_sq = np.maximum((e_vecs ** 2).sum(axis=1), 1e-12)
        extra_bundles.append((e_pts, e_vecs, e_lens_sq))

    def dist_to_any_extra(pt: np.ndarray) -> float:
        if not extra_bundles:
            return 1e9
        best = 1e9
        for e_pts, e_vecs, e_lens_sq in extra_bundles:
            dp = pt - e_pts
            t = (dp * e_vecs).sum(axis=1) / e_lens_sq
            t = np.clip(t, 0.0, 1.0)
            proj = e_pts + t[:, None] * e_vecs
            d = float(np.sqrt(((pt - proj) ** 2).sum(axis=1)).min())
            if d < best:
                best = d
        return best

    def too_near_avoid(pt: np.ndarray) -> bool:
        for cp in avoid_points:
            if np.sqrt(((pt - cp) ** 2).sum()) < min_pixel_to_crossing:
                return True
        return False

    existing = existing_marks or []
    mark_indices: List[int] = []
    for _ in range(max_iter):
        if len(mark_indices) == num_marks:
            break
        t = rng.uniform(margin_arc, total_len - margin_arc)
        idx = int(np.searchsorted(arc, t))
        idx = max(1, min(n - 2, idx))
        pt = polyline[idx]
        if too_near_avoid(pt):
            continue
        if dist_to_other(pt) < min_pixel_to_other_strand:
            continue
        if dist_to_any_extra(pt) < min_pixel_to_other_strand:
            continue
        if any(abs(arc[idx] - arc[m]) < min_arc_dist for m in mark_indices):
            continue
        if any(np.sqrt(((pt - polyline[m]) ** 2).sum()) < min_pixel_between_marks
               for m in mark_indices):
            continue
        if any(np.sqrt(((pt - ep) ** 2).sum()) < min_pixel_between_marks
               for ep, _ in existing):
            continue
        mark_indices.append(idx)

    mark_indices.sort()
    return mark_indices


def label_anchor_for_mark(
    polyline: np.ndarray,
    other_polyline: np.ndarray,
    mark_idx: int,
    width: int,
    height: int,
    offset: float = 48.0,
    tangent_span: int = 6,
) -> Tuple[float, float]:
    n = len(polyline)
    lo = max(0, mark_idx - tangent_span)
    hi = min(n - 1, mark_idx + tangent_span)
    tan = polyline[hi] - polyline[lo]
    tnorm = math.hypot(float(tan[0]), float(tan[1]))
    if tnorm < 1e-8:
        ux, uy = 0.0, -1.0
    else:
        ux = float(tan[0]) / tnorm
        uy = float(tan[1]) / tnorm
    perps = [(-uy, ux), (uy, -ux)]
    pt = polyline[mark_idx]
    best = None
    best_score = -1e9
    for px, py in perps:
        cx = float(pt[0]) + px * offset
        cy = float(pt[1]) + py * offset
        score = 0.0
        d_self = float(np.sqrt(((polyline - np.array([cx, cy])) ** 2).sum(axis=1)).min())
        d_other = float(np.sqrt(((other_polyline - np.array([cx, cy])) ** 2).sum(axis=1)).min())
        score += min(d_self, d_other)
        if 30 < cx < width - 30 and 30 < cy < height - 30:
            score += 200.0
        if score > best_score:
            best_score = score
            best = (cx, cy)
    cx, cy = best
    return (
        float(np.clip(cx, 34, width - 34)),
        float(np.clip(cy, 34, height - 34)),
    )


# ── Instance sampling ──────────────────────────────────────────────

def sample_instance(
    rng: random.Random,
    width: int,
    height: int,
    min_marks_total: int = 4,
    max_marks_total: int = 7,
    min_crossings: int = 7,
    max_crossings: int = 25,
    min_pixel_between_marks: float = 90.0,
    s_endpoint_excl_px: float = 90.0,
    perimeter_margin: int = 70,
    interior_margin: int = 260,
    max_attempts: int = 2500,
    num_waypoints: int = 5,
    s_marks_override: int | None = None,
    o_marks_override: int | None = None,
    num_extra_distractor_curves: int = 0,
    extra_distractor_max_attempts: int = 80,
) -> Dict | None:
    labels_pool = list(string.ascii_uppercase)
    # reserve S
    labels_pool = [l for l in labels_pool if l != "S"]

    for _ in range(max_attempts):
        anchors = sample_perimeter_anchors(
            rng, 4, width, height, margin=perimeter_margin,
        )
        if anchors is None:
            continue

        # Pair anchor i with anchor i+2 (opposite-side pairing).
        pairs = [(anchors[0], anchors[2]), (anchors[1], anchors[3])]
        rng.shuffle(pairs)

        polylines = []
        ok = True
        for (sp, sd), (ep, ed) in pairs:
            poly = build_anchored_curve(
                rng, width, height,
                start_pos=sp, start_inward=sd,
                end_pos=ep, end_inward=ed,
                leader_length=150.0,
                step_size=rng.uniform(3.0, 3.8),
                max_turn=rng.uniform(0.034, 0.044),
                drift_rate=rng.uniform(0.010, 0.016),
                num_waypoints=num_waypoints,
                interior_margin=interior_margin,
                max_steps=3200,
            )
            if len(poly) < 50:
                ok = False
                break
            polylines.append(poly)
        if not ok:
            continue

        # Crossings between the two curves (no self-crossings desired, but allow).
        pair_count, pair_min_angle, pair_details = _find_crossings(
            polylines[0], polylines[1]
        )
        self_counts = []
        self_details_list = []
        self_min_angle = 180.0
        for p in polylines:
            sc, sa, sd_ = _find_crossings(p, p, same_curve=True)
            self_counts.append(sc)
            self_details_list.append(sd_)
            self_min_angle = min(self_min_angle, sa)

        total_cross = pair_count + sum(self_counts)
        if pair_count < min_crossings or pair_count > max_crossings:
            continue
        # Keep self-crossings modest so traversal order stays clear.
        if sum(self_counts) > 3:
            continue

        min_angle = min(pair_min_angle, self_min_angle)
        if min_angle < 30.0:
            continue

        # Hygiene: no close strands outside crossing regions.
        all_cross_pts = _details_to_points(pair_details)
        # 1% of canvas short side keeps strands visibly separated at any
        # resolution while staying tractable for the sampler.
        min_dist_px = 0.01 * float(min(width, height))
        if _curves_too_close(polylines[0], polylines[1],
                             min_dist=min_dist_px,
                             known_crossings=all_cross_pts):
            continue
        too_close_self = False
        for i, p in enumerate(polylines):
            if _curves_too_close(p, p, same_curve=True,
                                 min_dist=min_dist_px,
                                 known_crossings=_details_to_points(self_details_list[i])):
                too_close_self = True
                break
        if too_close_self:
            continue

        # Extra unlabeled distractor curves (difficulty-driven).
        extra_polylines: List[np.ndarray] = []
        extra_pair_details_all: List[Dict] = []
        extra_self_details_all: List[Dict] = []
        extra_ok = True
        for _extra_idx in range(num_extra_distractor_curves):
            placed = False
            for _attempt in range(extra_distractor_max_attempts):
                extra_anchors = sample_perimeter_anchors(
                    rng, 2, width, height, margin=perimeter_margin,
                )
                if extra_anchors is None:
                    continue
                (esp, esd), (eep, eed) = extra_anchors[0], extra_anchors[1]
                epoly = build_anchored_curve(
                    rng, width, height,
                    start_pos=esp, start_inward=esd,
                    end_pos=eep, end_inward=eed,
                    leader_length=150.0,
                    step_size=rng.uniform(3.0, 3.8),
                    max_turn=rng.uniform(0.034, 0.044),
                    drift_rate=rng.uniform(0.010, 0.016),
                    num_waypoints=num_waypoints,
                    interior_margin=interior_margin,
                    max_steps=3200,
                )
                if len(epoly) < 50:
                    continue
                # Self-crossing hygiene for the extra curve.
                esc, esa, esd_det = _find_crossings(epoly, epoly, same_curve=True)
                if esc > 3 or esa < 30.0:
                    continue
                if _curves_too_close(epoly, epoly, same_curve=True,
                                     min_dist=min_dist_px,
                                     known_crossings=_details_to_points(esd_det)):
                    continue
                # Cross-curve hygiene vs all existing polylines.
                all_existing = polylines + extra_polylines
                bad = False
                candidate_pair_details: List[Dict] = []
                for existing_poly in all_existing:
                    ec, ea, ed_det = _find_crossings(epoly, existing_poly)
                    if ea < 30.0:
                        bad = True
                        break
                    if _curves_too_close(epoly, existing_poly,
                                         min_dist=min_dist_px,
                                         known_crossings=_details_to_points(ed_det)):
                        bad = True
                        break
                    candidate_pair_details.extend(ed_det)
                if bad:
                    continue
                extra_polylines.append(epoly)
                extra_pair_details_all.extend(candidate_pair_details)
                extra_self_details_all.extend(esd_det)
                placed = True
                break
            if not placed:
                extra_ok = False
                break
        if not extra_ok:
            continue

        # Collect points to avoid for mark placement: all crossings.
        avoid_pts: List[np.ndarray] = [np.array([d["px"], d["py"]])
                                       for d in pair_details]
        for sd_ in self_details_list:
            avoid_pts.extend(np.array([d["px"], d["py"]]) for d in sd_)
        for d_ in extra_pair_details_all:
            avoid_pts.append(np.array([d_["px"], d_["py"]]))
        for d_ in extra_self_details_all:
            avoid_pts.append(np.array([d_["px"], d_["py"]]))

        # Pick S-curve and which endpoint is S.
        s_curve = rng.randint(0, 1)
        s_at_start = rng.random() < 0.5
        other_curve = 1 - s_curve

        # Decide mark counts. Default: 10 total, 5 on S-curve, 5 on the
        # distractor curve. If the caller narrows the range we split roughly
        # evenly, keeping at least 2 on each curve.
        total_marks = rng.randint(min_marks_total, max_marks_total)
        s_marks = total_marks // 2
        s_marks = max(2, min(s_marks, total_marks - 2))
        o_marks = total_marks - s_marks

        s_poly = polylines[s_curve]
        o_poly = polylines[other_curve]

        s_indices = place_marks_on_curve(
            rng, s_poly, o_poly, s_marks, avoid_points=avoid_pts,
            min_pixel_between_marks=min_pixel_between_marks,
            extra_polylines=extra_polylines,
        )
        if len(s_indices) < s_marks:
            continue

        # Existing marks (pixel-space) to avoid from other curve's perspective.
        existing_for_other = [(s_poly[i], i) for i in s_indices]
        o_indices = place_marks_on_curve(
            rng, o_poly, s_poly, o_marks, avoid_points=avoid_pts,
            existing_marks=existing_for_other,
            min_pixel_between_marks=min_pixel_between_marks,
            extra_polylines=extra_polylines,
        )
        if len(o_indices) < o_marks:
            continue

        # Also avoid marks too close to the S endpoint on s_poly.
        s_endpoint_pt = s_poly[0] if s_at_start else s_poly[-1]
        all_mark_pts = [s_poly[i] for i in s_indices] + [o_poly[i] for i in o_indices]
        if any(np.sqrt(((s_endpoint_pt - p) ** 2).sum()) < s_endpoint_excl_px
               for p in all_mark_pts):
            continue

        # Assign labels. Pool of letters sized to total_marks, shuffled.
        pool = labels_pool[:total_marks]
        rng.shuffle(pool)
        s_labels = pool[:s_marks]
        o_labels = pool[s_marks:s_marks + o_marks]

        # Determine traversal order on the S-curve.
        # s_indices is ascending in polyline order. If s_at_start, forward;
        # else reverse.
        order_pairs = list(zip(s_indices, s_labels))
        if not s_at_start:
            order_pairs = order_pairs[::-1]
        answer_sequence = [lab for _, lab in order_pairs]
        answer = ", ".join(answer_sequence)

        # Build mark info.
        marks_info: List[Dict] = []
        for idx, lab in zip(s_indices, s_labels):
            lx, ly = label_anchor_for_mark(s_poly, o_poly, idx, width, height)
            marks_info.append({
                "label": lab,
                "curve": s_curve,
                "on_s_curve": True,
                "polyline_index": int(idx),
                "x": round(float(s_poly[idx, 0]), 2),
                "y": round(float(s_poly[idx, 1]), 2),
                "label_x": round(lx, 2),
                "label_y": round(ly, 2),
            })
        for idx, lab in zip(o_indices, o_labels):
            lx, ly = label_anchor_for_mark(o_poly, s_poly, idx, width, height)
            marks_info.append({
                "label": lab,
                "curve": other_curve,
                "on_s_curve": False,
                "polyline_index": int(idx),
                "x": round(float(o_poly[idx, 0]), 2),
                "y": round(float(o_poly[idx, 1]), 2),
                "label_x": round(lx, 2),
                "label_y": round(ly, 2),
            })

        # S marker info.
        s_pt = s_poly[0] if s_at_start else s_poly[-1]
        # Label offset for S: away from curve tangent.
        s_tan_idx = 10 if s_at_start else len(s_poly) - 11
        s_idx_for_anchor = 0 if s_at_start else len(s_poly) - 1
        slx, sly = label_anchor_for_mark(s_poly, o_poly, s_idx_for_anchor,
                                         width, height, offset=52.0,
                                         tangent_span=10)

        all_labels_display = sorted(s_labels + o_labels)
        question = (
            "The image shows two smooth curves that cross each other. "
            f"Labeled points ({', '.join(all_labels_display)}) are marked on "
            "both curves. A single green 'S' marks the start endpoint of one "
            "of the curves. Starting from S, follow THAT curve (the one S "
            "lies on) all the way to its other endpoint, and list the labels "
            "of the marked points you visit in order, separated by commas "
            "(for example: B, D, A). Ignore any labeled points that lie on "
            "the OTHER curve. Provide your final answer enclosed in "
            "<answer>...</answer> tags."
        )

        all_polylines = polylines + extra_polylines
        return {
            "width": width,
            "height": height,
            "polylines": all_polylines,
            "num_extra_distractor_curves": int(len(extra_polylines)),
            "s_curve": int(s_curve),
            "s_at_start": bool(s_at_start),
            "s_point": {
                "x": round(float(s_pt[0]), 2),
                "y": round(float(s_pt[1]), 2),
                "label_x": round(float(slx), 2),
                "label_y": round(float(sly), 2),
            },
            "marks": marks_info,
            "num_marks_total": total_marks,
            "num_marks_on_s": s_marks,
            "num_pair_crossings": int(pair_count),
            "num_self_crossings": int(sum(self_counts)),
            "question": question,
            "answer": answer,
        }
    return None


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

def render_instance(out_path: Path, record: Dict, noise_seed: int) -> None:
    width = int(record["width"])
    height = int(record["height"])
    polylines = record["polylines"]
    marks = record["marks"]
    s_point = record["s_point"]

    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 i, poly in enumerate(polylines):
        ax.plot(poly[:, 0], poly[:, 1],
                color=LINE_COLOR, linewidth=2.8,
                solid_capstyle="round", solid_joinstyle="round",
                zorder=2.0 + i * 0.05)

    # Subtle dots at all four endpoints.
    for poly in polylines:
        for ep in (poly[0], poly[-1]):
            ax.scatter([ep[0]], [ep[1]], s=30,
                       facecolors="#f3efe8", edgecolors="#999",
                       linewidths=1.0, zorder=3.2)

    # Marks with offset labels.
    for i, mark in enumerate(marks):
        x, y = mark["x"], mark["y"]
        lx = mark.get("label_x", x)
        ly = mark.get("label_y", y - 22)
        color = MARK_COLORS[i % len(MARK_COLORS)]
        ax.plot([x, lx], [y, ly],
                color="#9b7b56", linewidth=1.0, alpha=0.7,
                linestyle=(0, (2.0, 3.2)), zorder=3.8)
        ax.scatter([x], [y], s=120, facecolors=color, edgecolors="white",
                   linewidths=1.5, zorder=4.0)
        ax.text(lx, ly, mark["label"],
                fontsize=18, fontweight="bold", color=color,
                ha="center", va="center", zorder=5,
                bbox=dict(facecolor="#f3efe8", edgecolor=color,
                          boxstyle="round,pad=0.25", alpha=0.95, linewidth=1.2))

    # S marker on the S-curve endpoint — green, larger.
    sx, sy = s_point["x"], s_point["y"]
    slx, sly = s_point["label_x"], s_point["label_y"]
    ax.plot([sx, slx], [sy, sly],
            color=S_COLOR, linewidth=1.2, alpha=0.8,
            linestyle=(0, (2.0, 3.2)), zorder=4.2)
    ax.scatter([sx], [sy], s=180, facecolors=S_COLOR, edgecolors="white",
               linewidths=2.0, zorder=5.0)
    ax.text(slx, sly, "S",
            fontsize=20, fontweight="bold", color=S_COLOR,
            ha="center", va="center", zorder=6,
            bbox=dict(facecolor="#f3efe8", edgecolor=S_COLOR,
                      boxstyle="round,pad=0.3", alpha=0.95, linewidth=1.5))

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


# ── Main ───────────────────────────────────────────────────────────

def _polyline_to_list(p: np.ndarray) -> List[List[float]]:
    return [[round(float(x), 2), round(float(y), 2)] for x, y in p]


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--count", type=int, default=6)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--width", type=int, default=1024)
    parser.add_argument("--height", type=int, default=1024)
    parser.add_argument("--min-marks", type=int, default=10)
    parser.add_argument("--max-marks", type=int, default=10)
    parser.add_argument("--min-crossings", type=int, default=7)
    parser.add_argument("--max-crossings", type=int, default=25)
    parser.add_argument("--difficulty", type=int, default=5,
                        help="Integer difficulty >=0; scales crossings and marks.")
    parser.add_argument("--workers", type=int, default=8)
    args = parser.parse_args()

    d = max(0, int(args.difficulty))
    # Defaults (used whether difficulty override fires or not).
    min_pixel_between_marks = 90.0
    s_endpoint_excl_px = 90.0
    num_waypoints = 5
    num_extra_distractor_curves = 0
    if d > 0:
        args.min_crossings = 4 + d
        args.max_crossings = 6 + 2 * d
        s_marks = 4 + d // 2
        o_marks = 4 + d // 2
        args.min_marks = s_marks + o_marks
        args.max_marks = s_marks + o_marks
        num_waypoints = 5 + d
        min_pixel_between_marks = float(max(55, 90 - 5 * d))
        s_endpoint_excl_px = float(max(50, 90 - 5 * d))
        num_extra_distractor_curves = d // 3

    # Canvas scaling with difficulty (sqrt of mark-density growth).
    N_d = 8 + 4 * d
    N_0 = 8
    s_scale = math.sqrt(max(1.0, N_d / N_0))
    args.width = int(round(args.width * s_scale))
    args.height = int(round(args.height * s_scale))

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

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

    sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
    from _sample_pool import parallel_sample_records  # noqa: E402

    def _attempt(rng):
        return sample_instance(
            rng, args.width, args.height,
            min_marks_total=args.min_marks,
            max_marks_total=args.max_marks,
            min_crossings=args.min_crossings,
            max_crossings=args.max_crossings,
            min_pixel_between_marks=min_pixel_between_marks,
            s_endpoint_excl_px=s_endpoint_excl_px,
            num_waypoints=num_waypoints,
            num_extra_distractor_curves=num_extra_distractor_curves,
            max_attempts=50,
        )

    records_raw = parallel_sample_records(
        _attempt, count=args.count, workers=args.workers,
        seed_base=args.seed,
    )
    rng_render = random.Random(args.seed ^ 0xA5A5)
    for idx, record in enumerate(records_raw):
        name = f"traverse_ordering_{idx:05d}.png"
        ns = rng_render.randint(0, 10**9)
        render_instance(img_dir / name, record, noise_seed=ns)
        polylines = record.pop("polylines")
        record["polylines"] = [_polyline_to_list(p) for p in polylines]
        record["image"] = f"images/{name}"
        records.append(record)
    print(f"  {len(records)}/{args.count} valid samples (workers={args.workers})")

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

    data_json = {
        "task": "traverse_ordering",
        "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()