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

This is a case-specific script for episode 13 with that photo's parameters hard-coded: the 17 pier pixel columns LEFT/RIGHT, the ridge points ridge,
the candidate center lat0/lon0 and the line name are all example parameters from one real case. Kept only as a reproduction record; not guaranteed to run on another photo.

Pixel column of each pier in the photo → ray bearing → intersect with the OSM bridge line → spacing between adjacent piers along the line should be constant (32 m box girders).
Grid-search camera position, heading, and focal length over the candidate area; score = spacing dispersion + |log(mean/32)|. Independent of the skyline fit."""
import json, math, sys
import numpy as np
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "skills/geo-sleuth/scripts"))
import terrain

LEFT = [39, 133, 219, 296, 369]
RIGHT = [745, 788, 829, 869, 907, 944, 981, 1016, 1050, 1083, 1116, 1148]
PIERS = np.array(LEFT + RIGHT, float)
CX = 640.0
lat0, lon0 = 23.736, 113.121   # example parameters from one real case: candidate center given by the previous refine step
kx = 111320 * math.cos(math.radians(lat0)); ky = 110540

g = json.load(open("qy_rail.geojson"))
line = None
for f in g["features"]:
    if f["properties"].get("name") == "广清城际线":
        line = np.array(f["geometry"]["coordinates"]); break
P = np.c_[(line[:, 0] - lon0) * kx, (line[:, 1] - lat0) * ky]   # local metric coordinates (x east, y north)
seg_a, seg_b = P[:-1], P[1:]
seg_len = np.hypot(*(seg_b - seg_a).T)
chain0 = np.r_[0, np.cumsum(seg_len)][:-1]

def hits(cx, cy, az):
    """Nearest intersection of the ray with the polyline: returns (distance, chainage along the line)."""
    d = np.array([math.sin(math.radians(az)), math.cos(math.radians(az))])
    e = seg_b - seg_a
    den = d[0] * e[:, 1] - d[1] * e[:, 0]
    w = seg_a - np.array([cx, cy])
    with np.errstate(divide="ignore", invalid="ignore"):
        t = (w[:, 0] * e[:, 1] - w[:, 1] * e[:, 0]) / den      # ray parameter
        u = (w[:, 0] * d[1] - w[:, 1] * d[0]) / den             # segment parameter
    ok = (t > 100) & (u >= 0) & (u <= 1)
    if not ok.any():
        return None
    i = np.argmin(np.where(ok, t, np.inf))
    return t[i], chain0[i] + u[i] * seg_len[i]

res = []
HS = np.arange(55, 115.1, 0.25)
e = seg_b - seg_a
nL = len(LEFT)
dem = terrain.DEM((lat0, lon0), 18000, 13, Path(".geo-cache/dem"), None)
ridge = {760: 826, 780: 816, 800: 813, 820: 811, 840: 810, 860: 804, 880: 794, 900: 787, 920: 783, 940: 771, 960: 765,
         980: 757, 1000: 755, 1020: 747, 1040: 741, 1060: 740, 1080: 738, 1100: 737, 1120: 738, 1140: 736, 1160: 735,
         1180: 734, 1200: 725, 1220: 728, 1240: 725, 1260: 724}
RX = np.array(list(ridge.keys()), float); RY = np.array(list(ridge.values()), float)
FLX = np.arange(0, 281, 20, dtype=float)
AZ = np.arange(0, 360, 0.1)
NS = 400
DIST = 100 * (16000 / 100) ** (np.arange(NS) / (NS - 1))
for yy in np.arange(-1500, 1501, 50):
    for xx in np.arange(-1500, 1501, 50):
        w = seg_a - np.array([xx, yy])
        clat = lat0 + yy / ky; clon = lon0 + xx / kx
        hor = None
        for f in (1200, 1281, 1350, 1430, 1500):
            offs = np.degrees(np.arctan((PIERS - CX) / f))
            az = np.radians(HS[:, None] + offs[None, :])
            dx, dy = np.sin(az)[..., None], np.cos(az)[..., None]
            den = dx * e[:, 1] - dy * e[:, 0]
            with np.errstate(divide="ignore", invalid="ignore"):
                t = (w[:, 0] * e[:, 1] - w[:, 1] * e[:, 0]) / den
                u = (w[:, 0] * dy - w[:, 1] * dx) / den
            ok = (t > 100) & (u >= 0) & (u <= 1)
            tt = np.where(ok, t, np.inf)
            i = np.argmin(tt, axis=2)
            tmin = np.take_along_axis(tt, i[..., None], 2)[..., 0]
            valid = np.all(np.isfinite(tmin), axis=1)
            if not valid.any():
                continue
            uu = np.take_along_axis(u, i[..., None], 2)[..., 0]
            ch = chain0[i] + uu * seg_len[i]
            dl = np.abs(np.diff(ch[:, :nL], axis=1)); dr = np.abs(np.diff(ch[:, nL:], axis=1))
            sp = np.concatenate([dl, dr], axis=1)
            m = sp.mean(axis=1); cv = sp.std(axis=1) / np.maximum(m, 1e-6)
            dch = np.diff(ch, axis=1)
            mono = np.all(dch > 0, axis=1) | np.all(dch < 0, axis=1)
            pscore = cv + np.abs(np.log(np.maximum(m, 1e-3) / 32)) + (~mono) * 1.0
            pscore[~valid] = np.inf
            k = int(np.argmin(pscore))
            if not np.isfinite(pscore[k]) or pscore[k] > 0.08:
                continue
            H = float(HS[k])
            if hor is None:
                g0 = float(dem.sample(np.array([clat]), np.array([clon]))[0])
                la, lo = terrain._dest_np(clat, clon, AZ, DIST)
                hh = dem.sample(la, lo)
                drop = DIST ** 2 / (2 * 6371008.8) * 0.87
                hor = np.degrees(np.arctan2(hh - drop[None, :] - g0 - 1.6, DIST[None, :])).max(axis=1)
            r_off = np.degrees(np.arctan((RX - CX) / f)); r_el = np.degrees(np.arctan((935 - RY) / f))
            fl_off = np.degrees(np.arctan((FLX - CX) / f))
            mr = np.interp((H + r_off) % 360, AZ, hor, period=360)
            mf = np.interp((H + fl_off) % 360, AZ, hor, period=360)
            diff = mr - r_el; cc = float(np.clip(np.median(diff), -0.8, 0.8))
            rms = float(np.sqrt(np.mean((diff - cc) ** 2)))
            fpen = float(np.mean(np.clip(mf - cc - 1.0, 0, None)))
            tot = rms + 1.5 * fpen + 2 * float(pscore[k])
            res.append((tot, rms, float(pscore[k]), float(m[k]), xx, yy, f, H, cc, float(tmin[k, 0]), float(tmin[k, -1])))
res.sort()
out = []
for r in res[:25]:
    lat = lat0 + r[5] / ky; lon = lon0 + r[4] / kx
    print(f"tot {r[0]:.3f} sky_rms {r[1]:.3f} pier {r[2]:.3f} span {r[3]:.1f}  cam {lat:.5f},{lon:.5f} f {r[6]} H {r[7]} cc {r[8]:.2f} dL {r[9]:.0f} dR {r[10]:.0f}")
    out.append({"tot": r[0], "rms": r[1], "pier": r[2], "cam": [round(lat, 5), round(lon, 5)], "f": r[6], "H": r[7], "cc": r[8]})
json.dump(out, open("joint.json", "w"))

# ===== file: examples/rail-skyline-session/rail_mtn_scan.py =====
# /// script
# requires-python = ">=3.10"
# dependencies = ["pillow", "numpy"]
# ///
"""Co-occurrence scan: railway viaduct × steep mountain nearby.

This is a case-specific script for episode 13; thresholds are hard-coded from estimates for that photo (mountain elevation angle, flat-horizon length, nearby relief).
Kept only as a reproduction record; not guaranteed to run on another photo. The input geojson comes from a railway-bridge query via osm.py geom.

For each bridge in rail_bridges.geojson, take a point every STEP meters along it and compute with Terrarium DEM (z10):
- whether the ground at the point is plain (small elevation relief within 1.2 km)
- horizon elevation angle every 5° for bearings 0–355° (1.5–9 km)
- whether there is a "continuous ≥30° flat horizon (<1°)" right next to "a mountain at elevation angle ≥7°"
Output candidate points and their features, sorted by mountain elevation angle and steepness.
"""
import json, math, sys
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "skills/geo-sleuth/scripts"))
import terrain  # noqa

Z = 10
STEP = 400.0
CACHE = Path(".geo-cache/dem")
CACHE.mkdir(parents=True, exist_ok=True)
R = 6371008.8


def hav(a, b):
    la1, lo1, la2, lo2 = map(math.radians, (a[0], a[1], b[0], b[1]))
    d = math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2
    return 2 * R * math.asin(math.sqrt(d))


gj = json.load(open(sys.argv[1]))
pts = []
for f in gj["features"]:
    g = f["geometry"]
    if g["type"] != "LineString" or f.get("properties", {}).get("electrified") == "no":
        continue
    c = [(y, x) for x, y in g["coordinates"]]
    tags = f.get("properties", {})
    acc = 0.0
    last = None
    for i in range(1, len(c)):
        d = hav(c[i - 1], c[i])
        n = int((acc + d) // STEP)
        for k in range(n):
            t = (STEP * (k + 1) - acc) / d if d else 0
            pts.append((c[i - 1][0] + (c[i][0] - c[i - 1][0]) * t, c[i - 1][1] + (c[i][1] - c[i - 1][1]) * t, tags))
        acc = (acc + d) % STEP
    if not pts or len(c) >= 2 and hav(c[0], c[-1]) < STEP:
        pts.append((c[len(c) // 2][0], c[len(c) // 2][1], tags))
print("samples", len(pts), file=sys.stderr)

# tile cache
tiles = {}
def tile_of(lat, lon):
    n = 2 ** Z
    x = (lon + 180) / 360 * n
    y = (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n
    return x, y

need = set()
for lat, lon, _ in pts:
    x, y = tile_of(lat, lon)
    r = 9500 / (40075016.7 * math.cos(math.radians(lat)) / 2 ** Z)
    for tx in range(int(x - r), int(x + r) + 1):
        for ty in range(int(y - r), int(y + r) + 1):
            need.add((tx, ty))
print("tiles", len(need), file=sys.stderr)
with ThreadPoolExecutor(24) as ex:
    for (tx, ty), arr in zip(need, ex.map(lambda t: terrain._fetch(Z, t[0], t[1], CACHE, None), need)):
        tiles[(tx, ty)] = arr


TX0 = min(t[0] for t in need); TY0 = min(t[1] for t in need)
TX1 = max(t[0] for t in need); TY1 = max(t[1] for t in need)
MOS = np.zeros(((TY1 - TY0 + 1) * 256, (TX1 - TX0 + 1) * 256), dtype=np.int16)
for (tx, ty), arr in tiles.items():
    MOS[(ty - TY0) * 256:(ty - TY0 + 1) * 256, (tx - TX0) * 256:(tx - TX0 + 1) * 256] = np.clip(arr, -500, 9000).astype(np.int16)
tiles.clear()


def elev(lat, lon):
    n = 256 * 2 ** Z
    x = ((lon + 180) / 360 * n - TX0 * 256).astype(int)
    y = ((1 - np.arcsinh(np.tan(np.radians(lat))) / np.pi) / 2 * n - TY0 * 256).astype(int)
    x = np.clip(x, 0, MOS.shape[1] - 1); y = np.clip(y, 0, MOS.shape[0] - 1)
    return MOS[y, x].astype(np.float32)


AZ = np.arange(0, 360, 5.0)
DIST = np.array([1500, 2000, 2500, 3000, 3500, 4000, 5000, 6000, 7000, 8000, 9000], dtype=float)
NEAR = np.array([0, 300, 600, 900, 1200], dtype=float)

res = []
for idx, (lat, lon, tags) in enumerate(pts):
    la, lo = terrain._dest_np(lat, lon, AZ, DIST)
    h = elev(la, lo)
    ln, lon_n = terrain._dest_np(lat, lon, AZ, NEAR)
    hn = elev(ln, lon_n)
    h0 = float(np.median(hn))
    if hn.max() - hn.min() > 40:     # not flat nearby
        continue
    ang = np.degrees(np.arctan2(h - h0 - 1.5, DIST[None, :]))
    hor = ang.max(axis=1)
    rel = (h - h0).max(axis=1)
    mt = hor >= 6.0
    low = hor < 1.2
    if not mt.any() or low.sum() < 6:
        continue
    # find a continuous flat-horizon run right next to the mountain
    best = 0
    for i in range(72):
        if not mt[i]:
            continue
        for sgn in (-1, 1):
            j = (i + sgn) % 72
            # allow a 1-cell transition
            k = 0
            run = 0
            while k < 20:
                jj = (i + sgn * (k + 1)) % 72
                if low[jj]:
                    run += 1
                elif run == 0 and k < 2:
                    pass
                else:
                    break
                k += 1
            best = max(best, run)
    if best < 6:
        continue
    i = int(np.argmax(hor))
    res.append({"lat": round(lat, 5), "lon": round(lon, 5), "h0": round(h0), "max_ang": round(float(hor[i]), 1),
                "az": float(AZ[i]), "relief": round(float(rel[i])), "flat_run_deg": best * 5,
                "name": tags.get("name", ""), "hs": tags.get("highspeed", ""), "elec": tags.get("electrified", ""),
                "id": tags.get("id", tags.get("@id", ""))})

print("hits", len(res), file=sys.stderr)
json.dump(res, open(sys.argv[2], "w"), ensure_ascii=False, indent=0)

# ===== file: examples/rail-skyline-session/railgeom.py =====
# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy"]
# ///
"""Round 3: filter camera positions by the bridge-line geometry inferred from the pier spacing in the frame.

This is a case-specific script for episode 13; the three bridge-distance windows are hard-coded from estimates for that photo.
Kept only as a reproduction record; not guaranteed to run on another photo.
Inferred from the photo (f≈1281–1435 px, 32 m spans): the bridge line's perpendicular distance from the camera position is about 450–750 m, its nearest point about 30–45° left of frame center,
the distance along the center sight line about 600–800 m, at the right edge about 0.9–1.4 km; the bridge line crosses the frame diagonally from near-left to far-right.
For each stage-2 camera position (with its best heading H), take the bridge sample points within field of view [-27°,27°] and 300–2500 m, and check one by one:
- nearest bridge point on the center sight line (±3°) at 550–900 m
- bridge point at the left edge (-26°±3°) at 350–750 m
- bridge point at the right edge (+22°±4°) at 800–1700 m
"""
import json, math, sys, glob
import numpy as np

gj = json.load(open("rail_bridges.geojson"))
cell = {}
for f in gj["features"]:
    if f["properties"].get("electrified") == "no":
        continue
    c = f["geometry"]["coordinates"]
    for (x1, y1), (x2, y2) in zip(c, c[1:]):
        d = math.hypot((x2 - x1) * 111320 * math.cos(math.radians(y1)), (y2 - y1) * 110540)
        n = max(1, int(d // 50))
        for k in range(n + 1):
            la, lo = y1 + (y2 - y1) * k / n, x1 + (x2 - x1) * k / n
            cell.setdefault((int(la / 0.02), int(lo / 0.02)), []).append((la, lo))

def near(lat, lon):
    i, j = int(lat / 0.02), int(lon / 0.02)
    out = []
    for di in (-2, -1, 0, 1, 2):
        for dj in (-2, -1, 0, 1, 2):
            out += cell.get((i + di, j + dj), [])
    return np.array(out) if out else np.zeros((0, 2))

recs = []
for f in sorted(glob.glob("f2_?.json")):
    recs += json.load(open(f))
out = []
for r in recs:
    if r["rms"] > 0.6 or r["flatpen"] > 0.15:
        continue
    lat, lon = r["cam"]
    br = near(lat, lon)
    if not len(br):
        continue
    by = (br[:, 0] - lat) * 110540
    bx = (br[:, 1] - lon) * 111320 * math.cos(math.radians(lat))
    bd = np.hypot(bx, by)
    baz = np.degrees(np.arctan2(bx, by)) % 360
    best = None
    for dH in np.arange(-6, 6.1, 1.5):
        H = r["H"] + dH
        off = (baz - H + 180) % 360 - 180
        def dmin(lo_, hi_):
            m = (off > lo_) & (off < hi_) & (bd > 150)
            return float(bd[m].min()) if m.any() else None
        c = dmin(-3, 3); L = dmin(-27, -21); Rr = dmin(18, 27)
        if c is None or L is None or Rr is None:
            continue
        pen = 0
        pen += max(0, 550 - c) / 200 + max(0, c - 900) / 200
        pen += max(0, 350 - L) / 200 + max(0, L - 750) / 200
        pen += max(0, 800 - Rr) / 300 + max(0, Rr - 1700) / 300
        if L >= c or c >= Rr:
            pen += 1
        if best is None or pen < best[0]:
            best = (pen, H, c, L, Rr)
    if best is None:
        continue
    out.append({**r, "rail_pen": round(best[0], 2), "H2": best[1], "dC": round(best[2]), "dL": round(best[3]), "dR": round(best[4]),
                "total": round(r["rms"] + r["flatpen"] + 0.3 * best[0], 3)})
out.sort(key=lambda x: x["total"])
sel = []
for x in out:
    if all(abs(x["cam"][0] - y["cam"][0]) > 0.02 or abs(x["cam"][1] - y["cam"][1]) > 0.02 for y in sel):
        sel.append(x)
json.dump(sel, open("f3_sel.json", "w"), ensure_ascii=False)
print(len(out), len(sel))
for i, x in enumerate(sel[:30]):
    print(i, x["name"] or "-", x["cam"], "H", x["H2"], "rms", x["rms"], "railpen", x["rail_pen"], "dL/C/R", x["dL"], x["dC"], x["dR"], "total", x["total"])

# ===== file: examples/rail-skyline-session/refine.py =====
# /// script
# requires-python = ">=3.10"
# dependencies = ["pillow", "numpy"]
# ///
"""Local fine search: given a center, camera positions on a 100 m grid, scored by z13 DEM skyline + bridge-line distance together.

This is a case-specific script for episode 13 with the photo parameters hard-coded (focal length, horizon row, ridge points, expected bridge distances 430/660/1150 m).
Kept only as a reproduction record; not guaranteed to run on another photo.
Usage: refine.py lat,lon radius_m out.json
"""
import json, math, sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "skills/geo-sleuth/scripts"))
import terrain  # noqa

lat0, lon0 = map(float, sys.argv[1].split(","))
RAD = float(sys.argv[2])
Z = 13
F0, HROW, CX = 1281.0, 935.0, 640.0
ridge = {760: 826, 780: 816, 800: 813, 820: 811, 840: 810, 860: 804, 880: 794, 900: 787, 920: 783, 940: 771, 960: 765,
         980: 757, 1000: 755, 1020: 747, 1040: 741, 1060: 740, 1080: 738, 1100: 737, 1120: 738, 1140: 736, 1160: 735,
         1180: 734, 1200: 725, 1220: 728, 1240: 725, 1260: 724}
RX = np.array(list(ridge.keys()), float); RY = np.array(list(ridge.values()), float)
FLX = np.arange(0, 281, 20, dtype=float)
R = 6371008.8
dem = terrain.DEM((lat0, lon0), RAD + 16000, Z, Path(".geo-cache/dem"), None)

gj = json.load(open("rail_bridges.geojson"))
pts = []
for f in gj["features"]:
    c = f["geometry"]["coordinates"]
    if not any(abs(y - lat0) < 0.1 and abs(x - lon0) < 0.1 for x, y in c):
        continue
    for (x1, y1), (x2, y2) in zip(c, c[1:]):
        d = math.hypot((x2 - x1) * 111320 * math.cos(math.radians(y1)), (y2 - y1) * 110540)
        n = max(1, int(d // 25))
        for k in range(n + 1):
            pts.append((y1 + (y2 - y1) * k / n, x1 + (x2 - x1) * k / n))
BR = np.array(pts)

AZ = np.arange(0, 360, 0.25)
NA = len(AZ)
NS = 400
DIST = 100 * (16000 / 100) ** (np.arange(NS) / (NS - 1))
HS = np.arange(0, NA)
out = []
for dy in np.arange(-RAD, RAD + 1, 100):
    for dx in np.arange(-RAD, RAD + 1, 100):
        clat = lat0 + dy / 110540; clon = lon0 + dx / (111320 * math.cos(math.radians(lat0)))
        ring = terrain._dest_np(clat, clon, np.arange(0, 360, 45.0), np.array([0, 100, 200.0]))
        g = dem.sample(ring[0], ring[1])
        if g.max() - g.min() > 6:
            continue
        g0 = float(g[:, 0].mean())
        la, lo = terrain._dest_np(clat, clon, AZ, DIST)
        hh = dem.sample(la, lo)
        drop = DIST ** 2 / (2 * R) * 0.87
        ang = np.degrees(np.arctan2(hh - drop[None, :] - g0 - 1.6, DIST[None, :]))
        hor = ang.max(axis=1)
        by = (BR[:, 0] - clat) * 110540; bx = (BR[:, 1] - clon) * 111320 * math.cos(math.radians(clat))
        bd = np.hypot(bx, by); baz = np.degrees(np.arctan2(bx, by)) % 360
        best = None
        for fs in (1.0, 1.08, 1.16):
            f = F0 * fs
            r_off = np.degrees(np.arctan((RX - CX) / f)); r_el = np.degrees(np.arctan((HROW - RY) / f))
            fl_off = np.degrees(np.arctan((FLX - CX) / f))
            ri = (HS[:, None] + np.round(r_off / 0.25).astype(int)[None, :]) % NA
            fi = (HS[:, None] + np.round(fl_off / 0.25).astype(int)[None, :]) % NA
            diff = hor[ri] - r_el[None, :]
            cc = np.clip(np.median(diff, axis=1), -0.7, 0.7)
            rms = np.sqrt(np.mean((diff - cc[:, None]) ** 2, axis=1))
            pen = np.mean(np.clip(hor[fi] - cc[:, None] - 1.0, 0, None), axis=1)
            s = rms + 1.5 * pen
            for k in np.argsort(s)[:12]:
                H = k * 0.25
                off = (baz - H + 180) % 360 - 180
                def dmin(a, b):
                    m = (off > a) & (off < b) & (bd > 100)
                    return float(bd[m].min()) if m.any() else 99999
                hf = math.degrees(math.atan(640 / f))
                L = dmin(-hf, -hf + 5); C = dmin(-2, 2); Rr = dmin(hf - 8, hf)
                eL, eC, eR = 430 * fs, 660 * fs, 1150 * fs
                rp = abs(math.log(L / eL)) + abs(math.log(C / eC)) + abs(math.log(Rr / eR))
                tot = float(s[k]) + 0.5 * rp
                if best is None or tot < best["total"]:
                    best = {"cam": [round(clat, 5), round(clon, 5)], "g": round(g0, 1), "H": H, "fs": fs, "cc": round(float(cc[k]), 2),
                            "rms": round(float(rms[k]), 3), "flatpen": round(float(pen[k]), 3), "dL": round(L), "dC": round(C), "dR": round(Rr),
                            "railpen": round(rp, 3), "total": round(tot, 3)}
        if best:
            out.append(best)
out.sort(key=lambda x: x["total"])
json.dump(out, open(sys.argv[3], "w"), ensure_ascii=False)
for x in out[:15]:
    print(x)

# ===== file: examples/rail-skyline-session/skyfit2.py =====
# /// script
# requires-python = ">=3.10"
# dependencies = ["pillow", "numpy"]
# ///
"""Round 2: camera-position grid + three constraints scored together.

This is a case-specific script for episode 13 with the photo parameters hard-coded: focal length F0, horizon row HROW, the 26 ridge pixel points ridge,
and the flat-horizon column range FLX were all measured from that photo. Kept only as a reproduction record; not guaranteed to run on another photo.
A ground at the camera position is flat (relief < 8 m within 300 m)
B bridge in the left part of the frame [-27°,-10°] (250–1000 m), bridge in the right part [3°,27°] (400–2000 m)
C ridgeline RMS (heading, horizon offset, and focal-length scale searched together)
D skyline < 1° in the left part [-27°,-12°]
"""
import json, math, sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "skills/geo-sleuth/scripts"))
import terrain  # noqa

Z = 11
CACHE = Path(".geo-cache/dem")
F0, HROW, CX = 1281.0, 935.0, 640.0
ridge = {760: 826, 780: 816, 800: 813, 820: 811, 840: 810, 860: 804, 880: 794, 900: 787, 920: 783, 940: 771, 960: 765,
         980: 757, 1000: 755, 1020: 747, 1040: 741, 1060: 740, 1080: 738, 1100: 737, 1120: 738, 1140: 736, 1160: 735,
         1180: 734, 1200: 725, 1220: 728, 1240: 725, 1260: 724}
RX = np.array(list(ridge.keys()), float); RY = np.array(list(ridge.values()), float)
FLX = np.arange(0, 281, 20, dtype=float)
R = 6371008.8

hits = json.load(open(sys.argv[1]))
a0, a1 = (int(v) for v in sys.argv[3].split(":"))

# bridge sample points (100 m)
gj = json.load(open("rail_bridges.geojson"))
cell = {}
def add(lat, lon):
    cell.setdefault((int(lat / 0.02), int(lon / 0.02)), []).append((lat, lon))
for f in gj["features"]:
    if f["properties"].get("electrified") == "no":
        continue
    c = f["geometry"]["coordinates"]
    for (x1, y1), (x2, y2) in zip(c, c[1:]):
        d = math.hypot((x2 - x1) * 111320 * math.cos(math.radians(y1)), (y2 - y1) * 110540)
        n = max(1, int(d // 100))
        for k in range(n + 1):
            add(y1 + (y2 - y1) * k / n, x1 + (x2 - x1) * k / n)

def bridges_near(lat, lon):
    i, j = int(lat / 0.02), int(lon / 0.02)
    out = []
    for di in (-1, 0, 1):
        for dj in (-1, 0, 1):
            out += cell.get((i + di, j + dj), [])
    return np.array(out) if out else np.zeros((0, 2))

AZ = np.arange(0, 360, 0.5)
NS = 260
DIST = 150 * (15000 / 150) ** (np.arange(NS) / (NS - 1))
HS = np.arange(0, 720)  # headings in 0.5° steps

def fit(hor):
    best = None
    for fs in (0.9, 1.0, 1.12):
        f = F0 * fs
        r_off = np.degrees(np.arctan((RX - CX) / f)); r_el = np.degrees(np.arctan((HROW - RY) / f))
        fl_off = np.degrees(np.arctan((FLX - CX) / f))
        ri = (HS[:, None] + np.round(r_off / 0.5).astype(int)[None, :]) % 720
        fi = (HS[:, None] + np.round(fl_off / 0.5).astype(int)[None, :]) % 720
        diff = hor[ri] - r_el[None, :]
        cc = np.clip(np.median(diff, axis=1), -0.7, 0.7)
        rms = np.sqrt(np.mean((diff - cc[:, None]) ** 2, axis=1))
        pen = np.mean(np.clip(hor[fi] - cc[:, None] - 1.0, 0, None), axis=1)
        s = rms + 1.5 * pen
        k = int(np.argmin(s))
        if best is None or s[k] < best[0]:
            best = (float(s[k]), float(rms[k]), float(pen[k]), k * 0.5, fs, float(cc[k]))
    return best

out = []
done_cams = set()
for hi, h in list(enumerate(hits))[a0:a1]:
    lat, lon = h["lat"], h["lon"]
    try:
        dem = terrain.DEM((lat, lon), 17500, Z, CACHE, None)
    except SystemExit:
        continue
    br = bridges_near(lat, lon)
    # camera-position grid: 2 km radius, 250 m spacing
    for dy in np.arange(-2000, 2001, 250):
        for dx in np.arange(-2000, 2001, 250):
            if dx * dx + dy * dy > 2000 ** 2:
                continue
            clat = lat + dy / 110540; clon = lon + dx / (111320 * math.cos(math.radians(lat)))
            key = (round(clat / 0.00225), round(clon / 0.00245))
            if key in done_cams:
                continue
            done_cams.add(key)
            # A flat ground
            ring = terrain._dest_np(clat, clon, np.arange(0, 360, 45.0), np.array([0, 150, 300.0]))
            g = dem.sample(ring[0], ring[1])
            if g.max() - g.min() > 8:
                continue
            g0 = float(g[:, 0].mean())
            # B bridge distribution (rough bearings first; heading unknown → keep each bridge point's bearing and distance)
            if len(br) == 0:
                continue
            by = (br[:, 0] - clat) * 110540; bx = (br[:, 1] - clon) * 111320 * math.cos(math.radians(clat))
            bd = np.hypot(bx, by); baz = np.degrees(np.arctan2(bx, by)) % 360
            m = (bd > 250) & (bd < 2000)
            if m.sum() < 3:
                continue
            baz, bd = baz[m], bd[m]
            la, lo = terrain._dest_np(clat, clon, AZ, DIST)
            hh = dem.sample(la, lo)
            drop = DIST ** 2 / (2 * R) * 0.87
            ang = np.degrees(np.arctan2(hh - drop[None, :] - g0 - 1.6, DIST[None, :]))
            hor = ang.max(axis=1)
            if hor.max() < 6:
                continue
            best = fit(hor)
            s, rms, pen, H, fs, cc = best
            f = F0 * fs
            hf = math.degrees(math.atan(640 / f))
            off = (baz - H + 180) % 360 - 180
            left = ((off > -hf) & (off < -10) & (bd < 1000)).sum()
            right = ((off > 3) & (off < hf) & (bd > 400)).sum()
            bpen = (0 if left else 0.25) + (0 if right else 0.25)
            out.append({"hit": hi, "name": h["name"], "cam": [round(clat, 5), round(clon, 5)], "g": round(g0),
                        "H": H, "fs": fs, "cc": round(cc, 2), "rms": round(rms, 3), "flatpen": round(pen, 3),
                        "left_br": int(left), "right_br": int(right), "score": round(s + bpen, 3)})
    print(hi, h["name"], len(out), file=sys.stderr, flush=True)
json.dump(out, open(sys.argv[2], "w"), ensure_ascii=False)

# ===== file: skills/geo-sleuth/scripts/_browser.py =====
"""Shared Chrome / Playwright Chromium launch and actionable setup errors."""
from __future__ import annotations

from _net import resolve_proxy


async def launch_browser(playwright, proxy: str | None = None):
    value = resolve_proxy(proxy)
    options = {"headless": True, "timeout": 15000,
               "args": ["--disable-blink-features=AutomationControlled"]}
    if value:
        options["proxy"] = {"server": value.replace("socks5h://", "socks5://")}
    else:
        options["args"].append("--no-proxy-server")
    errors = []
    for channel in ("chrome", None):
        try:
            browser = await playwright.chromium.launch(
                **({"channel": channel} if channel else {}), **options)
            return browser, "Google Chrome" if channel else "Playwright Chromium"
        except Exception as exc:
            errors.append(f"{channel or 'chromium'}: {str(exc).splitlines()[0]}")
    raise RuntimeError(
        "Neither Google Chrome nor Playwright Chromium could start. "
        "Run `uvx playwright install chromium` and retry; on Linux, missing system libraries "
        "may require `uvx playwright install --with-deps chromium`. "
        + " | ".join(errors))

# ===== file: skills/geo-sleuth/scripts/_net.py =====
"""HTTP helpers shared by service clients."""
from __future__ import annotations

import os
import subprocess

PROXY_HELP = "proxy URL or 'direct'"


def resolve_proxy(proxy: str | None = None) -> str | None:
    value = (os.environ.get("GEO_PROXY", "") if proxy is None else proxy).strip()
    return None if value.lower() in ("", "direct") else value


def curl_args(proxy: str | None = None) -> list[str]:
    value = resolve_proxy(proxy)
    # Clear NO_PROXY for an explicit proxy; ignore ambient proxies for direct mode.
    return ["--proxy", value, "--noproxy", ""] if value else ["--noproxy", "*"]


def fetch_bytes(url: str, proxy: str | None = None, timeout: int = 20,
                headers: dict[str, str] | None = None) -> bytes:
    cmd = ["curl", "-q", "-fsSL", "--max-time", str(timeout), *curl_args(proxy)]
    for name, value in (headers or {}).items():
        cmd += ["-H", f"{name}: {value}"]
    result = subprocess.run(cmd + [url], capture_output=True, timeout=timeout + 5)
    if result.returncode:
        raise RuntimeError(f"Request failed (curl exit {result.returncode}); run doctor.py --network to check connectivity.")
    return result.stdout


def model_proxy_env(proxy: str | None = None) -> None:
    """Set the model downloader's process environment before importing its HTTP client."""
    value = resolve_proxy(proxy)
    for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
                "http_proxy", "https_proxy", "all_proxy", "no_proxy"):
        os.environ.pop(key, None)
    if value:
        os.environ.update(HTTP_PROXY=value, HTTPS_PROXY=value, ALL_PROXY=value)
    else:
        os.environ["NO_PROXY"] = "*"

# ===== file: skills/geo-sleuth/scripts/baidu_pano.py =====
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["pillow"]
# ///
"""Baidu panoramas (street view in China): find points, scan an area, render by heading, build comparison sheets.

Uses the public endpoints the Baidu Maps web page itself calls; no key needed.
The endpoints are rate-limited: when scanning an area, keep the step at 15 m or more and concurrency at 32 or less.
Baidu street view in China was mostly captured in 2017–2019; when comparing, look at old buildings, new ones may not be there yet.

Examples:
  baidu_pano.py near 22.6047,114.0523                       # nearest panorama point
  baidu_pano.py info 09005700121709201230455178V            # date, position, all points on this road
  baidu_pano.py scan 22.6050,114.0535 --radius 300 --out panos.json
  baidu_pano.py render 09005700121709201230455178V --heading 47 --out v.jpg
  baidu_pano.py sheet --panos panos.json --toward 22.6072,114.0564 --offset -12 --out s.jpg
  baidu_pano.py sheet --ids ID1,ID2 --heading 45 --out s.jpg
  baidu_pano.py sheet --ids ID1 --headings 0,60,120,180,240,300 --out around.jpg   # look around from a single point
  baidu_pano.py sheet --panos panos.json --road <name>路 --spread 60 --toward 22.6072,114.0564 --out s.jpg  # one road only (路 = road), thinned
  baidu_pano.py sample --bbox 22.52,113.90,22.60,114.10 --n 24 --out cityA.jpg     # street-view sample of a candidate city: compare guardrails, streetlights, bus stops
"""
from __future__ import annotations

import argparse
from _net import fetch_bytes, PROXY_HELP
import io
import json
import math
import os
import re
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont

sys.path.insert(0, str(Path(__file__).parent))
import geo  # noqa: E402

API = "https://mapsv0.bdimg.com/"


def _get(url: str, timeout: int = 20, proxy: str | None = None) -> bytes:
    return fetch_bytes(url, proxy, timeout)


def near_bdmc(x: float, y: float, proxy: str | None = None) -> dict | None:
    try:
        c = json.loads(_get(f"{API}?qt=qsdata&x={x:.0f}&y={y:.0f}", proxy=proxy)).get("content")
    except Exception:
        return None
    if not c:
        return None
    bx, by = c["x"] / 100, c["y"] / 100
    lat, lon = geo.convert(bx, by, "bdmc", "wgs")
    return {"id": c["id"], "bdmc": [bx, by], "wgs": [lat, lon], "road": c.get("RoadName", "")}


def near(lat: float, lon: float, proxy: str | None = None) -> dict | None:
    return near_bdmc(*geo.convert(lat, lon, "wgs", "bdmc"), proxy=proxy)


def info(pid: str, proxy: str | None = None) -> dict:
    c = json.loads(_get(f"{API}?qt=sdata&sid={pid}", proxy=proxy))["content"][0]
    x, y = c["X"] / 100, c["Y"] / 100
    lat, lon = geo.convert(x, y, "bdmc", "wgs")
    roads = []
    for r in c.get("Roads") or []:
        roads.append([{"id": p["PID"], "wgs": list(geo.convert(p["X"] / 100, p["Y"] / 100, "bdmc", "wgs"))}
                      for p in (r.get("Panos") or [])])        # some points (construction access roads, isolated points) have no road-segment info
    return {"id": pid, "date": c.get("Date"), "wgs": [lat, lon], "bdmc": [x, y],
            "move_dir": c.get("MoveDir"), "roads": roads,
            "timeline": [t.get("ID") for t in (c.get("TimeLine") or [])]}


def scan(lat: float, lon: float, radius_m: float, step_m: float, workers: int = 24, proxy: str | None = None) -> dict:
    """Query the nearest panorama point at each point of a square grid; deduplicate and return {id: {...}}."""
    pts = []
    n = int(radius_m // step_m)
    for i in range(-n, n + 1):
        for j in range(-n, n + 1):
            p = geo.dest(geo.dest((lat, lon), 0, i * step_m), 90, j * step_m)
            pts.append(p)
    found: dict = {}
    with ThreadPoolExecutor(workers) as ex:
        for r in ex.map(lambda p: near(*p, proxy=proxy), pts):
            if r:
                found[r["id"]] = r
    return found


def thin(panos: dict, spread_m: float) -> dict:
    """Thin by minimum spacing: of points closer than spread_m, keep only the first."""
    kept: dict = {}
    for k, v in panos.items():
        if all(geo.distance(tuple(v["wgs"]), tuple(u["wgs"])) >= spread_m for u in kept.values()):
            kept[k] = v
    return kept


def sample(bbox: tuple[float, float, float, float], n: int, spread_m: float, seed: int,
           skip: list[str], named_only: bool = True, workers: int = 16, proxy: str | None = None) -> list[dict]:
    """Scatter random points in the area to find panoramas, deduplicate, thin by spacing, take n; the heading is the capture car's direction of travel (along the road)."""
    import random
    rnd = random.Random(seed)
    s, w, nn, e = bbox
    found: dict = {}
    tries = 0
    while len(found) < n and tries < n * 8:
        batch = [(rnd.uniform(s, nn), rnd.uniform(w, e)) for _ in range(n * 2)]
        tries += len(batch)
        with ThreadPoolExecutor(workers) as ex:
            for r in ex.map(lambda p: near(*p, proxy=proxy), batch):
                if not r or r["id"] in found or any(k in (r.get("road") or "") for k in skip):
                    continue
                if named_only and not r.get("road"):        # points without a road name are mostly internal roads of residential compounds and campuses, with no municipal fixtures in view
                    continue
                if not (s <= r["wgs"][0] <= nn and w <= r["wgs"][1] <= e):
                    continue
                if all(geo.distance(tuple(r["wgs"]), tuple(u["wgs"])) >= spread_m for u in found.values()):
                    found[r["id"]] = r
                if len(found) >= n:
                    break
    items = []
    with ThreadPoolExecutor(8) as ex:
        infos = list(ex.map(lambda pid: info(pid, proxy=proxy), list(found)[:n]))
    for inf in infos:
        v = found[inf["id"]]
        items.append({"id": inf["id"], "heading": (inf.get("move_dir") or 0) % 360, "pitch": 0, "fov": 60,
                      "date": inf.get("date"), "wgs": v["wgs"], "road": v.get("road", ""),
                      "label": f"{(v.get('road') or '')[:10]} {str(inf.get('date') or '')[:6]}"})
    return items


def render(pid: str, heading: float, pitch: float = 10, fov: float = 80,
           w: int = 1024, h: int = 768, cache: Path | None = None, proxy: str | None = None) -> Image.Image:
    """Render a perspective view at a compass heading. heading 0 = north, positive pitch = looking up, fov is the vertical field of view. Max width 1024."""
    w = min(w, 1024)
    key = f"{pid}_{heading:.0f}_{pitch:.0f}_{fov:.0f}_{w}x{h}.jpg"
    if cache:
        cache.mkdir(parents=True, exist_ok=True)
        if (cache / key).exists():
            return Image.open(cache / key)
    url = (f"{API}?qt=pr3d&fovy={fov:.0f}&quality=80&panoid={pid}&heading={heading:.1f}"
           f"&pitch={pitch:.1f}&width={w}&height={h}")
    try:
        data = _get(url, 40, proxy)
    except Exception:
        return Image.new("RGB", (w, h), "gray")
    if cache:
        (cache / key).write_bytes(data)
    return Image.open(io.BytesIO(data))


# CJK-capable fonts, tried in order; GEO_FONT can point at any other font file.
_FONT_PATHS = (
    "C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/msyhbd.ttc",
    "C:/Windows/Fonts/simhei.ttf", "C:/Windows/Fonts/simsun.ttc",
    "/System/Library/Fonts/STHeiti Medium.ttc", "/System/Library/Fonts/Hiragino Sans GB.ttc",
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
)


def _font(size: int):
    for p in (os.environ.get("GEO_FONT", "").strip(), *_FONT_PATHS):
        if not p:
            continue
        try:
            return ImageFont.truetype(p, size)
        except Exception:
            continue
    return ImageFont.load_default()


def sheet(items: list[dict], out: Path, cols: int = 3, tw: int = 480, th: int = 360,
          cache: Path | None = None, proxy: str | None = None) -> None:
    """items: [{id, heading, pitch?, fov?, label?}] → numbered contact sheet."""
    def one(it):
        return render(it["id"], it["heading"], it.get("pitch", 10), it.get("fov", 80), cache=cache, proxy=proxy)

    with ThreadPoolExecutor(12) as ex:
        ims = list(ex.map(one, items))
    rows = (len(items) + cols - 1) // cols
    S = Image.new("RGB", (cols * tw, rows * th), "black")
    d = ImageDraw.Draw(S)
    f = _font(16)
    for i, (it, im) in enumerate(zip(items, ims)):
        x, y = (i % cols) * tw, (i // cols) * th
        S.paste(im.convert("RGB").resize((tw, th)), (x, y))
        text = it.get("label") or f"{i}: …{it['id'][-9:]} h{it['heading']:.0f}"
        d.rectangle([x, y, x + tw, y + 22], fill="black")
        d.text((x + 4, y + 2), text, fill="yellow", font=f)
    S.save(out, quality=88)



def _neg_coords(argv: list[str]) -> list[str]:
    """argparse treats negative coordinates like -1.45,-48.5 as option names; prefixing a space makes them plain values (float ignores the space). Needed for every puzzle in the southern or western hemisphere."""
    return [" " + a if re.match(r"^-\d[\d.]*(,-?[\d.]+)+$", a) else a for a in argv]


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--proxy", help=PROXY_HELP)
    ap.add_argument("--cache", type=Path, default=Path(".geo-cache/pano"))
    sub = ap.add_subparsers(dest="cmd", required=True)

    n = sub.add_parser("near")
    n.add_argument("latlon")

    i = sub.add_parser("info")
    i.add_argument("id")

    s = sub.add_parser("scan")
    s.add_argument("center")
    s.add_argument("--radius", type=float, default=250)
    s.add_argument("--step", type=float, default=20)
    s.add_argument("--out", type=Path, required=True)

    r = sub.add_parser("render")
    r.add_argument("id")
    r.add_argument("--heading", type=float, required=True)
    r.add_argument("--pitch", type=float, default=10)
    r.add_argument("--fov", type=float, default=80)
    r.add_argument("--out", type=Path, required=True)

    sh = sub.add_parser("sheet")
    g = sh.add_mutually_exclusive_group(required=True)
    g.add_argument("--ids", help="comma-separated panoids")
    g.add_argument("--panos", type=Path, help="JSON output of scan")
    g.add_argument("--spec", type=Path, help="JSON list [{id, heading, pitch, fov, label}]")
    sh.add_argument("--heading", type=float, help="one heading for all")
    sh.add_argument("--headings", help="render these headings at every point, comma-separated, e.g. 0,60,120,180,240,300 (look around from a single point)")
    sh.add_argument("--toward", help="lat,lon: each point faces this target")
    sh.add_argument("--offset", type=float, default=0, help="angle added on top of the toward bearing")
    sh.add_argument("--pitch", type=float, default=10)
    sh.add_argument("--fov", type=float, default=80)
    sh.add_argument("--within", help="lat,lon,radius in meters: only points inside this circle")
    sh.add_argument("--road", help="only points whose road name contains these characters (the road field in scan output); comma-separated for several")
    sh.add_argument("--spread", type=float, help="thinning: minimum meters between neighboring points")
    sh.add_argument("--limit", type=int, default=12, help="max cells per contact sheet; extra cells go to more pages automatically")
    sh.add_argument("--out", type=Path, required=True)

    sp = sub.add_parser("sample", help="random street-view sample contact sheet of a candidate city/area: compare the styles of municipal fixtures such as guardrails, streetlights, bus stops, curbs")
    sp.add_argument("--bbox", required=True, help="south,west,north,east (urban area)")
    sp.add_argument("--n", type=int, default=24, help="how many points to sample")
    sp.add_argument("--spread", type=float, default=300, help="minimum spacing between two points, m")
    sp.add_argument("--seed", type=int, default=1)
    sp.add_argument("--skip", default="隧道,高速,高架,匝道,立交", help="skip points whose road name contains these characters, comma-separated (default: tunnel, expressway, elevated road, ramp, interchange)")
    sp.add_argument("--heading-offset", type=float, default=0, help="extra degrees to turn from the along-road direction (90 = look at the roadside)")
    sp.add_argument("--include-unnamed", action="store_true", help="also take points without a road name (internal roads of residential compounds, campuses); skipped by default")
    sp.add_argument("--out", type=Path, required=True)

    for parser in (n, i, s, r, sh, sp):
        parser.add_argument("--proxy", default=argparse.SUPPRESS, help=PROXY_HELP)
    args = ap.parse_args(_neg_coords(sys.argv[1:]))
    if args.cmd == "sample":
        bb = tuple(map(float, args.bbox.split(",")))
        items = sample(bb, args.n, args.spread, args.seed, [k for k in args.skip.split(",") if k],
                       named_only=not args.include_unnamed, proxy=args.proxy)
        for it in items:
            it["heading"] = (it["heading"] + args.heading_offset) % 360
        if not items:
            sys.exit("no panorama points found in the area (area too small, or no Baidu street view here)")
        pages = [items[k:k + 12] for k in range(0, len(items), 12)]
        for pi, page in enumerate(pages):
            out = args.out if pi == 0 else args.out.with_name(f"{args.out.stem}_{pi + 1}{args.out.suffix}")
            sheet(page, out, cache=args.cache, proxy=args.proxy)
            print(out)
        idx = args.out.with_suffix(".index.json")
        idx.write_text(json.dumps(items, ensure_ascii=False, indent=1), encoding="utf-8")
        dates = sorted(str(i.get("date") or "")[:4] for i in items)
        print(f"{len(items)} points, capture years {dates[0]}–{dates[-1]}; index -> {idx}")
        return
    if args.cmd == "near":
        print(json.dumps(near(*map(float, args.latlon.split(",")), proxy=args.proxy), ensure_ascii=False))
    elif args.cmd == "info":
        print(json.dumps(info(args.id, proxy=args.proxy), ensure_ascii=False, indent=1))
    elif args.cmd == "scan":
        lat, lon = map(float, args.center.split(","))
        res = scan(lat, lon, args.radius, args.step, proxy=args.proxy)
        args.out.write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding="utf-8")
        print(f"{len(res)} panos -> {args.out}")
    elif args.cmd == "render":
        render(args.id, args.heading, args.pitch, args.fov, cache=args.cache, proxy=args.proxy).save(args.out)
        print(args.out)
    elif args.cmd == "sheet":
        if args.spec:
            items = json.loads(args.spec.read_text(encoding="utf-8"))
        else:
            if args.ids:
                need_pos = bool(args.within or args.toward)
                panos = {p: (info(p, proxy=args.proxy) if need_pos else None) for p in args.ids.split(",")}
            else:
                panos = json.loads(args.panos.read_text(encoding="utf-8"))
            if args.within:
                wl, wo, wr = map(float, args.within.split(","))
                panos = {k: v for k, v in panos.items() if geo.distance((wl, wo), v["wgs"]) <= wr}
            if args.road:
                keys = [k for k in args.road.split(",") if k]
                panos = {k: v for k, v in panos.items() if any(x in ((v or {}).get("road") or "") for x in keys)}
                print(f"{len(panos)} points after --road filter")
            if args.spread:
                panos = thin(panos, args.spread)
                print(f"{len(panos)} points after --spread thinning")
            target = tuple(map(float, args.toward.split(","))) if args.toward else None
            items = []
            for pid, v in panos.items():
                if args.headings:
                    for hd in (float(x) for x in args.headings.split(",")):
                        items.append({"id": pid, "heading": hd % 360, "pitch": args.pitch, "fov": args.fov})
                    continue
                if target:
                    hd = geo.bearing(tuple(v["wgs"]), target) + args.offset
                elif args.heading is not None:
                    hd = args.heading
                else:
                    ap.error("need --heading, --headings or --toward")
                items.append({"id": pid, "heading": hd % 360, "pitch": args.pitch, "fov": args.fov})
        pages = [items[k:k + args.limit] for k in range(0, len(items), args.limit)] or [[]]
        for pi, page in enumerate(pages):
            # page 1 is written to --out itself, later pages get _2, _3…, to avoid "the file given by --out doesn't exist"
            out = args.out if pi == 0 else args.out.with_name(f"{args.out.stem}_{pi + 1}{args.out.suffix}")
            sheet(page, out, cache=args.cache, proxy=args.proxy)
            print(out)
        if len(pages) > 1:
            print(f"{len(pages)} pages: {args.out.name} plus {args.out.stem}_2 … _{len(pages)}, {args.limit} cells per page")
        if len(pages) > 1 or args.spec is None:
            idx = args.out.with_suffix(".index.json")
            idx.write_text(json.dumps(items, indent=1), encoding="utf-8")
            print(f"index -> {idx}")


if __name__ == "__main__":
    # Chinese-locale Windows writes GBK by default: m², ñ make it crash, and the Chinese the agent reads comes out garbled
    sys.stdout.reconfigure(encoding="utf-8")
    sys.stderr.reconfigure(encoding="utf-8", errors="backslashreplace")
    main()

# ===== file: skills/geo-sleuth/scripts/board.py =====
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""Candidate board: every candidate, clue, piece of evidence and exclusion during geolocation is recorded here; ranking and the next step are computed by the script, not from memory.

Rules are written as code, not left to self-discipline:
- There is no "delete candidate" operation. Exclusion has exactly one entry point, `exclude`, and it must be given a computed file (output of geo.py frame, terrain.py and the like);
  the clue itself must be text that was read or a computed result; an inference can only down-weight (likelihood ratio clamped to 1/3–3).
- Exclusion scope must be ≤ evidence scope: for candidates with extent (district/area/road), exclude must state with --covers which stretch the evidence covers;
  coverage under half is rejected. Looking at one point and excluding the whole road (one point standing in for the whole area) is a mistake that recurred twice.
- Discrete candidates are never averaged to a midpoint: the main answer in report is always first place; the rest go to alternatives.
- Population and fame are not evidence: the prior is uniform by default (optionally by area); there is no by-population option.
- Scan order is by "share ÷ pages": scan small districts first, put large districts last with a page cap.
- When discriminating tests can't separate the candidates, next gives a definite next step instead of stalling.

  init       create board.json
  add        add candidates (country/province/city/district/area/point); --from bulk-imports output of poi.py / gazetteer.py / osm.py geom
  children   use gazetteer.py to add every subdivision of an admin area as a candidate ("list the whole category first")
  clue       record a clue: seen / text read / inferred / computed
  evidence   a clue's likelihood ratio for some candidates (>1 supports, <1 opposes)
  exclude    exclude a candidate (needs a computed file)
  scan-bbox  set a candidate's scan extent (built-up area); pages are counted from it
  urban      fill scan-bbox automatically with gazetteer.py urban
  falsify    write the falsification condition before scanning/confirming
  rank       current ranking (score, share, evidence, pages, share/page)
  next       suggested next step
  check      checklist before the conclusion
  report     generate the candidates/alternatives/excluded/unused-clues fields of result.json
  apply      lookup clues (calling code, driving side, territories; plates, area codes… from region packs) add candidates and evidence automatically (uses clues.py)
  move       put a candidate under another candidate (a point under its road) so its supporting evidence counts there
  country    set the country context: apply restricts region-pack lookups to it, next uses its pack's tips
  log        print the ledger

Examples:
  board.py init --photo photo.jpg
  board.py children <municipality or province name>       # all 38 districts become candidates, uniform prior
  board.py add --from pois.json --level area --parent <city>   # fine-level candidates (same-name campuses, OSM walled compounds) all go on the board; don't hand-pick
  board.py clue "bus yellow on top, green below; green rear stripe curves down" --kind livery --status observed --file bus_zoom.png
  board.py evidence --clue K1 --for <district A>:5 --for <district B>:2 --why "compared bus rears one by one across both districts' bus photos" --file livery_sheet.jpg
  board.py apply --kind plate --value <first two plate characters>
  board.py urban <district A> --within <municipality or province name>
  board.py rank
  board.py next
  board.py falsify <district A> --text "give up if the sports field's long axis isn't north-south"
  board.py exclude <district B> --clue K4 --computed frame.json --why "by the view-angle range X should be in frame and ≥40px; it isn't in the image"
  board.py check
  board.py report --merge result.json
"""
from __future__ import annotations

import argparse
from _net import PROXY_HELP
import json
import math
import os
import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path

import regions

HERE = Path(__file__).parent
# uv run writes its own path into the UV env var: call child scripts with it, so uv is found even when it isn't on PATH (e.g. just installed, terminal not reopened)
UV = os.environ.get("UV") or "uv"
LEVELS = ["country", "admin1", "admin2", "city", "district", "area", "road", "point"]
LEVEL_LABEL = {"country": "country", "admin1": "province/state", "admin2": "prefecture/county", "city": "city",
               "district": "district", "area": "area", "road": "road", "point": "point"}
# Candidates with extent: exclusion scope must be <= evidence scope. Looking at one point on a road/area and excluding the whole of it is a mistake that recurred twice
EXTENDED_LEVELS = {"district", "area", "road"}
COVERS_MIN = 0.5  # --covers must cover at least this fraction of the candidate's extent before the whole candidate can be excluded
STATUS = ["observed", "read", "inferred", "computed"]
# Likelihood ratio caps: inferences can only rank; only text read and computed results can move the score a lot
LR_CAP = {"inferred": 3.0, "observed": 5.0, "read": 50.0, "computed": 50.0}
GLOBAL_KINDS = ("calling-code", "driving-side", "territories")   # clues.py tables in data/, not region packs
CHEAP_OPS = [
    ("plate/area-code/calling-code", "plate, area code or calling code readable → `clues.py lookup` + `board.py apply`"),
    ("terrain", "flat vs hill city in the image → `terrain.py view` or z13 satellite imagery per candidate to check terrain; one call rules out a batch"),
    ("livery", "bus/taxi livery → image search for \"<city> <color> bus\" in the local language; read route signs from the results, compare the rear waistline stripe district by district"),
    ("municipal", "guardrails, street lights, bus stops, curb styles → street view of each candidate's built-up area (`gsv.py sheet --points`, or the street-view script the region pack names), one contact sheet per candidate"),
    ("network", "water/road network template → `tiles.py fetch --zoom 13` per candidate, compare river direction and number of bridges"),
    ("phenology", "vegetation + month → weak evidence only, can't exclude on its own"),
]


def _norm(s: str) -> str:
    return re.sub(r"[\s()()]", "", s or "").rstrip("市省区县自治州自治县自治区特别行政区")


def _clue_kind(kind: str) -> str:
    # Accept the long spelling in new clues and in boards written by older versions.
    return "infra" if kind.strip().lower() in ("infra", "infrastructure") else kind


def _load(p: Path) -> dict:
    if not p.exists():
        sys.exit(f"No {p}: run `board.py init --photo photo.jpg` first")
    return json.loads(p.read_text(encoding="utf-8"))


def _save(p: Path, b: dict) -> None:
    b["updated"] = datetime.now().isoformat(timespec="seconds")
    p.write_text(json.dumps(b, ensure_ascii=False, indent=1), encoding="utf-8")


def _find(b: dict, name: str) -> str:
    if name in b["candidates"]:
        return name
    hits = [k for k in b["candidates"] if _norm(k) == _norm(name)]
    if len(hits) == 1:
        return hits[0]
    if not hits:
        sys.exit(f"No candidate \"{name}\": add it or use children first (existing: {', '.join(list(b['candidates'])[:12])}…)")
    sys.exit(f"\"{name}\" matches several candidates: {hits}; write the full name")


def _log(b: dict, text: str) -> None:
    b.setdefault("log", []).append(f"{datetime.now():%H:%M} {text}")


def _run(cmd: list[str]) -> subprocess.CompletedProcess:
    """Run gazetteer.py, clues.py. Child scripts and this one both use UTF-8: Chinese Windows reads and writes GBK by default, and if the two sides differ you get mojibake or crashes."""
    return subprocess.run(cmd, text=True, encoding="utf-8", errors="replace", capture_output=True,
                          env={**os.environ, "PYTHONUTF8": "1"})


def _bbox_km2(bb: list[float]) -> float:
    s, w, n, e = bb
    return abs(n - s) * 110.574 * abs(e - w) * 111.320 * math.cos(math.radians((s + n) / 2))


def _pages(bb: list[float], zoom: int, cell: int, cols: int) -> int:
    s, w, n, e = bb
    mpp = 156543.03392 * math.cos(math.radians((s + n) / 2)) / 2 ** zoom
    step = cell * mpp * 0.9
    r = max(1, math.ceil((n - s) * 110574 / step))
    c = max(1, math.ceil((e - w) * 111320 * math.cos(math.radians((s + n) / 2)) / step))
    return math.ceil(r * c / (cols * cols))


def _inherited(b: dict, name: str, own_clues: set[str]) -> list[dict]:
    """Support flows up, refutation doesn't: a point that matches supports its road, a point that doesn't match says nothing about the rest of the road.
    Per clue the strongest supporting evidence among descendants, for clues the candidate has no evidence of its own."""
    kids: dict[str, list[str]] = {}
    for n, c in b["candidates"].items():
        if c.get("parent") and c.get("status") != "excluded":
            kids.setdefault(c["parent"], []).append(n)
    seen, todo, best = {name}, list(kids.get(name, [])), {}
    while todo:
        n = todo.pop()
        if n in seen:
            continue
        seen.add(n)
        todo += kids.get(n, [])
        for e in b["evidence"]:
            if e["candidate"] == n and e["lr"] > 1 and e["clue"] not in own_clues and e["lr"] > best.get(e["clue"], {}).get("lr", 1):
                best[e["clue"]] = {**e, "via": n}
    return list(best.values())


def _scores(b: dict, level: str, prior_by: str) -> list[dict]:
    rows = []
    for name, c in b["candidates"].items():
        if c["level"] != level:
            continue
        prior = 1.0
        if prior_by == "area" and c.get("bbox"):
            prior = max(_bbox_km2(c["bbox"]), 1.0)
        logit = math.log(prior) + math.log(max(c.get("prior", 1.0), 1e-9))
        ev = [e for e in b["evidence"] if e["candidate"] == name]
        ev += _inherited(b, name, {e["clue"] for e in ev})
        for e in ev:
            logit += math.log(max(e["lr"], 1e-9))
        rows.append({"name": name, "logit": logit, "n_ev": len(ev),
                     "n_verified": sum(1 for e in ev if b["clues"][e["clue"]]["status"] in ("read", "computed")),
                     "excluded": c.get("status") == "excluded", "c": c, "ev": ev})
    open_rows = [r for r in rows if not r["excluded"]]
    if open_rows:
        m = max(r["logit"] for r in open_rows)
        z = sum(math.exp(r["logit"] - m) for r in open_rows)
        for r in open_rows:
            r["share"] = math.exp(r["logit"] - m) / z
    for r in rows:
        r.setdefault("share", 0.0)
    rows.sort(key=lambda r: (r["excluded"], -r["share"]))
    return rows


def _frontier(b: dict) -> str | None:
    """The finest level that still has ≥2 non-excluded candidates; if none, the finest level that has candidates."""
    for lv in reversed(LEVELS):
        if sum(1 for c in b["candidates"].values() if c["level"] == lv and c.get("status") != "excluded") >= 2:
            return lv
    for lv in reversed(LEVELS):
        if any(c["level"] == lv and c.get("status") != "excluded" for c in b["candidates"].values()):
            return lv
    return None


def _cost_of(c: dict, args) -> tuple[int | None, str]:
    bb = c.get("scan_bbox") or c.get("bbox")
    if not bb:
        return None, "no extent"
    pages = _pages(bb, args.zoom, args.cell, args.cols)
    return pages, ("built-up area" if c.get("scan_bbox") else "whole-district bbox")


# ---------------------------------------------------------------- subcommands

def cmd_init(args, p: Path) -> None:
    if p.exists() and not args.force:
        sys.exit(f"{p} already exists (add --force to overwrite)")
    b = {"case": args.case or Path.cwd().name, "photo": args.photo, "created": datetime.now().isoformat(timespec="seconds"),
         "country": _country_code(args.country) if args.country else None,
         "candidates": {}, "clues": {}, "evidence": [], "falsify": {}, "log": []}
    _save(p, b)
    print(f"Created {p}" + (f" (country {b['country']})" if b["country"] else ""))


def _country_code(text: str) -> str:
    pk = regions.resolve(text)
    if not pk:
        print(f"Note: no region pack for '{text}' (installed: {', '.join(sorted(regions.packs())) or 'none'}); "
              f"lookups that need a pack will answer unsupported, global tools still work.")
        return text.upper()
    return pk["code"]


def cmd_country(args, p: Path) -> None:
    b = _load(p)
    if args.code in ("none", "-", ""):
        b["country"] = None
        _log(b, "country cleared")
        _save(p, b)
        print("Country context cleared: lookups search every region pack.")
        return
    b["country"] = _country_code(args.code)
    _log(b, f"country {b['country']}")
    _save(p, b)
    pk = regions.resolve(b["country"])
    print(f"Country context {b['country']}: `apply` restricts region-pack lookups to it; `next` uses its tips."
          + (f" Card: `regions.py show {b['country'].lower()}`." if pk else ""))


def _bbox_around(lat: float, lon: float, r: float) -> list[float]:
    dy, dx = r / 110574, r / (111320 * math.cos(math.radians(lat)))
    return [round(lat - dy, 6), round(lon - dx, 6), round(lat + dy, 6), round(lon + dx, 6)]


def _coords(g) -> list[tuple[float, float]]:
    """All (lon, lat) in a GeoJSON geometry."""
    if isinstance(g, (list, tuple)) and g and isinstance(g[0], (int, float)):
        return [(float(g[0]), float(g[1]))]
    out = []
    for x in g or []:
        out += _coords(x)
    return out


def _read_from(path: Path, radius: float) -> list[tuple[str, dict]]:
    """--from file → [(name, {bbox, center})]. Accepts four forms:
    poi.py/tiles.py {name: [lat, lon]}; gazetteer.py {name: {bbox, center}};
    GeoJSON (osm.py geom, name taken from properties.name); [{name, lat, lon} or {name, bbox}]. Points get an extent from --radius."""
    d = json.loads(path.read_text(encoding="utf-8"))
    rows: list[tuple[str, dict]] = []

    def one(name: str, v) -> None:
        if isinstance(v, (list, tuple)) and len(v) >= 2 and all(isinstance(x, (int, float)) for x in v[:2]):
            lat, lon = float(v[0]), float(v[1])
            rows.append((name, {"center": [lat, lon], "bbox": _bbox_around(lat, lon, radius)}))
        elif isinstance(v, dict):
            bb = v.get("bbox")
            c = v.get("center") or ([v["lat"], v["lon"]] if "lat" in v and "lon" in v else None)
            if bb:
                rows.append((name, {"center": c or [(bb[0] + bb[2]) / 2, (bb[1] + bb[3]) / 2], "bbox": bb}))
            elif c:
                rows.append((name, {"center": c, "bbox": _bbox_around(float(c[0]), float(c[1]), radius)}))

    if isinstance(d, dict) and d.get("type") == "FeatureCollection":
        for i, f in enumerate(d.get("features", []), 1):
            pr = f.get("properties") or {}
            pts = _coords((f.get("geometry") or {}).get("coordinates"))
            if not pts:
                continue
            lons, lats = [q[0] for q in pts], [q[1] for q in pts]
            name = pr.get("name") or f"{pr.get('@id') or pr.get('id') or f'#{i}'}"
            bb = [min(lats), min(lons), max(lats), max(lons)]
            if len(pts) == 1:
                bb = _bbox_around(lats[0], lons[0], radius)
            rows.append((name, {"center": [round((bb[0] + bb[2]) / 2, 6), round((bb[1] + bb[3]) / 2, 6)],
                                "bbox": [round(v, 6) for v in bb]}))
    elif isinstance(d, dict):
        for name, v in d.items():
            if not str(name).startswith("_"):
                one(str(name), v)
    elif isinstance(d, list):
        for i, v in enumerate(d, 1):
            if isinstance(v, dict):
                one(str(v.get("name") or f"#{i}"), v)
    # Same names (several campuses of one school, several same-name walled areas in OSM) get a sequence number; none are dropped
    seen: dict[str, int] = {}
    out = []
    for name, v in rows:
        seen[name] = seen.get(name, 0) + 1
        out.append((name if seen[name] == 1 else f"{name}#{seen[name]}", v))
    return out


def cmd_add(args, p: Path) -> None:
    b = _load(p)
    if args.level not in LEVELS:
        sys.exit(f"--level must be one of {LEVELS}")
    if not args.names and not args.from_:
        sys.exit("Give candidate names, or --from a file (poi.py --out, gazetteer.py --out, GeoJSON from osm.py geom)")
    if args.from_:
        rows = _read_from(Path(args.from_), args.radius)
        if not rows:
            sys.exit(f"No candidates with coordinates read from {args.from_}")
        n, added = 0, []
        for name, v in rows:
            key = _slot(b, name, args.parent, None, args.level)
            if not key:
                continue
            added.append(key)
            b["candidates"][key] = {"level": args.level, "parent": args.parent, "bbox": v["bbox"], "scan_bbox": None,
                                     "center": v["center"], "prior": args.prior, "status": "open",
                                     "note": args.note or "", "from": str(args.from_)}
            n += 1
        _log(b, f"add --from {args.from_} → +{n} {args.level}")
        _save(p, b)
        hints = [h for k in added for h in [_skip_hint(b, k)] if h]
        if hints:
            print(f"NOTE {hints[0]}" + (f" (and {len(hints) - 1} more)" if len(hints) > 1 else ""))
        print(f"Added {n} {LEVEL_LABEL[args.level]} candidates from {args.from_} ({len(rows)} read; duplicate names skipped). "
              f"Same names under another parent get the parent in the key. All on the board with a uniform prior: record evidence for every one you look at (record --against too when it doesn't match); check lists the ones not looked at.")
    for raw in args.names:
        name = _slot(b, raw, args.parent, None, args.level)
        if not name:
            print(f"Already have {raw}" + (f" under {args.parent}" if args.parent else "") + ", skipping")
            continue
        c = {"level": args.level, "parent": args.parent, "bbox": None, "scan_bbox": None, "prior": args.prior,
             "status": "open", "note": args.note or ""}
        if args.bbox:
            c["bbox"] = [float(v) for v in args.bbox.split(",")]
        b["candidates"][name] = c
        _log(b, f"add {name} ({args.level})")
        hint = _skip_hint(b, name)
        if hint:
            print(f"NOTE {hint}")
    _save(p, b)
    print(f"{len(b['candidates'])} candidates")


def cmd_move(args, p: Path) -> None:
    b = _load(p)
    name = _find(b, args.name)
    parent = _find(b, args.parent)
    if parent == name:
        sys.exit("A candidate can't be its own parent")
    if LEVELS.index(b["candidates"][parent]["level"]) >= LEVELS.index(b["candidates"][name]["level"]):
        sys.exit(f"{parent} ({b['candidates'][parent]['level']}) isn't coarser than {name} ({b['candidates'][name]['level']})")
    old = b["candidates"][name].get("parent")
    b["candidates"][name]["parent"] = parent
    _log(b, f"move {name}: {old} → {parent}")
    _save(p, b)
    print(f"{name} now under {parent} (was {old}); its supporting evidence now counts for {parent} in the {b['candidates'][parent]['level']} ranking")
    hint = _skip_hint(b, name)
    if hint:
        print(f"NOTE {hint}")


def cmd_children(args, p: Path) -> None:
    b = _load(p)
    cmd = [UV, "run", str(HERE / "gazetteer.py"), "children", args.parent, "--out", str(p.parent / ".gz_children.json")]
    if args.level:
        cmd += ["--level", str(args.level)]
    if args.within:
        cmd += ["--within", args.within]
    if args.proxy:
        cmd += ["--proxy", args.proxy]
    r = _run(cmd)
    for line in r.stderr.splitlines():
        if "not treated as the next level" in line or "falling back to the first" in line:
            print(line)
    out = r.stdout.strip(); print(out if len(out) < 1800 else out[:1800].rsplit('\n', 1)[0] + '\n  …')
    if r.returncode != 0:
        sys.exit(f"gazetteer failed: {r.stderr.strip()[-600:]}")
    kids = json.loads((p.parent / ".gz_children.json").read_text(encoding="utf-8"))
    as_level, why = _child_level(b, args, out)
    # Stable ids from a region pack's admin table, so lookups (plates, area codes) land on these same candidates
    pk, local = regions.admin_children(args.parent, b.get("country"))
    by_local = {}
    if pk:
        chain = regions.admin_chain(pk, regions.admin_find(args.parent, pk["code"])[0][1])
        for it in local:
            by_local[_norm(it["name"])] = "/".join([pk["code"], *chain, it["name"]])
    n = 0
    for raw, k in kids.items():
        cid = by_local.get(_norm(raw))
        name = _slot(b, raw, args.parent, cid, as_level)
        if not name:
            continue
        b["candidates"][name] = {"level": as_level, "parent": args.parent, "bbox": k.get("bbox"), "scan_bbox": None,
                                 "prior": 1.0, "status": "open", "note": k.get("note", ""), "osm_id": k.get("osm_id"),
                                 "country": pk["code"] if pk else b.get("country"), "cid": cid}
        n += 1
    _log(b, f"children {args.parent} → +{n} {as_level}")
    _save(p, b)
    print(f"Added {n} candidates (level {as_level}: {why}; uniform prior). Population and fame don't enter the score.")


# Parent's level on the board → level the children are recorded as
NEXT_LEVEL = {"country": "admin1", "admin1": "admin2", "admin2": "district", "city": "district", "district": "area",
              "area": "road", "road": "point"}


def _child_level(b: dict, args, gz_out: str) -> tuple[str, str]:
    """Candidate level for children: use --as-level if given; parent is a country → admin1; parent already on the board → its next level
    (where a province's next level down is directly districts, as with a municipality, record as district); otherwise → district."""
    if args.as_level:
        return args.as_level, "set by --as-level"
    m = re.search(r"admin_level (\d+)\) children admin_level (\d+)", gz_out)
    p_lv, c_lv = (int(m.group(1)), int(m.group(2))) if m else (None, None)
    if p_lv is not None and p_lv <= 2:
        # When jumping straight from a country to a finer level (--level 5/6), don't record as province level
        lv = "admin1" if c_lv is None or c_lv <= 4 else ("admin2" if c_lv == 5 else "district")
        return lv, f"parent is a country, children admin_level {c_lv}"
    hits = [k for k in b["candidates"] if _norm(k) == _norm(args.parent)]
    if len(hits) == 1:
        lv = b["candidates"][hits[0]]["level"]
        nxt = NEXT_LEVEL.get(lv, "district")
        if lv == "admin1" and p_lv is not None and c_lv is not None and c_lv >= p_lv + 2:
            nxt = "district"
        return nxt, f"parent {hits[0]} is {lv} on the candidate board"
    return "district", "default"


def cmd_clue(args, p: Path) -> None:
    b = _load(p)
    kid = f"K{len(b['clues']) + 1}"
    if args.status not in STATUS:
        sys.exit(f"--status must be one of {STATUS}: observed=shape/color seen directly in the image, read=text/numbers read, inferred=inference (building about 8 floors, road going uphill), computed=computed by a script")
    resolves = list(dict.fromkeys(getattr(args, "resolves", None) or []))
    output = args.file or ""
    if resolves:
        if args.status != "computed":
            sys.exit("--resolves requires --status computed: link a result that actually tests the named clues")
        unknown = [k for k in resolves if k not in b["clues"]]
        if unknown:
            sys.exit(f"Unknown clues in --resolves: {', '.join(unknown)}")
        if not output or not Path(output).is_file():
            sys.exit("--resolves requires --file pointing to an existing computed output file")
        output = str(Path(output).resolve())
    kind = _clue_kind(args.kind)
    b["clues"][kid] = {"text": args.text, "kind": kind, "status": args.status, "file": output,
                       "source": args.source or "", "used": False}
    if resolves:
        b["clues"][kid]["resolves"] = resolves
    _log(b, f"clue {kid} [{kind}/{args.status}] {args.text}" + (f"; resolves {', '.join(resolves)}" if resolves else ""))
    _save(p, b)
    cap = LR_CAP[args.status]
    print(f"{kid} recorded. Status {args.status}: likelihood ratio cap {cap:g}" + (", can only rank, can't exclude" if args.status in ("inferred", "observed") else ", usable for exclude (still needs a computed file)"))


def _parse_lr(items: list[str] | None, default: float | None) -> list[tuple[str, float]]:
    out = []
    for it in items or []:
        if ":" in it:
            name, v = it.rsplit(":", 1)
            out.append((name, float(v)))
        elif default is not None:
            out.append((it, default))
        else:
            sys.exit(f"Write it as name:likelihood_ratio, e.g. {it}:5")
    return out


def cmd_evidence(args, p: Path) -> None:
    b = _load(p)
    if args.clue not in b["clues"]:
        sys.exit(f"No clue {args.clue}; run `board.py clue` first")
    cl = b["clues"][args.clue]
    cap = LR_CAP[cl["status"]]
    pairs = _parse_lr(args.for_, 3.0) + [(n, v) for n, v in _parse_lr(args.against, 1 / 3)]
    if not pairs:
        sys.exit("Give at least one --for name:likelihood_ratio or --against name:likelihood_ratio")
    clipped = []
    for name, lr in pairs:
        cname = _find(b, name)
        if lr <= 0:
            sys.exit("A likelihood ratio of 0 means exclusion; use `board.py exclude` (needs a computed file)")
        lr2 = min(max(lr, 1 / cap), cap)
        if abs(lr2 - lr) > 1e-9:
            clipped.append(f"{cname}:{lr:g}→{lr2:g}")
        b["evidence"].append({"id": f"E{len(b['evidence']) + 1}", "clue": args.clue, "candidate": cname, "lr": lr2,
                              "why": args.why or "", "file": args.file or "", "cmd": args.command_ or ""})
    cl["used"] = True
    if args.file and not Path(args.file).exists():
        print(f"Note: {args.file} doesn't exist; evidence files must be real outputs of this session")
    _log(b, f"evidence {args.clue} → {', '.join(f'{n}:{v:g}' for n, v in pairs)}")
    _save(p, b)
    if clipped:
        print(f"Clue {args.clue} is \"{cl['status']}\", likelihood ratio clamped to 1/{cap:g}–{cap:g}: {'; '.join(clipped)}. "
              f"For more weight, first verify the clue as read/computed (read the text, run a script), then record a new clue.")
    print("Recorded." + ("" if args.why else " Suggest adding --why to state the basis."))


def cmd_exclude(args, p: Path) -> None:
    b = _load(p)
    cname = _find(b, args.name)
    if args.clue not in b["clues"]:
        sys.exit(f"No clue {args.clue}")
    cl = b["clues"][args.clue]
    if cl["status"] not in ("read", "computed"):
        sys.exit(f"Clue {args.clue} is \"{cl['status']}\" (inferred/observed): it can't exclude, only `evidence --against {cname}:0.34`. "
                 f"Hard rule 9: exclusion and confirmation use the same standard.")
    if not args.computed or not Path(args.computed).exists():
        sys.exit("Exclusion must attach a computed file (--computed, e.g. geo.py frame output or a terrain.py comparison image), and the file must actually exist")
    c = b["candidates"][cname]
    if c["level"] in EXTENDED_LEVELS:
        if not args.covers:
            sys.exit(
                f"{cname} is a {LEVEL_LABEL[c['level']]}-level candidate (has extent): exclusion needs --covers stating where the evidence actually covers "
                f"('lat,lon' or 'lat,lon:lat,lon'). Hard rule 9: exclusion scope must be ≤ evidence scope — "
                f"looking at one point and excluding the whole thing is one point standing in for the whole area. If you only checked one stretch, use instead: "
                f"board.py evidence --clue {args.clue} --against {cname}:0.34 --file {args.computed}")
        pts = _parse_covers(args.covers)
        if not pts:
            sys.exit("--covers must parse to coordinates: 'lat,lon' (single point) or 'lat,lon:lat,lon' (span)")
        r = _covers_ratio(c, pts)
        if r is not None and r[0] < COVERS_MIN:
            cov_m = _cov_span_m(pts[0], pts[-1]) if len(pts) >= 2 else 0.0
            sys.exit(
                f"--covers covers only about {r[0]:.0%} of {cname} (evidence {cov_m:.0f} m / candidate extent diagonal {r[1]:.0f} m): "
                f"not enough to exclude the whole thing. Add comparison images for the remaining stretches before excluding, or down-weight first: "
                f"board.py evidence --clue {args.clue} --against {cname}:0.34 --file {args.computed}")
    c["status"] = "excluded"
    c["excluded_by"] = {"clue": args.clue, "computed": args.computed, "why": args.why or "",
                        "covers": args.covers or ""}
    cl["used"] = True
    _log(b, f"exclude {cname} by {args.clue} ({args.computed})")
    _save(p, b)
    print(f"Excluded {cname}. Excluded candidates stay in the ledger; check looks back at them.")


def cmd_scan_bbox(args, p: Path) -> None:
    b = _load(p)
    cname = _find(b, args.name)
    b["candidates"][cname]["scan_bbox"] = [float(v) for v in args.bbox.split(",")]
    _log(b, f"scan-bbox {cname} {args.bbox}")
    _save(p, b)
    print("ok")


def cmd_urban(args, p: Path) -> None:
    b = _load(p)
    cname = _find(b, args.name)
    cmd = [UV, "run", str(HERE / "gazetteer.py"), "urban", cname]
    if args.within:
        cmd += ["--within", args.within]
    if args.proxy:
        cmd += ["--proxy", args.proxy]
    r = _run(cmd)
    if r.returncode != 0:
        sys.exit(f"gazetteer urban failed: {r.stderr.strip()[-600:]}")
    d = json.loads(r.stdout[r.stdout.index("{"):])
    if d.get("urban_bbox"):
        b["candidates"][cname]["scan_bbox"] = d["urban_bbox"]
        b["candidates"][cname]["urban_source"] = d.get("source")
        _log(b, f"urban {cname} {d['urban_bbox']} ({d.get('source')})")
        _save(p, b)
        print(f"{cname} built-up area {d['urban_bbox']}, about {d.get('urban_bbox_km2')} km² (source {d.get('source')})"
              + (f"; {d['note']}" if d.get("note") else ""))
    else:
        print(f"{cname}: {d.get('note', 'no built-up area data')}; set it by hand with `board.py scan-bbox`")


def cmd_falsify(args, p: Path) -> None:
    b = _load(p)
    cname = _find(b, args.name)
    b["falsify"].setdefault(cname, []).append(args.text)
    _log(b, f"falsify {cname}: {args.text}")
    _save(p, b)
    print("Falsification condition recorded. If it shows up, give up; don't look for reasons to explain it away.")


def cmd_rank(args, p: Path, quiet: bool = False) -> dict:
    b = _load(p)
    out = {}
    for lv in LEVELS:
        rows = _scores(b, lv, args.prior_by)
        if not rows:
            continue
        out[lv] = rows
        if quiet:
            continue
        print(f"\n[{LEVEL_LABEL[lv]}] {len(rows)} candidates ({sum(1 for r in rows if not r['excluded'])} not excluded)")
        print(f"  {'candidate':<14}{'share':>7}{'evidence':>9}{'verified':>9}{'pages':>6}  {'share/page':>10}  note")
        for r in rows[: args.limit]:
            pages, src = _cost_of(r["c"], args)
            ratio = (r["share"] / pages) if pages else None
            flag = "excluded" if r["excluded"] else ""
            print(f"  {r['name']:<14}{r['share']:>7.1%}{r['n_ev']:>9}{r['n_verified']:>9}{(pages if pages is not None else '?'):>6}"
                  f"  {(f'{ratio:.4f}' if ratio is not None else '?'):>10}  {flag} {src if pages is not None else ''} {r['c'].get('note', '')[:30]}")
        if len(rows) > args.limit:
            print(f"  … {len(rows) - args.limit} more (raise --limit)")
    if not out and not quiet:
        print("No candidates: run `board.py add` or `board.py children` first")
    return out


def _corridor_pending(b: dict) -> list[str]:
    """Infrastructure observations without a computed result explicitly addressing them."""
    infra = [k for k, c in b["clues"].items() if _clue_kind(c["kind"]) == "infra" and c["status"] in ("observed", "read")]
    done = {k for c in b["clues"].values()
            if c["status"] == "computed" and c.get("resolves") and c.get("file") and Path(c["file"]).is_file()
            for k in c.get("resolves", [])}
    return [k for k in infra if k not in done]


def cmd_next(args, p: Path) -> None:
    b = _load(p)
    pend = _corridor_pending(b)
    if pend:
        print(f"→ First: infrastructure clue {', '.join(pend)} has no linked corridor result yet. `osm.py geom '<filter>' --bbox <region> --out lines.geojson` → "
              f"`terrain.py scan --lines lines.geojson` (mountains fill the frame: add `--flat-run 0 --min-low-deg 0`) → `terrain.py fit`; "
              f"two or three kinds of infrastructure: `osm.py near`. Record a result that actually tests the clue with "
              f"`board.py clue '<result>' --kind corridor --status computed --file <output> --resolves <clue-id>` "
              f"(repeat --resolves for each clue tested).")
    lv = _frontier(b)
    if not lv:
        print("No candidates. First do step 2 (lookup clues) or step 4 (coarse location from the environment) and list the candidates in full (board.py children)")
        return
    rows = [r for r in _scores(b, lv, args.prior_by) if not r["excluded"]]
    top = rows[0]
    second = rows[1] if len(rows) > 1 else None
    unused = [k for k, c in b["clues"].items() if not c["used"]]
    print(f"Current frontier: {LEVEL_LABEL[lv]}, {len(rows)} not excluded; first {top['name']} {top['share']:.0%}"
          + (f", second {second['name']} {second['share']:.0%}" if second else ""))
    if unused:
        pending = ", ".join(f"{k}({b['clues'][k]['kind']})" for k in unused)
        print(f"Clues not used yet: {pending} → evidence or apply first")
    separable = (not second) or (top["share"] >= 0.7 and top["share"] / max(second["share"], 1e-9) >= 3)
    if separable and top["n_verified"] == 0 and second:
        print(f"{top['name']} leads but has no verified evidence at all (read/computed); it's built from inferences only: do one cheap verification before scanning.")
    if separable:
        pages, src = _cost_of(top["c"], args)
        print(f"→ Ready to narrow/scan: {top['name']} ({src}, about {pages if pages is not None else '?'} pages).")
        if src == "whole-district bbox":
            print("  First `board.py urban <name>` or `scan-bbox` to shrink the extent to the built-up area; pages drop by an order of magnitude.")
        elif pages is None:
            print(f"  It has no extent yet: `board.py urban {top['name']} --within <parent>` or `board.py scan-bbox {top['name']} --bbox s,w,n,e`, otherwise pages can't be computed.")
        if top["name"] not in b["falsify"]:
            print(f"  Write the falsification condition before scanning: `board.py falsify {top['name']} --text \"…\"`")
        print("  Let the machine rank the scan first: `sat_scan.py grid --bbox <scan_bbox> --preset …`, `osm.py buildings`, `poi.py`; look only at the top 20–30.")
        return
    print("→ Can't separate. Do discriminating tests from cheap to expensive, each on all non-excluded candidates together, not just the leader:")
    kinds_have = {c["kind"] for c in b["clues"].values()}
    pk = _region_of(b, rows)
    tips = (pk or {}).get("tips") or {}
    if pk:
        print(f"  (region pack {pk['code']}: `regions.py show {pk['code'].lower()}` lists its lookups, services and clue index)")
    for kind, tip in [(k, tips.get(k, t)) for k, t in CHEAP_OPS]:
        mark = "(you already have a clue of this kind; record evidence)" if any(k in kinds_have for k in kind.split("/")) else ""
        print(f"  - {kind}: {tip} {mark}")
    print("→ All cheap tests done and still can't separate: don't stop. Scan in \"share ÷ pages\" order, finish the small ones first, set a page cap on the large ones:")
    order = []
    for r in rows:
        pages, src = _cost_of(r["c"], args)
        order.append((r["share"] / pages if pages else 0, r, pages, src))
    order.sort(key=lambda t: -t[0])
    for ratio, r, pages, src in order[:8]:
        print(f"    {r['name']:<14} share {r['share']:.0%}  pages {pages if pages is not None else '?'} ({src})  share/page {ratio:.4f}")
    if any(pages is None for _, _, pages, _ in order):
        print("    Some candidates have no extent: fill it in with `board.py urban` or `scan-bbox`, otherwise they can't be ordered")


def _region_of(b: dict, rows: list[dict]) -> dict | None:
    """The board's country, else the one country all open frontier candidates share."""
    if b.get("country"):
        return regions.resolve(b["country"])
    codes = {r["c"].get("country") for r in rows}
    return regions.resolve(codes.pop()) if len(codes) == 1 and None not in codes else None


def _parse_covers(s: str) -> list[tuple[float, float]]:
    """--covers: 'lat,lon' or 'lat,lon:lat,lon' (the point/span the evidence actually covers). Returns [] if no coordinates parse."""
    pts = []
    for part in str(s).split(":"):
        m = re.findall(r"-?\d+\.\d+|-?\d+", part)
        if len(m) >= 2:
            pts.append((float(m[0]), float(m[1])))
    return pts


def _cov_span_m(a: tuple[float, float], b: tuple[float, float]) -> float:
    kx = 111320.0 * math.cos(math.radians((a[0] + b[0]) / 2))
    return math.hypot((b[1] - a[1]) * kx, (b[0] - a[0]) * 110540.0)


def _covers_ratio(c: dict, pts: list[tuple[float, float]]) -> tuple[float, float] | None:
    """(evidence coverage length / candidate extent diagonal, diagonal in meters). None if the candidate has no bbox (can't compute, only warn)."""
    bb = c.get("bbox") or c.get("scan_bbox")
    if not bb or len(bb) != 4:
        return None
    try:
        sw, ww, nn, ee = (float(v) for v in bb)
    except (TypeError, ValueError):
        return None
    diag = _cov_span_m((sw, ww), (nn, ee))
    if diag <= 1.0:
        return None
    cov = _cov_span_m(pts[0], pts[-1]) if len(pts) >= 2 else 0.0
    return cov / diag, diag


def _unseen(rows: list[dict], lv: str) -> list[str]:
    """Non-excluded candidates at fine levels (area/road/point) without a single piece of evidence. Coarse levels are scanned in share/pages order, where no evidence is normal, so they don't count."""
    if lv not in ("area", "road", "point"):
        return []
    return [r["name"] for r in rows if r["n_ev"] == 0 and not r["excluded"]]


def _center_of(c: dict) -> tuple[float, float] | None:
    if c.get("center"):
        return float(c["center"][0]), float(c["center"][1])
    bb = c.get("bbox")
    return ((bb[0] + bb[2]) / 2, (bb[1] + bb[3]) / 2) if bb else None


def _inside(c: dict, lat: float, lon: float, pad_m: float = 30) -> bool | None:
    """Is (lat, lon) inside the candidate's bbox (padded)? None when the candidate has no bbox."""
    bb = c.get("bbox")
    if not bb:
        return None
    dy, dx = pad_m / 110574, pad_m / (111320 * math.cos(math.radians(lat)))
    return bb[0] - dy <= lat <= bb[2] + dy and bb[1] - dx <= lon <= bb[3] + dx


def _skipped_level(b: dict, name: str) -> tuple[str, list[str], str | None] | None:
    """A candidate that skips a level its siblings use: a point added under a city that also has road candidates.
    Its evidence then never reaches that level's ranking, which goes on ranking the other roads.
    Returns (skipped level, the siblings at that level, the one whose bbox contains it or None)."""
    c = b["candidates"][name]
    li = LEVELS.index(c["level"])
    for lv in reversed(LEVELS[:li]):
        sibs = [n for n, s in b["candidates"].items() if s["level"] == lv and s.get("parent") == c.get("parent")
                and n != c.get("parent") and s.get("status") != "excluded"]
        if not sibs:
            continue
        at = _center_of(c)
        home = next((n for n in sibs if at and _inside(b["candidates"][n], *at)), None)
        return lv, sibs, home
    return None


def _skip_hint(b: dict, name: str) -> str | None:
    gap = _skipped_level(b, name)
    if not gap:
        return None
    lv, sibs, home = gap
    c = b["candidates"][name]
    where = (f"it lies inside {home} → `board.py move '{name}' --parent '{home}'`" if home else
             f"none of them contains it, so that ranking leaves the answer out → `board.py add <its {lv}> --level {lv} --parent '{c.get('parent')}' --bbox s,w,n,e`, "
             f"then `board.py move '{name}' --parent <it>`")
    return (f"{name} ({c['level']}) sits directly under {c.get('parent')}, which also has {len(sibs)} {lv} candidates; "
            f"its evidence never reaches the {lv} ranking: {where}")


def cmd_check(args, p: Path) -> None:
    b = _load(p)
    ok = True
    print("Pre-conclusion check:")
    for name