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
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
#!/usr/bin/env python3
"""
Generate event-centric benchmark plans (final version: case1 + case2 only).

case1: Pure left/right horizontal translation (90% fg pixel exit, back-and-forth).
       Originally named traj_f.
case2: Two-segment translation + in-place lookback yaw (right/left variants).

Core coordinate idea: define camera trajectory as *relative* poses in
first-frame local coordinates, then transform to world via
``c2w_first @ local_pose``.

Local convention (OpenCV camera):
    X → right, Y → down, Z → forward (into the scene).
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import re

import yaml
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple

import cv2
import numpy as np


CASE_CHOICES = ("case1", "case2")
EVENT_IDS = ("A", "B", "C", "D", "E", "F")
_QWEN_VL_CACHE: Dict[str, Tuple[object, object, str]] = {}
_DETECTION_MODEL_CACHE: Dict[Tuple[str, str, str, bool], Tuple[object, object]] = {}


# ---------------------------------------------------------------------------
# Combo definition registry
# ---------------------------------------------------------------------------

@dataclass
class ComboDef:
    combo_id: str
    case_type: str               # "case1" or "case2"
    num_events: int              # 1, 2, or 3
    num_rounds: int              # 2-6
    first_frame_has_event: bool
    actions: List[Dict[str, str]]      # per-round {"action": ..., "event": ...}
    target_sequence: List[str]         # per-round target location ID
    motion_primitive: str              # "case1" | "case2_right" | "case2_left"
    is_core: bool = True               # core = generated by default
    event_ids: List[str] = field(default_factory=list)  # which event IDs are used
    frames_per_round: Optional[int] = None   # override CLI --frames-per-round
    fps: int = 16                            # video fps (metadata only)
    layout_scale: float = 1.0                # scale factor for layout radius


@dataclass
class LayoutConfig:
    """Spatial layout configuration for events and camera positions."""
    name: str                                # "triangle", "square", "line", etc.
    event_positions: Dict[str, List[float]]  # event_id -> [x, y, z] local
    centroid: np.ndarray                     # shape (3,), layout centroid
    camera_orientation: str                  # "outward" | "inward" | "forward"
    interpolation: str                       # "lerp_slerp"
    path_noise_std: float                    # 0.0 = no noise


def _make_combo(combo_id, case_type, num_events, num_rounds, first_frame_has_event,
                actions, targets, motion_primitive="default", is_core=True,
                event_ids=None):
    if event_ids is None:
        event_ids = ["A", "B", "C"][:num_events]
    return ComboDef(
        combo_id=combo_id, case_type=case_type, num_events=num_events,
        num_rounds=num_rounds, first_frame_has_event=first_frame_has_event,
        actions=actions, target_sequence=targets,
        motion_primitive=motion_primitive, is_core=is_core,
        event_ids=event_ids,
    )


COMBO_REGISTRY: Dict[str, ComboDef] = {}

# ============================================================================
# Case 1: 纯左右平移,去回去回 (原 traj_f, 2 combos)
# R0: 向右/左平移,到90%像素出屏幕
# R1: 平移回原点
# R2: 重复R0
# R3: 重复R1
# ============================================================================

COMBO_REGISTRY["case1_right"] = _make_combo(
    "case1_right", "case1", 1, 4, True,
    [{"action": "leave", "event": "A"},
     {"action": "revisit", "event": "A"},
     {"action": "leave", "event": "A"},
     {"action": "revisit", "event": "A"}],
    ["B", "A", "B", "A"],
    motion_primitive="case1_right",
    event_ids=["A"],
)

COMBO_REGISTRY["case1_left"] = _make_combo(
    "case1_left", "case1", 1, 4, True,
    [{"action": "leave", "event": "A"},
     {"action": "revisit", "event": "A"},
     {"action": "leave", "event": "A"},
     {"action": "revisit", "event": "A"}],
    ["B", "A", "B", "A"],
    motion_primitive="case1_left",
    event_ids=["A"],
)

# ============================================================================
# Case 2: 独立两段平移 + 两次转向 (2 combos, 4 rounds each)
# R0: A->B 平移,|AB|=T(T 按前景出屏阈值求得)
# R1: 在B原地转向前景中心
# R2: B->C 平移,|BC|=T(方向与AB一致)
# R3: 在C原地再转向前景中心
# ============================================================================

COMBO_REGISTRY["case2_right"] = _make_combo(
    "case2_right", "case2", 1, 4, True,
    [{"action": "leave", "event": "A"},
     {"action": "leave", "event": "A"},
     {"action": "leave", "event": "A"},
     {"action": "leave", "event": "A"}],
    ["B", "B", "C", "C"],
    motion_primitive="case2_right",
    event_ids=["A"],
)

COMBO_REGISTRY["case2_left"] = _make_combo(
    "case2_left", "case2", 1, 4, True,
    [{"action": "leave", "event": "A"},
     {"action": "leave", "event": "A"},
     {"action": "leave", "event": "A"},
     {"action": "leave", "event": "A"}],
    ["B", "B", "C", "C"],
    motion_primitive="case2_left",
    event_ids=["A"],
)


def get_combos_for_case(case_type: str, all_variants: bool = False) -> List[ComboDef]:
    """Return all ComboDef entries for a given case_type."""
    return [c for c in COMBO_REGISTRY.values()
            if c.case_type == case_type and (all_variants or c.is_core)]


# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------

@dataclass
class ObjectDetection:
    entities: List[str]
    bbox_xyxy: Tuple[int, int, int, int]
    area_ratio: float
    method: str


@dataclass
class SceneScale:
    scene_center: List[float]
    scene_extent_x: float
    scene_extent_z: float
    nav_radius: float
    event_radius: float
    motion_scale: float
    geometry_used: bool


@dataclass
class SceneFeatures:
    brightness_mean: float
    edge_density: float
    texture_std: float
    clutter_score: float
    environment_hint: str


# ---------------------------------------------------------------------------
# Scene meta
# ---------------------------------------------------------------------------

def _load_scene_meta(meta_path: str) -> Optional[Dict]:
    """Load scene meta.npz → dict with c2w (4×4) and points_world (N×3)."""
    if not meta_path or not Path(meta_path).exists():
        return None
    data = np.load(meta_path)
    if "c2w" not in data or "points_world" not in data:
        return None
    meta = {
        "c2w": data["c2w"].astype(np.float32),
        "points_world": data["points_world"].astype(np.float32),
        "intrinsics": data["intrinsics"].astype(np.float32),
    }
    if "target_h" in data:
        meta["target_h"] = int(data["target_h"])
    if "target_w" in data:
        meta["target_w"] = int(data["target_w"])
    return meta


def _filter_fg_depth_outliers(
    points_local: np.ndarray,
    u_proj: np.ndarray,
    v_proj: np.ndarray,
    *,
    keep_upper_q: float = 0.90,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Drop the farthest foreground depth tail to suppress long-tail artifacts."""
    pts = np.asarray(points_local, dtype=np.float32)
    u = np.asarray(u_proj, dtype=np.float32)
    v = np.asarray(v_proj, dtype=np.float32)
    if len(pts) == 0:
        return pts, u, v
    if pts.ndim != 2 or pts.shape[1] != 3:
        raise ValueError(f"points_local must be Nx3, got shape={pts.shape}")
    if len(u) != len(pts) or len(v) != len(pts):
        raise ValueError("u_proj/v_proj must align with points_local length")

    q_hi = float(np.clip(keep_upper_q, 0.5, 1.0))

    z = pts[:, 2]
    finite = np.isfinite(z)
    if not np.any(finite):
        raise ValueError("foreground points have no finite depth values")

    z_finite = z[finite]
    z_hi = float(np.quantile(z_finite, q_hi))
    keep = finite & (z <= z_hi)
    if int(np.count_nonzero(keep)) == 0:
        raise ValueError("depth outlier filtering removed all foreground points")

    return pts[keep], u[keep], v[keep]


def _estimate_event_points_local(
    scene_meta: Optional[Dict],
    fg_union_mask: np.ndarray,
) -> Optional[np.ndarray]:
    """Estimate foreground 3D points in first-frame local camera coordinates."""
    if scene_meta is None:
        return None
    if fg_union_mask is None:
        raise ValueError("fg_union_mask is required for mask-only foreground calibration")
    pts_w = scene_meta.get("points_world")
    c2w = scene_meta.get("c2w")
    K = scene_meta.get("intrinsics")
    if (
        pts_w is None
        or c2w is None
        or K is None
        or np.asarray(K).shape != (3, 3)
        or len(pts_w) == 0
    ):
        return None

    pts_w = np.asarray(pts_w, dtype=np.float32)
    w2c = np.linalg.inv(np.asarray(c2w, dtype=np.float32))
    ones = np.ones((len(pts_w), 1), dtype=np.float32)
    pts_local = (w2c @ np.hstack([pts_w, ones]).T).T[:, :3]

    z = pts_local[:, 2]
    valid = np.isfinite(z) & (z > 0.1)
    if valid.sum() < 64:
        return None

    fx, fy = float(K[0, 0]), float(K[1, 1])
    cx, cy = float(K[0, 2]), float(K[1, 2])
    x = pts_local[:, 0]
    y = pts_local[:, 1]
    u = fx * x / np.maximum(z, 1e-6) + cx
    v = fy * y / np.maximum(z, 1e-6) + cy

    fg_mask = np.asarray(fg_union_mask)
    if fg_mask.ndim != 2:
        raise ValueError(f"fg_union_mask must be HxW, got shape={fg_mask.shape}")
    fg_mask = (fg_mask > 0)
    mask_h, mask_w = fg_mask.shape
    if mask_h <= 0 or mask_w <= 0 or int(np.count_nonzero(fg_mask)) == 0:
        raise ValueError("fg_union_mask is empty")

    target_w = scene_meta.get("target_w")
    target_h = scene_meta.get("target_h")
    if target_w is None or target_h is None:
        raise ValueError("scene_meta must contain target_w/target_h for mask alignment")
    proj_w = max(1, int(target_w))
    proj_h = max(1, int(target_h))

    scale_u = float(mask_w) / float(proj_w)
    scale_v = float(mask_h) / float(proj_h)
    u_m = u * scale_u
    v_m = v * scale_v
    u_i = np.rint(u_m).astype(np.int32)
    v_i = np.rint(v_m).astype(np.int32)

    inside_image = (
        valid
        & np.isfinite(u_m)
        & np.isfinite(v_m)
        & (u_i >= 0)
        & (u_i < int(mask_w))
        & (v_i >= 0)
        & (v_i < int(mask_h))
    )
    if inside_image.sum() < 32:
        return None

    fg_hit = np.zeros_like(inside_image, dtype=bool)
    cand_idx = np.flatnonzero(inside_image)
    if cand_idx.size > 0:
        fg_hit[cand_idx] = fg_mask[v_i[cand_idx], u_i[cand_idx]]
    if fg_hit.sum() < 32:
        return None

    pts = pts_local[fg_hit]
    u_sel = u_m[fg_hit]
    v_sel = v_m[fg_hit]
    pts, u_sel, v_sel = _filter_fg_depth_outliers(pts, u_sel, v_sel)
    if len(pts) < 32:
        return None

    boundary_idx = np.array(
        [
            int(np.argmin(u_sel)),
            int(np.argmax(u_sel)),
            int(np.argmin(v_sel)),
            int(np.argmax(v_sel)),
        ],
        dtype=np.int64,
    )
    boundary_idx = np.unique(boundary_idx)

    if len(pts) > 2048:
        keep_set = set(boundary_idx.tolist())
        budget = 2048 - len(keep_set)
        if budget > 0:
            all_idx = np.arange(len(pts), dtype=np.int64)
            if keep_set:
                mask = np.ones(len(pts), dtype=bool)
                mask[np.array(sorted(keep_set), dtype=np.int64)] = False
                pool = all_idx[mask]
            else:
                pool = all_idx
            if len(pool) <= budget:
                sample_idx = pool
            else:
                sample_idx = pool[np.linspace(0, len(pool) - 1, budget, dtype=np.int64)]
            keep_idx = np.unique(
                np.concatenate(
                    [
                        np.array(sorted(keep_set), dtype=np.int64),
                        np.asarray(sample_idx, dtype=np.int64),
                    ]
                )
            )
        else:
            keep_idx = boundary_idx[:2048]
        pts = pts[keep_idx]

    pts = pts.astype(np.float32, copy=False)
    if not np.all(np.isfinite(pts)):
        pts = pts[np.isfinite(pts).all(axis=1)]
    if len(pts) == 0:
        return None
    return pts


# ---------------------------------------------------------------------------
# Image / scene feature helpers
# ---------------------------------------------------------------------------

def _load_image_rgb(image_path: str) -> np.ndarray:
    img_bgr = cv2.imread(image_path, cv2.IMREAD_COLOR)
    if img_bgr is None:
        raise FileNotFoundError(f"Cannot load image: {image_path}")
    return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)


def _prepare_image_to_target(image_rgb: np.ndarray, target_h: int, target_w: int) -> np.ndarray:
    """Resize/crop image to exact target size with same policy as scene builders."""
    from liveworld.geometry_utils import resize_short_edge_and_center_crop

    try:
        return resize_short_edge_and_center_crop(image_rgb, target_h, target_w)
    except ValueError:
        pass

    h, w = image_rgb.shape[:2]
    scale = min(target_w / float(w), target_h / float(h))
    new_w = max(1, int(round(w * scale)))
    new_h = max(1, int(round(h * scale)))
    resized = cv2.resize(image_rgb, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
    canvas = np.zeros((target_h, target_w, 3), dtype=np.uint8)
    y0 = (target_h - new_h) // 2
    x0 = (target_w - new_w) // 2
    canvas[y0 : y0 + new_h, x0 : x0 + new_w] = resized
    return canvas


def _prepare_detection_image_for_scene(
    image_path: str,
    scene_meta: Optional[Dict],
) -> str:
    """Return detection image path aligned to scene_meta target geometry."""
    if scene_meta is None:
        return image_path
    target_h = scene_meta.get("target_h")
    target_w = scene_meta.get("target_w")
    if target_h is None or target_w is None:
        return image_path
    target_h = int(target_h)
    target_w = int(target_w)
    if target_h <= 0 or target_w <= 0:
        return image_path

    raw_rgb = _load_image_rgb(image_path)
    if raw_rgb.shape[0] == target_h and raw_rgb.shape[1] == target_w:
        return image_path

    aligned_rgb = _prepare_image_to_target(raw_rgb, target_h, target_w)
    src = Path(image_path).resolve()
    cache_dir = Path(".cache/event_bench/detect_aligned")
    cache_dir.mkdir(parents=True, exist_ok=True)
    key = f"{src}|{target_h}x{target_w}"
    digest = hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]
    out_path = cache_dir / f"{src.stem}_{target_h}x{target_w}_{digest}.png"
    if not out_path.exists():
        cv2.imwrite(str(out_path), cv2.cvtColor(aligned_rgb, cv2.COLOR_RGB2BGR))
    return str(out_path)


def extract_scene_features(image_rgb: np.ndarray) -> SceneFeatures:
    gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
    brightness_mean = float(np.mean(gray) / 255.0)
    edges = cv2.Canny(gray, threshold1=80, threshold2=160)
    edge_density = float(np.mean(edges > 0))
    texture_std = float(np.std(cv2.Laplacian(gray, cv2.CV_32F)))
    texture_norm = float(np.clip(texture_std / 40.0, 0.0, 1.0))
    clutter_score = float(np.clip(0.6 * edge_density + 0.4 * texture_norm, 0.0, 1.0))

    if clutter_score > 0.42:
        environment_hint = "cluttered"
    elif clutter_score > 0.22:
        environment_hint = "moderate"
    else:
        environment_hint = "open"

    return SceneFeatures(
        brightness_mean=brightness_mean,
        edge_density=edge_density,
        texture_std=texture_std,
        clutter_score=clutter_score,
        environment_hint=environment_hint,
    )


# ---------------------------------------------------------------------------
# Object detection
# ---------------------------------------------------------------------------

_DYNAMIC_FILTER_PROMPT = """\
Given this image and these detected objects: {entities}

Which of these can move ON THEIR OWN? (people, animals, birds, vehicles, robots, etc.)

STATIC (exclude): furniture, appliances, fixtures, radiators, doors, windows,
lamps, plants, decorations, buildings, structures, signs, sky, water, road, ground.

List ONLY the dynamic/movable ones. If none can move, output exactly: Nothing

Output format:
Nothing
OR numbered list:
1) person
2) dog"""

_STATIC_ENTITY_KEYWORDS = (
    "sky",
    "cloud",
    "ground",
    "floor",
    "ceiling",
    "wall",
    "road",
    "street",
    "sidewalk",
    "building",
    "tree",
    "grass",
    "mountain",
    "water",
    "river",
    "lake",
    "ocean",
    "sea",
    "snow",
    "forest",
    "background",
    "scenery",
    "furniture",
    "table",
    "chair",
    "sofa",
    "couch",
    "bench",
    "door",
    "window",
    "ceiling",
)


def _is_static_entity_label(text: str) -> bool:
    lowered = str(text).strip().lower()
    if not lowered:
        return True
    if lowered in {"none", "nothing", "background"}:
        return True
    for kw in _STATIC_ENTITY_KEYWORDS:
        if re.search(rf"\b{re.escape(kw)}\b", lowered):
            return True
    return False


def _bbox_from_mask(mask: np.ndarray) -> Tuple[int, int, int, int]:
    ys, xs = np.where(mask > 0)
    if len(xs) == 0:
        return (0, 0, 0, 0)
    return (int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max()))


def detect_event_object(
    image_path: str,
    qwen_model_path: str,
    sam3_model_path: str,
    scene_detect_prompt: str,
    qwen_device: str = "cuda",
    cpu_offload_qwen: bool = False,
    cpu_offload_sam3: bool = False,
) -> Tuple[ObjectDetection, np.ndarray]:
    """Detect all foreground entities using Qwen+SAM."""
    from scripts.create_train_data._entity_detector import Qwen3VLEntityExtractor
    from scripts.create_train_data._sam3_segmenter import Sam3VideoSegmenter

    qwen_device = str(qwen_device).strip().lower() if qwen_device else "cuda"
    if cpu_offload_qwen:
        qwen_device = "cpu"
    if qwen_device not in {"cuda", "cpu"}:
        qwen_device = "cuda"
    if qwen_device == "cuda":
        try:
            import torch
            if not torch.cuda.is_available():
                qwen_device = "cpu"
        except Exception:
            qwen_device = "cpu"

    cache_key = (qwen_model_path, sam3_model_path, qwen_device, bool(cpu_offload_sam3))
    if cache_key not in _DETECTION_MODEL_CACHE:
        qwen = Qwen3VLEntityExtractor(model_path=qwen_model_path, device=qwen_device)
        sam3 = None if cpu_offload_sam3 else Sam3VideoSegmenter(checkpoint_path=sam3_model_path)
        _DETECTION_MODEL_CACHE[cache_key] = (qwen, sam3)
    else:
        qwen, sam3 = _DETECTION_MODEL_CACHE[cache_key]

    if cpu_offload_sam3 or sam3 is None:
        sam3 = Sam3VideoSegmenter(checkpoint_path=sam3_model_path)

    raw_entities, _ = qwen.extract(image_path, prompt=scene_detect_prompt)
    entities = sorted(
        {
            str(e).strip()
            for e in raw_entities
            if str(e).strip() and not _is_static_entity_label(str(e))
        }
    )
    if entities and hasattr(qwen, "generate_text"):
        try:
            from scripts.create_train_data._entity_detector import parse_entities as _parse_entities

            filter_prompt = _DYNAMIC_FILTER_PROMPT.format(entities=", ".join(entities))
            filter_raw = qwen.generate_text(image_path, filter_prompt)
            filtered = [
                str(e).strip()
                for e in _parse_entities(filter_raw)
                if str(e).strip() and not _is_static_entity_label(str(e))
            ]
            if filtered:
                entities = sorted({e for e in filtered})
        except Exception as exc:
            print(f"  [warn] dynamic entity filtering failed, fallback to raw entities ({exc})")
    image_rgb = _load_image_rgb(image_path)
    h, w = image_rgb.shape[:2]

    if not entities:
        print(
            f"  [warn] Qwen detected no dynamic entities in {image_path}, "
            "using center-crop fallback mask"
        )
        entities = ["foreground entity"]
        union_mask = np.zeros((h, w), dtype=np.uint8)
        cy, cx = h // 2, w // 2
        rh, rw = h // 4, w // 4
        union_mask[cy - rh : cy + rh, cx - rw : cx + rw] = 1
    else:
        union_mask = np.zeros((h, w), dtype=np.uint8)
        for ent in entities:
            seg = sam3.segment(
                video_path=image_path,
                prompts=[ent],
                frame_index=0,
                expected_frames=1,
            )
            if seg is None or seg.size == 0:
                print(f"  [warn] SAM3 returned empty mask for '{ent}', skipping")
                continue
            if seg.ndim == 3:
                mask = seg[0]
            elif seg.ndim == 2:
                mask = seg
            else:
                mask = seg.reshape(seg.shape[-2], seg.shape[-1])
            union_mask = np.maximum(union_mask, (mask > 0).astype(np.uint8))

    x1, y1, x2, y2 = _bbox_from_mask(union_mask)
    if x2 <= x1 or y2 <= y1:
        print(
            f"  [warn] SAM3 union mask for entities {entities} has zero area, "
            "using center-crop fallback mask"
        )
        union_mask = np.zeros((h, w), dtype=np.uint8)
        cy, cx = h // 2, w // 2
        rh, rw = h // 4, w // 4
        union_mask[cy - rh : cy + rh, cx - rw : cx + rw] = 1
        x1, y1, x2, y2 = _bbox_from_mask(union_mask)
    area_ratio = ((x2 - x1 + 1) * (y2 - y1 + 1)) / float(h * w)
    det = ObjectDetection(
        entities=entities,
        bbox_xyxy=(int(x1), int(y1), int(x2), int(y2)),
        area_ratio=float(area_ratio),
        method="qwen_sam",
    )
    if cpu_offload_sam3:
        try:
            import gc
            import torch

            del sam3
            gc.collect()
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
        except Exception:
            pass
    return det, union_mask.astype(np.uint8)


# ---------------------------------------------------------------------------
# Motion scale estimation
# ---------------------------------------------------------------------------


def _estimate_motion_scale_from_area_ratio(area_ratio: float) -> float:
    if area_ratio >= 0.18:
        return 0.65
    if area_ratio >= 0.10:
        return 0.85
    if area_ratio >= 0.05:
        return 1.05
    if area_ratio >= 0.02:
        return 1.25
    return 1.45


def _parse_motion_scale_from_text(text: str) -> Optional[float]:
    if not text:
        return None
    start = text.find("{")
    end = text.rfind("}")
    if start >= 0 and end >= start:
        try:
            obj = json.loads(text[start : end + 1])
            if "motion_scale" in obj:
                val = float(obj["motion_scale"])
                return float(np.clip(val, 0.5, 1.8))
        except Exception:
            pass
    m = re.search(r"([-+]?\d*\.?\d+)", text)
    if m is None:
        return None
    try:
        val = float(m.group(1))
        return float(np.clip(val, 0.5, 1.8))
    except Exception:
        return None


def _qwen_vl_motion_scale(
    image_path: str,
    qwen_model_path: str,
    prompt: str,
) -> Optional[float]:
    try:
        import torch
        from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
    except Exception:
        return None

    try:
        device = "cuda" if torch.cuda.is_available() else "cpu"
        cache_key = f"{qwen_model_path}@{device}"
        if cache_key not in _QWEN_VL_CACHE:
            load_kwargs = {
                "device_map": {"": device},
            }
            if device == "cuda":
                load_kwargs["dtype"] = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
                load_kwargs["attn_implementation"] = "flash_attention_2"
            else:
                load_kwargs["dtype"] = torch.float32

            model = Qwen3VLForConditionalGeneration.from_pretrained(qwen_model_path, **load_kwargs)
            processor = AutoProcessor.from_pretrained(qwen_model_path)
            _QWEN_VL_CACHE[cache_key] = (model, processor, device)

        model, processor, device = _QWEN_VL_CACHE[cache_key]

        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "image", "image": image_path},
                    {"type": "text", "text": prompt},
                ],
            }
        ]
        inputs = processor.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=True,
            return_dict=True,
            return_tensors="pt",
        )
        inputs = inputs.to(device)

        with torch.no_grad():
            out_ids = model.generate(**inputs, max_new_tokens=96)
        trimmed = [o[len(i) :] for i, o in zip(inputs.input_ids, out_ids)]
        text = processor.batch_decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        return _parse_motion_scale_from_text(text)
    except Exception:
        return None


def _maybe_llm_adjust_motion_scale(
    enable: bool,
    image_path: str,
    qwen_model_path: str,
    area_ratio: float,
    scene_features: SceneFeatures,
    case_type: str,
) -> Optional[float]:
    if not enable:
        return None

    prompt = (
        "You are planning camera movement scale for a scene benchmark.\n"
        f"Case: {case_type}\n"
        f"Detected event object area ratio in first frame: {area_ratio:.4f}\n"
        f"Scene environment hint: {scene_features.environment_hint}\n"
        f"Scene clutter score [0,1]: {scene_features.clutter_score:.4f}\n"
        f"Image brightness mean [0,1]: {scene_features.brightness_mean:.4f}\n"
        "Return JSON only: {\"motion_scale\": number}.\n"
        "Allowed range: 0.5 to 1.8. Larger means farther movement.\n"
        "If object appears large/close or scene is cluttered, reduce movement scale.\n"
    )

    return _qwen_vl_motion_scale(
        image_path=image_path,
        qwen_model_path=qwen_model_path,
        prompt=prompt,
    )


def _estimate_nav_radius_screen_uniform(
    *,
    pts_local: np.ndarray,
    intrinsics: np.ndarray,
    target_w: Optional[int],
    target_shift_ratio: float,
    screen_depth_percentile: float,
) -> Optional[float]:
    """Estimate nav radius from desired screen-space displacement."""
    if pts_local is None or len(pts_local) == 0:
        return None
    if intrinsics is None or np.asarray(intrinsics).shape != (3, 3):
        return None

    z = np.asarray(pts_local[:, 2], dtype=np.float32)
    valid = np.isfinite(z) & (z > 0.25)
    if valid.sum() < 128:
        return None

    z_ref = float(np.percentile(z[valid], float(np.clip(screen_depth_percentile, 5.0, 95.0))))
    fx = float(abs(intrinsics[0, 0]))
    if not np.isfinite(fx) or fx < 1e-6:
        return None

    if target_w is None or int(target_w) <= 0:
        return None

    ratio = float(np.clip(target_shift_ratio, 0.05, 0.45))
    target_px = float(target_w) * ratio
    d = target_px * z_ref / fx
    nav_radius = d / 0.8
    return float(np.clip(nav_radius, 0.4, 3.2))


def estimate_scene_scale(
    det: ObjectDetection,
    scene_features: SceneFeatures,
    image_path: str,
    geometry_path: str,
    case_type: str,
    llm_motion_scaling: bool,
    qwen_model_path: str,
    scene_meta: Optional[Dict] = None,
    distance_mode: str = "screen_uniform",
    target_shift_ratio: float = 0.18,
    screen_depth_percentile: float = 45.0,
    distance_blend_alpha: float = 0.7,
) -> SceneScale:
    """Estimate nav_radius / event_radius for trajectory planning (strict screen_uniform)."""
    _ = geometry_path
    _ = distance_blend_alpha
    if distance_mode != "screen_uniform":
        raise ValueError(
            f"Unsupported distance_mode={distance_mode}. Only 'screen_uniform' is allowed."
        )
    if scene_meta is None:
        raise ValueError("scene_meta is required for strict trajectory scale estimation.")

    motion_scale = _estimate_motion_scale_from_area_ratio(det.area_ratio)
    motion_scale = float(motion_scale * (1.1 - 0.35 * scene_features.clutter_score))
    llm_scale = _maybe_llm_adjust_motion_scale(
        enable=llm_motion_scaling,
        image_path=image_path,
        qwen_model_path=qwen_model_path,
        area_ratio=det.area_ratio,
        scene_features=scene_features,
        case_type=case_type,
    )
    if llm_scale is not None:
        motion_scale = 0.6 * motion_scale + 0.4 * llm_scale

    c2w = scene_meta["c2w"]  # (4,4)
    w2c = np.linalg.inv(c2w)
    pts_w = scene_meta["points_world"]
    ones = np.ones((len(pts_w), 1), dtype=np.float32)
    pts_local = (w2c @ np.hstack([pts_w, ones]).T).T[:, :3]
    extent_x = float(np.percentile(pts_local[:, 0], 95) - np.percentile(pts_local[:, 0], 5))
    extent_z = float(np.percentile(pts_local[:, 2], 95) - np.percentile(pts_local[:, 2], 5))
    nav_radius = _estimate_nav_radius_screen_uniform(
        pts_local=pts_local,
        intrinsics=scene_meta.get("intrinsics"),
        target_w=scene_meta.get("target_w"),
        target_shift_ratio=target_shift_ratio,
        screen_depth_percentile=screen_depth_percentile,
    )
    if nav_radius is None:
        raise ValueError("Failed to estimate nav_radius in strict screen_uniform mode.")

    event_radius = float(np.clip(2.0 * nav_radius, 0.8, 6.0))
    return SceneScale(
        scene_center=[0.0, 0.0, 0.0],
        scene_extent_x=float(max(0.1, extent_x)),
        scene_extent_z=float(max(0.1, extent_z)),
        nav_radius=nav_radius,
        event_radius=event_radius,
        motion_scale=float(motion_scale),
        geometry_used=True,
    )


# ---------------------------------------------------------------------------
# Local-frame trajectory helpers
# ---------------------------------------------------------------------------

def _circle_points_local(
    radius: float,
    count: int,
    y: float = 0.0,
    z_offset: float = 0.0,
    angle_offset_deg: float = 0.0,
) -> List[List[float]]:
    """Circle in the local XZ plane centred at origin."""
    pts: List[List[float]] = []
    for i in range(count):
        ang = math.radians(angle_offset_deg + (360.0 * i / count))
        x = radius * math.sin(ang)
        z = z_offset + radius * math.cos(ang)
        pts.append([float(x), float(y), float(z)])
    return pts


def _normalize(v: np.ndarray) -> np.ndarray:
    n = float(np.linalg.norm(v))
    if n < 1e-8:
        return v
    return v / n


def _lookat_local(position: np.ndarray, look_at: np.ndarray) -> np.ndarray:
    """Build a 4×4 c2w (local) that looks from *position* towards *look_at*."""
    forward = _normalize(look_at - position)
    if float(np.linalg.norm(forward)) < 1e-8:
        forward = np.array([0.0, 0.0, 1.0], dtype=np.float32)
    world_up = np.array([0.0, -1.0, 0.0], dtype=np.float32)
    right = np.cross(forward, world_up)
    if float(np.linalg.norm(right)) < 1e-8:
        world_up = np.array([1.0, 0.0, 0.0], dtype=np.float32)
        right = np.cross(forward, world_up)
    right = _normalize(right)
    down = _normalize(np.cross(forward, right))

    c2w = np.eye(4, dtype=np.float32)
    c2w[:3, 0] = right
    c2w[:3, 1] = down
    c2w[:3, 2] = forward
    c2w[:3, 3] = position
    return c2w


def _local_to_world(local_c2w: np.ndarray, first_c2w: np.ndarray) -> np.ndarray:
    """Transform a local-frame c2w into world coordinates."""
    return (first_c2w @ local_c2w).astype(np.float32)


# ---------------------------------------------------------------------------
# Event slot builder
# ---------------------------------------------------------------------------

def _build_event_slots(
    combo: ComboDef,
    event_points: Dict[str, List[float]],
    entities: List[str],
) -> Dict[str, Dict]:
    """Build event slots based on combo definition."""
    slots: Dict[str, Dict] = {}
    spawn_rounds: Dict[str, int] = {}
    for i, act in enumerate(combo.actions):
        eid = act.get("event", "")
        if act["action"] == "spawn" and eid:
            spawn_rounds[eid] = i
    if combo.first_frame_has_event and "A" in combo.event_ids:
        spawn_rounds.setdefault("A", -1)

    entities_text = ", ".join(entities) if entities else "foreground entity"
    for eid in combo.event_ids:
        if eid not in event_points:
            continue
        slots[eid] = {
            "entities": list(entities),
            "entity": entities_text,
            "position": event_points[eid],
            "spawn_round": spawn_rounds.get(eid, 0),
        }
    return slots


# ---------------------------------------------------------------------------
# Location / pose pool  (all in LOCAL coords)
# ---------------------------------------------------------------------------

def _build_location_pool(
    nav_radius: float,
    event_slots: Dict[str, Dict],
) -> Dict[str, List[float]]:
    """Camera locations in local XZ plane."""
    pool: Dict[str, List[float]] = {}
    pool["S"] = [0.0, 0.0, 0.0]
    pool["O"] = [0.0, 0.0, 0.9 * nav_radius]
    return pool


def _build_location_pose_pool(
    location_pool: Dict[str, List[float]],
    event_slots: Dict[str, Dict],
) -> Dict[str, Dict]:
    """For each location, build a local c2w."""
    pose_pool: Dict[str, Dict] = {}
    forward_target = np.array([0.0, 0.0, 1.0], dtype=np.float32)
    for loc, pos_list in location_pool.items():
        pos = np.asarray(pos_list, dtype=np.float32)
        if loc == "S":
            c2w = np.eye(4, dtype=np.float32)
            look = forward_target
        elif loc in event_slots:
            look = np.asarray(event_slots[loc]["position"], dtype=np.float32)
            c2w = _lookat_local(pos, look)
        else:
            look = np.zeros(3, dtype=np.float32)
            c2w = _lookat_local(pos, look)
        pose_pool[loc] = {
            "position": [float(x) for x in pos],
            "look_at": [float(x) for x in look],
            "c2w": c2w.astype(float).tolist(),
        }
    return pose_pool


# ---------------------------------------------------------------------------
# Trajectory calibration helpers
# ---------------------------------------------------------------------------

def _yaw_c2w_local(yaw_deg: float, position: Optional[np.ndarray] = None) -> np.ndarray:
    """Build a local c2w with given yaw angle around Y-down axis."""
    rad = math.radians(yaw_deg)
    c = math.cos(rad)
    s = math.sin(rad)
    R = np.array([
        [ c, 0.0, s],
        [0.0, 1.0, 0.0],
        [-s, 0.0, c],
    ], dtype=np.float32)
    c2w = np.eye(4, dtype=np.float32)
    c2w[:3, :3] = R
    if position is not None:
        c2w[:3, 3] = position
    return c2w


def _count_visible_fg_projection_points(
    *,
    points_local: np.ndarray,
    intrinsics: np.ndarray,
    image_width: int,
    image_height: int,
    position_local: np.ndarray,
    yaw_deg: float,
) -> int:
    """Count visible foreground projections for one candidate local pose."""
    pts = np.asarray(points_local, dtype=np.float32)
    if pts.ndim != 2 or pts.shape[1] != 3 or len(pts) == 0:
        return 0

    c2w = _yaw_c2w_local(float(yaw_deg), position=np.asarray(position_local, dtype=np.float32))
    R = c2w[:3, :3]
    t = c2w[:3, 3]
    p_cam = (R.T @ (pts - t).T).T

    z = p_cam[:, 2]
    valid_z = np.isfinite(z) & (z > 1e-6)
    if not np.any(valid_z):
        return 0

    fx = float(intrinsics[0, 0])
    fy = float(intrinsics[1, 1])
    cx = float(intrinsics[0, 2])
    cy = float(intrinsics[1, 2])
    u = fx * p_cam[:, 0] / np.maximum(z, 1e-6) + cx
    v = fy * p_cam[:, 1] / np.maximum(z, 1e-6) + cy

    W = max(1, int(image_width))
    H = max(1, int(image_height))
    visible = (
        valid_z
        & np.isfinite(u)
        & np.isfinite(v)
        & (u >= 0.0)
        & (u < float(W))
        & (v >= 0.0)
        & (v < float(H))
    )
    return int(np.count_nonzero(visible))


def _compute_exit_visible_threshold(
    points_local: Optional[np.ndarray],
    exit_visible_ratio: float,
) -> int:
    """Compute visible-count threshold for exit detection."""
    if exit_visible_ratio <= 0:
        return 0
    if points_local is None:
        return 0
    total = int(len(points_local))
    if total <= 0:
        return 0
    ratio = float(np.clip(exit_visible_ratio, 0.0, 1.0))
    if ratio <= 0.0:
        return 0
    threshold = int(math.ceil(total * ratio))
    return max(1, threshold)


def _find_first_no_projection_param(
    eval_visible_count,
    *,
    hi: float,
    n_steps: int = 320,
    visible_count_threshold: int = 0,
) -> Optional[float]:
    """Dense-sample a trajectory and return first param where visible count is low."""
    if hi <= 0:
        return None

    threshold = max(0, int(visible_count_threshold))
    c0 = int(eval_visible_count(0.0))
    if c0 <= threshold:
        return 0.0

    for i in range(1, n_steps + 1):
        t = hi * float(i) / float(n_steps)
        c = int(eval_visible_count(t))
        if c <= threshold:
            return float(t)
    return None


def _solve_symmetric_exit_limits(
    *,
    points_local: np.ndarray,
    intrinsics: np.ndarray,
    image_width: int,
    image_height: int,
    nav_radius: float,
    max_yaw: float = 85.0,
    visible_count_threshold: int = 0,
) -> Dict[str, Optional[float]]:
    """Solve left/right exit limits by foreground no-projection criterion."""
    W = max(1, int(image_width))
    H = max(1, int(image_height))
    pts = np.asarray(points_local, dtype=np.float32)
    if pts.ndim != 2 or pts.shape[1] != 3 or len(pts) == 0:
        return {
            "d_left": None, "d_right": None, "d_max": None,
            "yaw_left": None, "yaw_right": None, "yaw_max": None,
        }

    max_d = max(0.6, 2.8 * float(nav_radius))

    d_right = _find_first_no_projection_param(
        lambda d: _count_visible_fg_projection_points(
            points_local=pts, intrinsics=intrinsics,
            image_width=W, image_height=H,
            position_local=np.array([float(d), 0.0, 0.0], dtype=np.float32),
            yaw_deg=0.0,
        ),
        hi=max_d, visible_count_threshold=visible_count_threshold,
    )
    d_left = _find_first_no_projection_param(
        lambda d: _count_visible_fg_projection_points(
            points_local=pts, intrinsics=intrinsics,
            image_width=W, image_height=H,
            position_local=np.array([-float(d), 0.0, 0.0], dtype=np.float32),
            yaw_deg=0.0,
        ),
        hi=max_d, visible_count_threshold=visible_count_threshold,
    )

    yaw_right = _find_first_no_projection_param(
        lambda y: _count_visible_fg_projection_points(
            points_local=pts, intrinsics=intrinsics,
            image_width=W, image_height=H,
            position_local=np.zeros(3, dtype=np.float32),
            yaw_deg=float(y),
        ),
        hi=float(max_yaw), visible_count_threshold=visible_count_threshold,
    )
    yaw_left = _find_first_no_projection_param(
        lambda y: _count_visible_fg_projection_points(
            points_local=pts, intrinsics=intrinsics,
            image_width=W, image_height=H,
            position_local=np.zeros(3, dtype=np.float32),
            yaw_deg=-float(y),
        ),
        hi=float(max_yaw), visible_count_threshold=visible_count_threshold,
    )

    d_candidates = [float(v) for v in (d_left, d_right) if v is not None and v > 1e-5]
    yaw_candidates = [float(v) for v in (yaw_left, yaw_right) if v is not None and v > 1e-5]
    d_max = max(d_candidates) if d_candidates else None
    yaw_max_mag = max(yaw_candidates) if yaw_candidates else None

    return {
        "d_left": float(d_left) if d_left is not None else None,
        "d_right": float(d_right) if d_right is not None else None,
        "d_max": float(d_max) if d_max is not None else None,
        "yaw_left": float(yaw_left) if yaw_left is not None else None,
        "yaw_right": float(yaw_right) if yaw_right is not None else None,
        "yaw_max": float(yaw_max_mag) if yaw_max_mag is not None else None,
    }


# ---------------------------------------------------------------------------
# Round plan & interpolation
# ---------------------------------------------------------------------------

def _build_round_plan(
    combo: ComboDef,
    location_pool: Dict[str, List[float]],
    location_pose_pool: Dict[str, Dict],
    event_slots: Dict[str, Dict],
) -> Dict[str, Dict]:
    """Build round plan from combo definition."""
    actions = combo.actions
    targets = combo.target_sequence
    if len(actions) != len(targets):
        raise ValueError(
            f"Combo {combo.combo_id}: actions ({len(actions)}) and "
            f"targets ({len(targets)}) mismatch"
        )
    plan: Dict[str, Dict] = {}
    for i in range(combo.num_rounds):
        loc_to = targets[i]
        loc_from = "S" if i == 0 else targets[i - 1]
        event = actions[i].get("event", "")
        action = actions[i]["action"]

        if event and event in event_slots:
            look_at = event_slots[event]["position"]
        elif loc_to in event_slots:
            look_at = event_slots[loc_to]["position"]
        else:
            look_at = [0.0, 0.0, 0.0]

        plan[str(i)] = {
            "action": action,
            "event": event,
            "location_from": loc_from,
            "location_to": loc_to,
            "camera_start": location_pool.get(loc_from, [0.0, 0.0, 0.0]),
            "camera_end": location_pool.get(loc_to, [0.0, 0.0, 0.0]),
            "pose_start_c2w": location_pose_pool.get(loc_from, {}).get(
                "c2w", np.eye(4).tolist()
            ),
            "pose_end_c2w": location_pose_pool.get(loc_to, {}).get(
                "c2w", np.eye(4).tolist()
            ),
            "look_at": look_at,
        }
    return plan


def _interp_rotation(R0: np.ndarray, R1: np.ndarray, t: float) -> np.ndarray:
    R = (1.0 - t) * R0 + t * R1
    u, _, vt = np.linalg.svd(R)
    return (u @ vt).astype(np.float32)


def _interpolate_pose_sequence(
    round_plan: Dict[str, Dict],
    location_pose_pool: Dict[str, Dict],
    frames_per_round: int,
    first_c2w: np.ndarray,
    motion_primitive: str = "default",
    nav_radius: float = 1.0,
    seed: int = 42,
    calibration_points_local: Optional[np.ndarray] = None,
    calibration_intrinsics: Optional[np.ndarray] = None,
    calibration_image_width: Optional[int] = None,
    calibration_image_height: Optional[int] = None,
    exit_visible_ratio: float = 0.0,
) -> List[Dict]:
    """Interpolate per-frame poses and transform local → world.

    Supports two motion primitives:
      - case1_right / case1_left: Pure X translation (90% fg exit), back-and-forth
      - case2_right / case2_left: Triangular A→B + yaw at B → B→C + yaw at C
    """
    if frames_per_round < 2:
        frames_per_round = 2
    keys = sorted(round_plan.keys(), key=lambda x: int(x))

    # --- Case 1: 纯左右平移,去回去回 (90%像素出屏幕) ---
    if motion_primitive.startswith("case1_"):
        if len(keys) != 4:
            raise ValueError(f"case1 motion primitive expects 4 rounds, got {len(keys)}")

        sign = -1.0 if motion_primitive == "case1_left" else 1.0
        base_d = float(0.8 * nav_radius)
        exit_d = base_d  # fallback

        calib_pts = calibration_points_local
        calib_K = calibration_intrinsics
        calib_W = calibration_image_width
        calib_H = calibration_image_height

        if (
            calib_pts is not None and len(calib_pts) > 0
            and calib_K is not None and np.asarray(calib_K).shape == (3, 3)
            and calib_W is not None and calib_H is not None
        ):
            W_cal = max(1, int(calib_W))
            H_cal = max(1, int(calib_H))
            visible_threshold = _compute_exit_visible_threshold(calib_pts, 0.1)
            full_exit = _find_first_no_projection_param(
                lambda a: _count_visible_fg_projection_points(
                    points_local=np.asarray(calib_pts, dtype=np.float32),
                    intrinsics=np.asarray(calib_K, dtype=np.float32),
                    image_width=W_cal,
                    image_height=H_cal,
                    position_local=np.array(
                        [sign * base_d * float(a), 0.0, 0.0], dtype=np.float32,
                    ),
                    yaw_deg=0.0,
                ),
                hi=4.0,
                n_steps=640,
                visible_count_threshold=visible_threshold,
            )
            if full_exit is not None and full_exit > 1e-5:
                exit_d = base_d * float(full_exit)

        trans_dist = exit_d

        frames: List[Dict] = []
        frame_idx = 0
        for ri, rk in enumerate(keys):
            r = round_plan[rk]
            for si in range(frames_per_round):
                t = float(si) / max(1, frames_per_round - 1)
                if ri in (0, 2):
                    x = sign * trans_dist * t
                elif ri in (1, 3):
                    x = sign * trans_dist * (1.0 - t)
                else:
                    x = 0.0
                pos = np.array([x, 0.0, 0.0], dtype=np.float32)
                local = _yaw_c2w_local(0.0, position=pos)
                world = _local_to_world(local, first_c2w)
                frames.append({
                    "frame_idx": int(frame_idx),
                    "round_idx": int(rk),
                    "interp_t": float(t),
                    "location_from": r["location_from"],
                    "location_to": r["location_to"],
                    "action": r["action"],
                    "event": r["event"],
                    "c2w": world.astype(float).tolist(),
                })
                frame_idx += 1

        return frames

    # --- Case 2: Triangular layout  A -> B -> (yaw at B) -> C -> (yaw at C)
    if motion_primitive.startswith("case2_"):
        base_d = float(0.8 * nav_radius)
        base_Z = base_d / math.sqrt(3.0)
        center_pt = np.array([0.0, 0.0, 1.0], dtype=np.float32)
        if motion_primitive == "case2_right":
            sign = 1.0
        else:
            sign = -1.0

        pos_A = np.zeros(3, dtype=np.float32)
        dir_AB = np.array([sign * base_d, 0.0, -base_Z], dtype=np.float32)
        pos_B = dir_AB.copy()
        dir_BC_unit = np.array([-sign, 0.0, 0.0], dtype=np.float32)

        def _yaw_to_center(position_local: np.ndarray) -> float:
            rel = center_pt - np.asarray(position_local, dtype=np.float32)
            rel_z = float(rel[2])
            if abs(rel_z) < 1e-4:
                rel_z = 1e-4 if rel_z >= 0 else -1e-4
            yaw = math.degrees(math.atan2(float(rel[0]), rel_z))
            return float(np.clip(yaw, -85.0, 85.0))

        yaw_B = _yaw_to_center(pos_B)
        pos_C = np.array([0.0, 0.0, -base_Z], dtype=np.float32)
        yaw_C = _yaw_to_center(pos_C)

        calib_points = calibration_points_local
        if (
            calib_points is not None
            and len(calib_points) > 0
            and calibration_intrinsics is not None
            and np.asarray(calibration_intrinsics).shape == (3, 3)
            and calibration_image_width is not None
            and calibration_image_height is not None
        ):
            W_cal = max(1, int(calibration_image_width))
            H_cal = max(1, int(calibration_image_height))
            visible_threshold = _compute_exit_visible_threshold(
                calib_points, exit_visible_ratio,
            )
            target_exit_amp = 0.75
            _calib_pts = np.asarray(calib_points, dtype=np.float32)
            _calib_K = np.asarray(calibration_intrinsics, dtype=np.float32)

            # Step 1: Calibrate R0 (A -> B, yaw=0)
            r0_exit_scale = _find_first_no_projection_param(
                lambda a: _count_visible_fg_projection_points(
                    points_local=_calib_pts,
                    intrinsics=_calib_K,
                    image_width=W_cal,
                    image_height=H_cal,
                    position_local=(float(a) * dir_AB).astype(np.float32),
                    yaw_deg=0.0,
                ),
                hi=2.0,
                n_steps=640,
                visible_count_threshold=visible_threshold,
            )
            if r0_exit_scale is not None and r0_exit_scale > 1e-5:
                scale_AB = float(r0_exit_scale) / target_exit_amp
            else:
                scale_AB = 1.0

            pos_B = (scale_AB * dir_AB).astype(np.float32)

            # Step 2: Compute yaw_B
            center_pt = np.median(_calib_pts, axis=0).astype(np.float32)
            yaw_B = _yaw_to_center(pos_B)

            # Step 3: Calibrate R2 (B -> C, yaw=yaw_B)
            r2_exit_scale = _find_first_no_projection_param(
                lambda a: _count_visible_fg_projection_points(
                    points_local=_calib_pts,
                    intrinsics=_calib_K,
                    image_width=W_cal,
                    image_height=H_cal,
                    position_local=(pos_B + float(a) * base_d * dir_BC_unit).astype(np.float32),
                    yaw_deg=yaw_B,
                ),
                hi=2.0,
                n_steps=640,
                visible_count_threshold=visible_threshold,
            )
            if r2_exit_scale is not None and r2_exit_scale > 1e-5:
                scale_BC = float(r2_exit_scale) / target_exit_amp
            else:
                scale_BC = scale_AB

            dist_BC = base_d * scale_BC
            pos_C = (pos_B + dist_BC * dir_BC_unit).astype(np.float32)

            # Step 4: Compute yaw_C
            yaw_C = _yaw_to_center(pos_C)

        if len(keys) != 4:
            raise ValueError(
                f"case2 motion primitive expects 4 rounds, got {len(keys)}"
            )

        frames: List[Dict] = []
        frame_idx = 0
        for ri, rk in enumerate(keys):
            r = round_plan[rk]
            if ri == 0:
                pos_start = pos_A
                pos_end = pos_B
                yaw_start = 0.0
                yaw_end = 0.0
            elif ri == 1:
                pos_start = pos_B
                pos_end = pos_B
                yaw_start = 0.0
                yaw_end = yaw_B
            elif ri == 2:
                pos_start = pos_B
                pos_end = pos_C
                yaw_start = yaw_B
                yaw_end = yaw_B
            else:
                pos_start = pos_C
                pos_end = pos_C
                yaw_start = yaw_B
                yaw_end = yaw_C
            for si in range(frames_per_round):
                t = float(si) / max(1, frames_per_round - 1)
                pos = (1.0 - t) * pos_start + t * pos_end
                yaw = (1.0 - t) * yaw_start + t * yaw_end
                local = _yaw_c2w_local(yaw, position=pos)
                world = _local_to_world(local, first_c2w)
                frames.append({
                    "frame_idx": int(frame_idx),
                    "round_idx": int(rk),
                    "interp_t": float(t),
                    "location_from": r["location_from"],
                    "location_to": r["location_to"],
                    "action": r["action"],
                    "event": r["event"],
                    "c2w": world.astype(float).tolist(),
                })
                frame_idx += 1
        return frames

    # --- Default: waypoint lerp + slerp ---
    frames: List[Dict] = []
    frame_idx = 0
    for rk in keys:
        r = round_plan[rk]
        c0 = np.asarray(
            location_pose_pool[r["location_from"]]["c2w"], dtype=np.float32,
        )
        c1 = np.asarray(
            location_pose_pool[r["location_to"]]["c2w"], dtype=np.float32,
        )
        for s in range(frames_per_round):
            t = float(s) / float(frames_per_round)
            p = (1.0 - t) * c0[:3, 3] + t * c1[:3, 3]
            R = _interp_rotation(c0[:3, :3], c1[:3, :3], t)
            local = np.eye(4, dtype=np.float32)
            local[:3, :3] = R
            local[:3, 3] = p
            world = _local_to_world(local, first_c2w)
            frames.append({
                "frame_idx": int(frame_idx),
                "round_idx": int(rk),
                "interp_t": float(t),
                "location_from": r["location_from"],
                "location_to": r["location_to"],
                "action": r["action"],
                "event": r["event"],
                "c2w": world.astype(float).tolist(),
            })
            frame_idx += 1
    last = round_plan[keys[-1]]
    c_end = np.asarray(
        location_pose_pool[last["location_to"]]["c2w"], dtype=np.float32,
    )
    world_end = _local_to_world(c_end, first_c2w)
    frames.append({
        "frame_idx": int(frame_idx),
        "round_idx": int(keys[-1]),
        "interp_t": 1.0,
        "location_from": last["location_to"],
        "location_to": last["location_to"],
        "action": "terminal",
        "event": last["event"],
        "c2w": world_end.astype(float).tolist(),
    })
    return frames


# ---------------------------------------------------------------------------
# Iter input (text prompts per round)
# ---------------------------------------------------------------------------

def _build_iter_input(
    case_type: str,
    round_plan: Dict[str, Dict],
    event_slots: Dict[str, Dict],
) -> Dict[str, Dict[str, str]]:
    out: Dict[str, Dict[str, str]] = {}
    keys = sorted(round_plan.keys(), key=lambda x: int(x))
    for k in keys:
        r = round_plan[k]
        action = r["action"]
        event_id = r["event"]
        scene_text = "A consistent indoor scene with smooth camera motion."
        fg_text = ""
        if event_id and event_id in event_slots:
            entity = event_slots[event_id]["entity"]
            if action == "spawn":
                fg_text = f"{entity} starts an event naturally at its fixed location."
            elif action == "revisit":
                fg_text = f"{entity} continues naturally at the same location."
            else:
                fg_text = f"{entity} remains in its local area."
        out[str(k)] = {"scene_text": scene_text, "fg_text": fg_text}
    return out


# ---------------------------------------------------------------------------
# Main plan generator
# ---------------------------------------------------------------------------

def _save_geometry_npz(
    plan: Dict,
    meta_path: str,
    out_dir: Path,
) -> Optional[Path]:
    """Save geometry.npz compatible with infer_spatia.py."""
    if not meta_path or not Path(meta_path).exists():
        return None
    data = np.load(meta_path)
    for key in ("depth_proc", "intrinsics_proc", "processed_size"):
        if key not in data:
            print(f"  [geometry.npz] Skipped: '{key}' not in {meta_path}")
            return None

    depth_proc = data["depth_proc"]
    intrinsics_proc = data["intrinsics_proc"]
    processed_size = data["processed_size"]
    target_h = int(data["target_h"])
    target_w = int(data["target_w"])

    traj = plan["trajectory_frames"]
    total_frames = len(traj)
    poses_c2w = np.array([f["c2w"] for f in traj], dtype=np.float32)

    from liveworld.geometry_utils import scale_intrinsics
    depth_target = cv2.resize(
        depth_proc, (target_w, target_h), interpolation=cv2.INTER_NEAREST,
    )
    intrinsics_target = scale_intrinsics(
        intrinsics_proc,
        (int(processed_size[0]), int(processed_size[1])),
        (target_h, target_w),
    )

    save_dict = {
        "depths": np.stack([depth_proc] * total_frames),
        "poses_c2w": poses_c2w,
        "intrinsics": np.stack([intrinsics_proc] * total_frames),
        "processed_size": processed_size,
        "original_size": np.array([target_h, target_w]),
        "depths_target": depth_target[None],
        "intrinsics_target": intrinsics_target[None],
        "target_size": np.array([target_h, target_w]),
    }
    geom_path = out_dir / "geometry.npz"
    np.savez_compressed(geom_path, **save_dict)
    return geom_path


def generate_plan_for_combo(
    combo: ComboDef,
    args: argparse.Namespace,
    image_rgb: np.ndarray,
    scene_features: SceneFeatures,
    det: ObjectDetection,
    det_union_mask: np.ndarray,
    scene_meta: Optional[Dict],
    first_c2w: np.ndarray,
    scene_scale: SceneScale,
) -> Dict:
    """Generate a single plan for one combo variant."""
    R = scene_scale.nav_radius * combo.layout_scale
    Re = scene_scale.event_radius * combo.layout_scale

    event_points = {eid: [0.0, 0.0, 0.0] for eid in combo.event_ids}
    nav_points = _circle_points_local(R, count=6)

    if det_union_mask is None:
        raise ValueError("det_union_mask is required (mask-only foreground calibration)")
    calibration_points_local = _estimate_event_points_local(scene_meta, det_union_mask)
    calibration_center_local = (
        np.median(calibration_points_local, axis=0).astype(np.float32)
        if calibration_points_local is not None and len(calibration_points_local) > 0
        else None
    )
    calibration_intrinsics = (
        np.asarray(scene_meta.get("intrinsics"), dtype=np.float32)
        if scene_meta is not None and scene_meta.get("intrinsics") is not None
        else None
    )
    calibration_image_width = (
        int(scene_meta.get("target_w"))
        if scene_meta is not None and scene_meta.get("target_w") is not None
        else None
    )
    calibration_image_height = (
        int(scene_meta.get("target_h"))
        if scene_meta is not None and scene_meta.get("target_h") is not None
        else None
    )

    event_points_used = {
        eid: event_points[eid]
        for eid in combo.event_ids
        if eid in event_points
    }

    event_slots = _build_event_slots(combo, event_points_used, det.entities)
    location_pool = _build_location_pool(nav_radius=R, event_slots=event_slots)

    # Add motion-primitive-specific locations
    if combo.motion_primitive.startswith("case1_"):
        d = float(1.6 * R)
        sign = -1.0 if combo.motion_primitive == "case1_left" else 1.0
        location_pool["A"] = [0.0, 0.0, 0.0]
        location_pool["B"] = [float(sign * d), 0.0, 0.0]
    elif combo.motion_primitive.startswith("case2_"):
        d = 1.6 * R
        Z = d / np.sqrt(3.0)
        location_pool["A"] = [0.0, 0.0, 0.0]
        if combo.motion_primitive == "case2_right":
            location_pool["B"] = [float(d), 0.0, float(-Z)]
        else:
            location_pool["B"] = [float(-d), 0.0, float(-Z)]
        location_pool["C"] = [0.0, 0.0, float(-Z)]

    location_pose_pool = _build_location_pose_pool(
        location_pool=location_pool, event_slots=event_slots,
    )
    round_plan = _build_round_plan(
        combo=combo,
        location_pool=location_pool,
        location_pose_pool=location_pose_pool,
        event_slots=event_slots,
    )
    fpr = combo.frames_per_round if combo.frames_per_round is not None else args.frames_per_round
    trajectory_frames = _interpolate_pose_sequence(
        round_plan=round_plan,
        location_pose_pool=location_pose_pool,
        frames_per_round=fpr,
        first_c2w=first_c2w,
        motion_primitive=combo.motion_primitive,
        nav_radius=R,
        seed=args.seed,
        calibration_points_local=calibration_points_local,
        calibration_intrinsics=calibration_intrinsics,
        calibration_image_width=calibration_image_width,
        calibration_image_height=calibration_image_height,
        exit_visible_ratio=float(getattr(args, "exit_visible_ratio", 0.0)),
    )
    iter_input = _build_iter_input(combo.case_type, round_plan, event_slots)

    # Convert event slot positions local → world
    event_slots_world = {}
    for eid, info in event_slots.items():
        p_local = np.array(info["position"] + [1.0], dtype=np.float32)
        p_world = (first_c2w @ p_local)[:3]
        event_slots_world[eid] = {
            **info,
            "position": [float(p_world[0]), float(p_world[1]), float(p_world[2])],
            "position_local": info["position"],
        }

    # Convert location pool local → world
    location_pool_world = {}
    for loc, pos in location_pool.items():
        p_local = np.array(pos + [1.0], dtype=np.float32)
        p_world = (first_c2w @ p_local)[:3]
        location_pool_world[loc] = [
            float(p_world[0]), float(p_world[1]), float(p_world[2]),
        ]

    sample_id = (
        args.sample_id
        or f"{Path(args.image_path).stem}_{combo.combo_id}_seed{args.seed}"
    )

    exit_visible_ratio = float(getattr(args, "exit_visible_ratio", 0.0))
    exit_visible_threshold = _compute_exit_visible_threshold(
        calibration_points_local,
        exit_visible_ratio,
    )
    if exit_visible_ratio <= 0.0:
        exit_criterion = "visible_fg_projection_count == 0"
    else:
        exit_criterion = (
            f"visible_fg_projection_count <= {exit_visible_threshold} "
            f"(ratio <= {exit_visible_ratio:.4f})"
        )

    output = {
        "sample_id": sample_id,
        "image_path": args.image_path,
        "scene_meta_path": getattr(args, "scene_meta_path", ""),
        "geometry_path": getattr(args, "geometry_path", ""),
        "combo_id": combo.combo_id,
        "case_type": combo.case_type,
        "motion_primitive": combo.motion_primitive,
        "num_rounds": combo.num_rounds,
        "num_events": combo.num_events,
        "first_frame_has_event": combo.first_frame_has_event,
        "first_c2w": first_c2w.astype(float).tolist(),
        "object_detection": asdict(det),
        "scene_features": asdict(scene_features),
        "scene_scale": asdict(scene_scale),
        "distance_normalization": {
            "mode": str(args.distance_mode),
            "target_shift_ratio": float(args.target_shift_ratio),
            "screen_depth_percentile": float(args.screen_depth_percentile),
            "distance_blend_alpha": float(args.distance_blend_alpha),
        },
        "view_calibration": {
            "enabled": bool(calibration_points_local is not None and calibration_intrinsics is not None),
            "event_center_local": (
                [float(x) for x in calibration_center_local.tolist()]
                if calibration_center_local is not None else None
            ),
            "calibration_points_source": "foreground_event_points",
            "calibration_points_count": (
                int(len(calibration_points_local))
                if calibration_points_local is not None
                else 0
            ),
            "exit_visible_ratio": float(exit_visible_ratio),
            "exit_visible_count_threshold": int(exit_visible_threshold),
            "all_foreground_points_exit_required": bool(exit_visible_ratio <= 0.0),
            "projection_exit_criterion": exit_criterion,
            "image_width": int(calibration_image_width) if calibration_image_width is not None else None,
            "image_height": int(calibration_image_height) if calibration_image_height is not None else None,
        },
        "event_slots": event_slots_world,
        "location_pool": location_pool_world,
        "round_target_sequence": combo.target_sequence,
        "nav_points": {f"N{i}": p for i, p in enumerate(nav_points)},
        "round_plan": round_plan,
        "frames_per_round": int(fpr),
        "fps": int(combo.fps),
        "total_frames": int(len(trajectory_frames)),
        "trajectory_frames": trajectory_frames,
        "iter_input": iter_input,
        "camera_control": {
            "yaw_rate_limit_deg_per_frame": float(args.yaw_rate_limit_deg_per_frame),
            "pitch_limit_deg": [-15.0, 15.0],
            "alpha_event": float(args.alpha_event),
            "alpha_non_event": float(args.alpha_non_event),
        },
        "quality_gate": {
            "min_in_frame_ratio": float(args.min_in_frame_ratio),
            "min_event_separation_deg": float(args.min_event_separation_deg),
        },
    }

    out_root = Path(args.output_dir) / sample_id
    out_root.mkdir(parents=True, exist_ok=True)
    with (out_root / "plan.json").open("w", encoding="utf-8") as f:
        json.dump(output, f, ensure_ascii=False, indent=2)

    meta_path = getattr(args, "scene_meta_path", "")
    geom_path = _save_geometry_npz(output, meta_path, out_root)
    if geom_path is not None:
        print(f"  [event_bench] geometry.npz saved: {geom_path}")

    return output


def _load_scene_detect_prompt(system_config_path: str) -> str:
    """Load scene_detect_prompt from system_config.yaml."""
    with open(system_config_path, "r", encoding="utf-8") as f:
        cfg = yaml.safe_load(f)
    return cfg["event"]["detection"]["scene_detect_prompt"]


def generate_all_combos(args: argparse.Namespace) -> List[Dict]:
    """Generate plans for all combos of the specified case_type."""
    scene_detect_prompt = _load_scene_detect_prompt(args.system_config_path)
    image_rgb = _load_image_rgb(args.image_path)
    scene_features = extract_scene_features(image_rgb)
    scene_meta = _load_scene_meta(getattr(args, "scene_meta_path", ""))
    detect_image_path = _prepare_detection_image_for_scene(args.image_path, scene_meta)
    det, det_union_mask = detect_event_object(
        image_path=detect_image_path,
        qwen_model_path=args.qwen_model_path,
        sam3_model_path=args.sam3_model_path,
        scene_detect_prompt=scene_detect_prompt,
    )
    first_c2w = (
        scene_meta["c2w"] if scene_meta is not None
        else np.eye(4, dtype=np.float32)
    )
    scene_scale = estimate_scene_scale(
        det=det,
        scene_features=scene_features,
        image_path=args.image_path,
        geometry_path=getattr(args, "geometry_path", ""),
        case_type=args.case_type,
        llm_motion_scaling=args.llm_motion_scaling,
        qwen_model_path=args.qwen_model_path,
        scene_meta=scene_meta,
        distance_mode=args.distance_mode,
        target_shift_ratio=args.target_shift_ratio,
        screen_depth_percentile=args.screen_depth_percentile,
        distance_blend_alpha=args.distance_blend_alpha,
    )

    combos = get_combos_for_case(
        args.case_type,
        all_variants=getattr(args, "all_variants", False),
    )
    plans = []
    for combo in combos:
        plan = generate_plan_for_combo(
            combo=combo,
            args=args,
            image_rgb=image_rgb,
            scene_features=scene_features,
            det=det,
            det_union_mask=det_union_mask,
            scene_meta=scene_meta,
            first_c2w=first_c2w,
            scene_scale=scene_scale,
        )
        plans.append(plan)
        print(f"  [event_bench] {combo.combo_id}: {plan['sample_id']}")
    return plans


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

def build_argparser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Generate event-centric eval benchmark plans (case1 + case2)",
    )
    parser.add_argument("--image-path", required=True, help="First-frame image path")
    parser.add_argument(
        "--scene-meta-path", default="",
        help="Scene meta.npz from build_scene_pointcloud_da3.py or Stream3R",
    )
    parser.add_argument("--geometry-path", default="", help="Optional geometry.npz path")
    parser.add_argument(
        "--case-type", required=True, choices=CASE_CHOICES,
        help="Benchmark case type (all combos for that case are generated)",
    )
    parser.add_argument(
        "--all-variants", action="store_true",
        help="Include optional (non-core) variants",
    )
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--sample-id", default="", help="Custom sample id (overrides auto naming)")
    parser.add_argument("--output-dir", default="outputs/event_bench")

    parser.add_argument("--qwen-model-path", default="/home/zhangzhilu/anaconda3/pretrained_models/Qwen3-VL-8B-Instruct")
    parser.add_argument("--sam3-model-path", default="/home/zhangzhilu/anaconda3/pretrained_models/sam3/sam3.pt")
    parser.add_argument(
        "--system-config-path",
        default="configs/event_centric_infer/system_config.yaml",
        help="Path to system_config.yaml (for scene_detect_prompt).",
    )

    parser.add_argument("--llm-motion-scaling", action="store_true",
                        help="Use QwenVL to adjust motion scale")
    parser.add_argument(
        "--distance-mode", default="screen_uniform",
        choices=["screen_uniform"],
        help="Trajectory distance scaling mode (only screen_uniform supported).",
    )
    parser.add_argument("--target-shift-ratio", type=float, default=0.18)
    parser.add_argument("--screen-depth-percentile", type=float, default=45.0)
    parser.add_argument("--distance-blend-alpha", type=float, default=0.7)
    parser.add_argument(
        "--exit-visible-ratio", type=float, default=0.0,
        help="Treat foreground as out-of-frame when visible ratio <= this value (0 = strict).",
    )
    parser.add_argument("--frames-per-round", type=int, default=33)

    parser.add_argument("--yaw-rate-limit-deg-per-frame", type=float, default=4.0)
    parser.add_argument("--alpha-event", type=float, default=0.8)
    parser.add_argument("--alpha-non-event", type=float, default=0.2)
    parser.add_argument("--min-in-frame-ratio", type=float, default=0.8)
    parser.add_argument("--min-event-separation-deg", type=float, default=60.0)
    return parser


def main() -> None:
    parser = build_argparser()
    args = parser.parse_args()
    combos = get_combos_for_case(
        args.case_type,
        all_variants=getattr(args, "all_variants", False),
    )
    print(
        f"[event_bench] Generating {len(combos)} combo(s) for {args.case_type}: "
        f"{[c.combo_id for c in combos]}"
    )
    plans = generate_all_combos(args)
    print(f"[event_bench] Done. Generated {len(plans)} plan(s) under {args.output_dir}")


if __name__ == "__main__":
    main()