File size: 22,595 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
from __future__ import annotations

import argparse
import json
import random
import string
from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Set, Tuple

from PIL import Image, ImageDraw, ImageFont


# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------

@dataclass
class MazeLayout:
    rows: int
    cols: int
    vertical_walls: List[List[bool]]
    horizontal_walls: List[List[bool]]
    # (side, index) for each opening in label order
    openings: List[Tuple[str, int]]
    # (side, index, row, col) in label order
    opening_cells: List[Tuple[str, int, int, int]]
    # Indices into openings[] that are the connected pair (always sorted)
    connected_indices: Tuple[int, int]
    path_length: int


# ---------------------------------------------------------------------------
# Maze generation (DFS / recursive backtracking)
# ---------------------------------------------------------------------------

def _generate_maze(
    rng: random.Random,
    rows: int,
    cols: int,
) -> Tuple[List[List[bool]], List[List[bool]]]:
    """Return (vertical_walls, horizontal_walls).

    vertical_walls[r][c]   = True  →  wall on the right side of cell (r, c)
    horizontal_walls[r][c] = True  →  wall on the bottom of cell (r, c)
    """
    visited = [[False] * cols for _ in range(rows)]
    vertical_walls = [[True] * cols for _ in range(rows)]
    horizontal_walls = [[True] * cols for _ in range(rows)]

    def dfs(r: int, c: int) -> None:
        visited[r][c] = True
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        rng.shuffle(directions)
        for dr, dc in directions:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc]:
                if dr == -1:
                    horizontal_walls[nr][nc] = False
                elif dr == 1:
                    horizontal_walls[r][c] = False
                elif dc == -1:
                    vertical_walls[nr][nc] = False
                elif dc == 1:
                    vertical_walls[r][c] = False
                dfs(nr, nc)

    dfs(0, 0)
    return vertical_walls, horizontal_walls


def _open_neighbors(
    vertical_walls: List[List[bool]],
    horizontal_walls: List[List[bool]],
    rows: int,
    cols: int,
    r: int,
    c: int,
) -> List[Tuple[int, int]]:
    neighbors: List[Tuple[int, int]] = []
    if r > 0 and not horizontal_walls[r - 1][c]:
        neighbors.append((r - 1, c))
    if r < rows - 1 and not horizontal_walls[r][c]:
        neighbors.append((r + 1, c))
    if c > 0 and not vertical_walls[r][c - 1]:
        neighbors.append((r, c - 1))
    if c < cols - 1 and not vertical_walls[r][c]:
        neighbors.append((r, c + 1))
    return neighbors


def _reachable(
    vertical_walls: List[List[bool]],
    horizontal_walls: List[List[bool]],
    rows: int,
    cols: int,
    start: Tuple[int, int],
) -> Set[Tuple[int, int]]:
    queue: deque[Tuple[int, int]] = deque([start])
    seen: Set[Tuple[int, int]] = {start}
    while queue:
        r, c = queue.popleft()
        for nr, nc in _open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c):
            if (nr, nc) not in seen:
                seen.add((nr, nc))
                queue.append((nr, nc))
    return seen


def _path_cells(
    vertical_walls: List[List[bool]],
    horizontal_walls: List[List[bool]],
    rows: int,
    cols: int,
    start: Tuple[int, int],
    goal: Tuple[int, int],
) -> Set[Tuple[int, int]]:
    """BFS path between start and goal; returns the set of cells on the path."""
    queue: deque[Tuple[int, int]] = deque([start])
    prev: Dict[Tuple[int, int], Tuple[int, int] | None] = {start: None}
    while queue:
        r, c = queue.popleft()
        if (r, c) == goal:
            break
        for nr, nc in _open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c):
            if (nr, nc) not in prev:
                prev[(nr, nc)] = (r, c)
                queue.append((nr, nc))
    if goal not in prev:
        return set()
    cells: Set[Tuple[int, int]] = set()
    cur: Tuple[int, int] | None = goal
    while cur is not None:
        cells.add(cur)
        cur = prev[cur]
    return cells


def _opening_candidates(rows: int, cols: int, corner_buffer: int = 1) -> List[Tuple[str, int, int, int]]:
    """(side, border_index, row, col) for each candidate opening."""
    candidates: List[Tuple[str, int, int, int]] = []
    for c in range(corner_buffer, cols - corner_buffer):
        candidates.append(("top", c, 0, c))
        candidates.append(("bottom", c, rows - 1, c))
    for r in range(corner_buffer, rows - corner_buffer):
        candidates.append(("left", r, r, 0))
        candidates.append(("right", r, r, cols - 1))
    return candidates


def _looks_natural(
    vertical_walls: List[List[bool]],
    horizontal_walls: List[List[bool]],
    rows: int,
    cols: int,
    r: int,
    c: int,
) -> bool:
    return len(_open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c)) >= 1


def _isolate_decoy(
    vertical_walls: List[List[bool]],
    horizontal_walls: List[List[bool]],
    rows: int,
    cols: int,
    rng: random.Random,
    root: Tuple[int, int],
    forbidden: Set[Tuple[int, int]],
    min_size: int,
    max_size: int,
) -> Set[Tuple[int, int]]:
    """Grow a compact subtree from root that avoids forbidden cells, then wall
    it off so it forms an isolated dead-end region."""
    if root in forbidden:
        return set()

    queue: deque[Tuple[int, int]] = deque([root])
    subtree: Set[Tuple[int, int]] = {root}
    max_depth = rows * cols

    while queue and len(subtree) < max_size:
        r, c = queue.popleft()
        neighbors = _open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c)
        rng.shuffle(neighbors)
        for nr, nc in neighbors:
            if (nr, nc) in subtree or (nr, nc) in forbidden:
                continue
            subtree.add((nr, nc))
            queue.append((nr, nc))
            if len(subtree) >= max_size:
                break

    if len(subtree) < min_size:
        return set()

    # Wall off subtree from the rest of the maze
    for r, c in list(subtree):
        if r > 0 and (r - 1, c) not in subtree:
            horizontal_walls[r - 1][c] = True
        if r < rows - 1 and (r + 1, c) not in subtree:
            horizontal_walls[r][c] = True
        if c > 0 and (r, c - 1) not in subtree:
            vertical_walls[r][c - 1] = True
        if c < cols - 1 and (r, c + 1) not in subtree:
            vertical_walls[r][c] = True

    return subtree


# ---------------------------------------------------------------------------
# Layout sampling
# ---------------------------------------------------------------------------

def sample_layout(
    rng: random.Random,
    rows: int,
    cols: int,
    num_openings: int,
    min_path_length_floor: int = 0,
) -> MazeLayout:
    """Generate a perfect maze and place border openings.

    Exactly two openings are connected through the maze interior; all others
    lead to isolated dead-end pockets (decoys).  The opening order is shuffled
    so that the connected pair does not always occupy the first two label slots.
    """
    vertical_walls, horizontal_walls = _generate_maze(rng, rows, cols)
    border_cells = _opening_candidates(rows, cols, corner_buffer=1)
    k = max(2, min(num_openings, len(border_cells)))

    # Pick a connected pair with a long interior path
    min_path_len = max(min_path_length_floor, (rows * cols) // 3)
    candidates: List[Tuple] = []
    for i in range(len(border_cells)):
        for j in range(i + 1, len(border_cells)):
            a, b = border_cells[i], border_cells[j]
            path = _path_cells(
                vertical_walls, horizontal_walls, rows, cols,
                (a[2], a[3]), (b[2], b[3]),
            )
            if len(path) >= min_path_len:
                candidates.append((a, b, path))

    if candidates:
        first, second, path = rng.choice(candidates)
    else:
        first, second = rng.sample(border_cells, 2)
        path = _path_cells(
            vertical_walls, horizontal_walls, rows, cols,
            (first[2], first[3]), (second[2], second[3]),
        )

    main_pair = [first, second]
    forbidden: Set[Tuple[int, int]] = set(path)

    # Build decoy openings
    total = rows * cols
    remaining = [
        cell for cell in border_cells
        if cell not in main_pair
        and (cell[2], cell[3]) not in path
        and _looks_natural(vertical_walls, horizontal_walls, rows, cols, cell[2], cell[3])
    ]
    rng.shuffle(remaining)

    extras: List[Tuple[str, int, int, int]] = []
    for side, idx, r, c in remaining:
        if len(extras) >= k - 2:
            break
        subtree = _isolate_decoy(
            vertical_walls, horizontal_walls, rows, cols, rng,
            (r, c), forbidden,
            min_size=3,
            max_size=max(12, (total * 3) // 5),
        )
        if not subtree:
            continue
        extras.append((side, idx, r, c))
        forbidden.update(subtree)

    # Validate: ensure main pair is connected and decoys cannot reach the exit
    ra, ca = first[2], first[3]
    rb, cb = second[2], second[3]
    main_component = _reachable(vertical_walls, horizontal_walls, rows, cols, (ra, ca))

    if (rb, cb) not in main_component:
        extras = []
    else:
        valid_extras = []
        for side, idx, r, c in extras:
            comp = _reachable(vertical_walls, horizontal_walls, rows, cols, (r, c))
            if (rb, cb) not in comp:
                valid_extras.append((side, idx, r, c))
        extras = valid_extras

    all_cells = main_pair + extras

    # Shuffle label order so connected pair is not always A-B
    order = list(range(len(all_cells)))
    rng.shuffle(order)
    shuffled = [all_cells[i] for i in order]

    conn_a = order.index(0)
    conn_b = order.index(1)
    if conn_a > conn_b:
        conn_a, conn_b = conn_b, conn_a

    return MazeLayout(
        rows=rows,
        cols=cols,
        vertical_walls=vertical_walls,
        horizontal_walls=horizontal_walls,
        openings=[(side, idx) for (side, idx, _, _) in shuffled],
        opening_cells=shuffled,
        connected_indices=(conn_a, conn_b),
        path_length=len(path),
    )


# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------

def _carve_openings(
    draw: ImageDraw.ImageDraw,
    rows: int,
    cols: int,
    cell_size: int,
    wall_width: int,
    margin: int,
    openings: List[Tuple[str, int]],
) -> None:
    x0, y0 = margin, margin
    x1, y1 = margin + cols * cell_size, margin + rows * cell_size
    opening_set = set(openings)

    for c in range(cols):
        if ("top", c) not in opening_set:
            xs = margin + c * cell_size
            draw.rectangle(
                [xs - wall_width // 2, y0 - wall_width // 2,
                 xs + cell_size + (wall_width - 1) // 2, y0 + (wall_width - 1) // 2],
                fill="black",
            )
        if ("bottom", c) not in opening_set:
            xs = margin + c * cell_size
            draw.rectangle(
                [xs - wall_width // 2, y1 - wall_width // 2,
                 xs + cell_size + (wall_width - 1) // 2, y1 + (wall_width - 1) // 2],
                fill="black",
            )

    for r in range(rows):
        if ("left", r) not in opening_set:
            ys = margin + r * cell_size
            draw.rectangle(
                [x0 - wall_width // 2, ys - wall_width // 2,
                 x0 + (wall_width - 1) // 2, ys + cell_size + (wall_width - 1) // 2],
                fill="black",
            )
        if ("right", r) not in opening_set:
            ys = margin + r * cell_size
            draw.rectangle(
                [x1 - wall_width // 2, ys - wall_width // 2,
                 x1 + (wall_width - 1) // 2, ys + cell_size + (wall_width - 1) // 2],
                fill="black",
            )


def _label_openings(
    draw: ImageDraw.ImageDraw,
    rows: int,
    cols: int,
    cell_size: int,
    wall_width: int,
    margin: int,
    openings: List[Tuple[str, int]],
) -> None:
    if not openings:
        return

    x0, y0 = margin, margin
    x1, y1 = margin + cols * cell_size, margin + rows * cell_size
    img_w = cols * cell_size + 2 * margin
    img_h = rows * cell_size + 2 * margin

    try:
        font = ImageFont.truetype("Arial.ttf", size=16)
    except Exception:
        try:
            font = ImageFont.truetype("DejaVuSans.ttf", size=16)
        except Exception:
            font = ImageFont.load_default()

    def measure(text: str) -> Tuple[float, float]:
        if hasattr(draw, "textbbox"):
            l, t, r, b = draw.textbbox((0, 0), text, font=font)
            return r - l, b - t
        if hasattr(font, "getbbox"):
            l, t, r, b = font.getbbox(text)
            return r - l, b - t
        return font.getsize(text)  # type: ignore[attr-defined]

    offset = wall_width + 4

    for i, (side, index) in enumerate(openings):
        label = string.ascii_uppercase[i]
        w, h = measure(label)

        if side == "top":
            col = max(0, min(cols - 1, index))
            cx = margin + col * cell_size + cell_size / 2
            x = cx - w / 2
            y = y0 - offset - h
        elif side == "bottom":
            col = max(0, min(cols - 1, index))
            cx = margin + col * cell_size + cell_size / 2
            x = cx - w / 2
            y = y1 + offset
        elif side == "left":
            row = max(0, min(rows - 1, index))
            cy = margin + row * cell_size + cell_size / 2
            x = x0 - offset - w
            y = cy - h / 2
        elif side == "right":
            row = max(0, min(rows - 1, index))
            cy = margin + row * cell_size + cell_size / 2
            x = x1 + offset
            y = cy - h / 2
        else:
            continue

        x = max(0.0, min(float(img_w - w), x))
        y = max(0.0, min(float(img_h - h), y))
        draw.text((x, y), label, fill="black", font=font)


def render_sample(
    out_path: Path,
    layout: MazeLayout,
    cell_size: int,
    wall_width: int,
    margin: int,
) -> None:
    if wall_width % 2 == 0:
        wall_width += 1

    rows, cols = layout.rows, layout.cols
    label_pad = max(16, wall_width * 2)
    draw_margin = margin + label_pad

    width = cols * cell_size + 2 * draw_margin
    height = rows * cell_size + 2 * draw_margin

    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)

    _carve_openings(draw, rows, cols, cell_size, wall_width, draw_margin, layout.openings)
    _label_openings(draw, rows, cols, cell_size, wall_width, draw_margin, layout.openings)

    for r in range(rows):
        for c in range(cols):
            cx = draw_margin + c * cell_size
            cy = draw_margin + r * cell_size

            if layout.vertical_walls[r][c] and c != cols - 1:
                x = cx + cell_size
                draw.rectangle(
                    [x - wall_width // 2, cy - wall_width // 2,
                     x + (wall_width - 1) // 2, cy + cell_size + (wall_width - 1) // 2],
                    fill="black",
                )

            if layout.horizontal_walls[r][c] and r != rows - 1:
                y = cy + cell_size
                draw.rectangle(
                    [cx - wall_width // 2, y - wall_width // 2,
                     cx + cell_size + (wall_width - 1) // 2, y + (wall_width - 1) // 2],
                    fill="black",
                )

    img.save(out_path)


# ---------------------------------------------------------------------------
# Annotation building
# ---------------------------------------------------------------------------

def choose_difficulty(rows: int, cols: int, num_openings: int) -> str:
    total = rows * cols
    if total <= 100 and num_openings <= 3:
        return "easy"
    if total <= 256 and num_openings <= 5:
        return "medium"
    return "hard"


def build_record(
    image_name: str,
    layout: MazeLayout,
    cell_size: int,
    wall_width: int,
    margin: int,
) -> Dict[str, object]:
    labels = [string.ascii_uppercase[i] for i in range(len(layout.openings))]
    answer_a = labels[layout.connected_indices[0]]
    answer_b = labels[layout.connected_indices[1]]

    opening_details = []
    for i, (side, idx) in enumerate(layout.openings):
        opening_details.append({
            "label": labels[i],
            "side": side,
            "index": idx,
            "is_connected": i in layout.connected_indices,
        })

    label_list = ", ".join(labels)
    question = (
        f"The image shows a maze with {len(labels)} labeled openings on its border: "
        f"{label_list}. Exactly one pair of openings is connected by a path through "
        f"the maze; all other pairs are blocked by walls. "
        f"Identify the connected pair. "
        f"Trace passages carefully from each opening — a path exists only if you "
        f"can travel from one opening to another through corridors without crossing "
        f"any wall. Report the connected pair in alphabetical order, formatted as "
        f"X-Y (for example, A-C). "
        f"Provide your final answer enclosed in <answer>...</answer> tags."
    )

    return {
        "image": image_name,
        "rows": layout.rows,
        "cols": layout.cols,
        "cell_size": cell_size,
        "wall_width": wall_width,
        "margin": margin,
        "num_openings": len(layout.openings),
        "openings": opening_details,
        "connected_pair": [answer_a, answer_b],
        "question": question,
        "answer": f"{answer_a}-{answer_b}",
        "path_length": layout.path_length,
        "difficulty": choose_difficulty(layout.rows, layout.cols, len(layout.openings)),
    }


# ---------------------------------------------------------------------------
# Dataset generation
# ---------------------------------------------------------------------------

def ensure_output_dir(root: Path) -> Tuple[Path, Path]:
    root.mkdir(parents=True, exist_ok=True)
    images_dir = root / "images"
    images_dir.mkdir(exist_ok=True)
    return root, images_dir


def generate_dataset(
    rng: random.Random,
    count: int,
    output_dir: Path,
    images_dir: Path,
    min_rows: int,
    max_rows: int,
    min_cols: int,
    max_cols: int,
    cell_size: int,
    wall_width: int,
    margin: int,
    min_openings: int,
    max_openings: int,
    min_path_length_floor: int = 0,
) -> None:
    records: List[Dict[str, object]] = []

    for idx in range(count):
        rows = rng.randint(min_rows, max_rows)
        cols = rng.randint(min_cols, max_cols)
        num_openings = rng.randint(min_openings, max_openings)

        layout = sample_layout(rng, rows, cols, num_openings,
                               min_path_length_floor=min_path_length_floor)

        image_name = f"maze_{idx:05d}.png"
        render_sample(images_dir / image_name, layout, cell_size, wall_width, margin)
        records.append(build_record(f"images/{image_name}", layout, cell_size, wall_width, margin))

    with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh:
        for record in records:
            fh.write(json.dumps(record) + "\n")

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


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Generate a maze puzzle dataset.")
    parser.add_argument("--output-root", type=Path, default=".", help="Dataset root directory.")
    parser.add_argument("--count", type=int, default=36)
    parser.add_argument("--min-rows", type=int, default=8)
    parser.add_argument("--max-rows", type=int, default=20)
    parser.add_argument("--min-cols", type=int, default=8)
    parser.add_argument("--max-cols", type=int, default=20)
    parser.add_argument("--cell-size", type=int, default=32)
    parser.add_argument("--wall-width", type=int, default=5)
    parser.add_argument("--margin", type=int, default=8)
    parser.add_argument("--min-openings", type=int, default=3)
    parser.add_argument("--max-openings", type=int, default=6)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--difficulty", type=int, default=5,
                        help="Integer difficulty >=0; scales maze size, openings, path length.")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    rng = random.Random(args.seed)
    output_dir, images_dir = ensure_output_dir(args.output_root)

    d = max(0, int(args.difficulty))
    # Formulas (no canvas_scale — canvas self-scales via rows × cols × cell_size):
    #   rows = cols = 10 + 2·d
    #   num_openings = min(10, 3 + d)
    #   min_path_length = 8 + 3·d
    #   wall_thickness_px = max(2, 5 − 0.3·d)
    #   dead_end_count = 3·d  (decoys)
    args.min_rows = args.max_rows = 10 + 2 * d
    args.min_cols = args.max_cols = 10 + 2 * d
    num_openings_val = min(10, 3 + d)
    args.min_openings = num_openings_val
    args.max_openings = num_openings_val
    min_path_length_floor = 8 + 3 * d
    args.wall_width = max(2, int(round(5 - 0.3 * d)))
    dead_end_count = 3 * d  # noqa: F841  (reserved; decoys already grown from extras)

    generate_dataset(
        rng=rng,
        count=args.count,
        output_dir=output_dir,
        images_dir=images_dir,
        min_rows=args.min_rows,
        max_rows=args.max_rows,
        min_cols=args.min_cols,
        max_cols=args.max_cols,
        cell_size=args.cell_size,
        wall_width=args.wall_width,
        margin=args.margin,
        min_openings=args.min_openings,
        max_openings=args.max_openings,
        min_path_length_floor=min_path_length_floor,
    )

    print(f"Saved dataset to {args.output_root}")


if __name__ == "__main__":
    main()