geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
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
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
//! Multi-source tile generation pipeline.
//!
//! Reads from all 6 data sources (Overture Parquet, OSM PBF,
//! Natural Earth SQLite, land/water shapefiles, India boundary `GeoJSON`),
//! processes features through layer dispatchers, sorts, merges, and
//! writes a single `PMTiles` archive.

use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use crate::tiles_error::{Result, TilesError};
use flate2::Compression;
use flate2::write::GzEncoder;
use geo::{LineString, Polygon};
use rayon::prelude::*;

use crate::config::TilesConfig;
use crate::conflation::BridgeIndex;
use crate::geometry::mercator::{self, TileCoord};
use crate::geometry::snap;
use crate::geometry::stripe_clip;
use crate::geometry::tile_bounds::TileBounds;
use crate::layers;
use crate::layers::Layer;
use crate::layers::boundaries::IndiaMask;
use crate::layers::buildings::{self, ProcessedFeature};
use crate::output::hilbert;
use crate::output::writer::{Compression as PmtCompression, PmtilesWriter, TileType};
use crate::progress;
use crate::sort::chunk::{ChunkSink, RUN_EXTENSION, SortBuffer};
use crate::sort::entry::SortEntry;
use crate::sort::merge::KWayMerge;
use crate::source;
use crate::source::bbox_filter::Bbox;
use crate::source::input::{InputFeature, layer_routing};
use crate::source::natural_earth;
use crate::source::osm;
use crate::source::osmium;
use crate::source::reader;
use crate::source::shapefile_reader;
use crate::tile::feature::{GeomType, PropValue, TileFeature};
use crate::tile::{mvt, sort_key};
use crate::timing::{PhaseTimer, format_count};
use geolith::geometry::guard;

/// Number of complete tiles to batch before parallel encode + gzip.
///
/// Larger batches increase parallelism but buffer more features in memory.
/// 512 tiles × ~100 features × ~200 bytes ≈ 10 MB buffered.
const ENCODE_BATCH_SIZE: usize = 512;

/// A complete tile pending parallel encoding.
struct PendingTile {
    /// Sort key: (zoom, `tile_id`).
    tile_key: (u8, u64),
    /// All features belonging to this tile.
    features: Vec<TileFeature>,
}

/// An encoded + compressed tile ready for sequential writing.
struct EncodedTile {
    /// Hilbert-order `PMTiles` tile ID.
    pmtiles_id: u64,
    /// Gzip-compressed MVT protobuf bytes.
    compressed: Vec<u8>,
}

/// Multi-bridge conflation filter for deduplicating OSM features.
///
/// Wraps one or more [`BridgeIndex`] instances and tracks how many OSM
/// features were skipped (had a GERS match) vs kept. Thread-safe via
/// atomic counters for use across rayon threads.
struct ConflationFilter {
    bridges: Vec<BridgeIndex>,
    skipped: AtomicU64,
    kept: AtomicU64,
}

impl ConflationFilter {
    /// Create a new conflation filter from loaded bridge indices.
    fn new(bridges: Vec<BridgeIndex>) -> Self {
        let total: usize = bridges.iter().map(BridgeIndex::len).sum();
        tracing::info!(
            bridge_files = bridges.len(),
            total_entries = total,
            "conflation filter ready"
        );
        Self {
            bridges,
            skipped: AtomicU64::new(0),
            kept: AtomicU64::new(0),
        }
    }

    /// Check whether an OSM feature should be skipped.
    ///
    /// Returns `true` if any loaded bridge index contains the OSM ID.
    fn should_skip(&self, osm_id: u64) -> bool {
        if self.bridges.iter().any(|b| b.contains(osm_id)) {
            self.skipped.fetch_add(1, Ordering::Relaxed);
            true
        } else {
            self.kept.fetch_add(1, Ordering::Relaxed);
            false
        }
    }

    /// Get the number of OSM features skipped so far.
    fn skipped_count(&self) -> u64 {
        self.skipped.load(Ordering::Relaxed)
    }

    /// Log a summary of deduplication statistics at INFO level.
    fn log_summary(&self) {
        let skipped = self.skipped.load(Ordering::Relaxed);
        let kept = self.kept.load(Ordering::Relaxed);
        let total = skipped + kept;
        tracing::info!(skipped, kept, total, "GERS bridge deduplication summary");
    }
}

/// Execute the full tile pipeline: read, sort, merge and write the
/// protomaps-schema `PMTiles` archive.
pub fn execute(config: &TilesConfig) -> Result<()> {
    run_in_pool(config.threads, || execute_in_pool(config))?
}

/// Run `work` in a rayon pool of `threads` threads (the current pool without
/// a count). The pool belongs to this call: the library never sets the
/// process-wide pool, so every run gets the count it asked for.
fn run_in_pool<T: Send>(threads: Option<usize>, work: impl FnOnce() -> T + Send) -> Result<T> {
    let Some(threads) = threads else {
        return Ok(work());
    };
    let pool = rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build()
        .map_err(|e| TilesError::ThreadPool(e.to_string()))?;
    Ok(pool.install(work))
}

/// The message of a thread's panic payload (`&str` and `String` carry one).
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    payload
        .downcast_ref::<&str>()
        .map(|m| (*m).to_owned())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "no message".to_owned())
}

fn execute_in_pool(config: &TilesConfig) -> Result<()> {
    guard::begin_build(config.max_geometry_failures);
    let bbox = config
        .bbox
        .as_deref()
        .map(Bbox::parse)
        .transpose()
        .map_err(TilesError::InvalidBbox)?;

    // India is always the Survey of India map: a build whose area touches
    // that land (the whole world without --bbox) needs --india-boundary.
    // Decided by geometry before any data is read.
    if config.india_boundary.is_none()
        && geolith::admin::soi_area::touches_soi_land(
            bbox.as_ref()
                .map(|b| [b.min_lon, b.min_lat, b.max_lon, b.max_lat]),
        )
    {
        return Err(TilesError::IndiaBoundaryRequired);
    }

    // Pre-compute per-zoom tile ranges for bbox filtering.
    // This is the single biggest perf optimization for regional builds:
    // tiles outside the bbox are skipped with 4 integer comparisons.
    let tile_bounds = bbox
        .as_ref()
        .map(|b| TileBounds::from_bbox(b, config.max_zoom));
    if tile_bounds.is_some() {
        tracing::info!("TileBounds: pre-computed tile ranges for bbox filtering");
    }

    let max_zoom = config.max_zoom;
    let chunk_bytes = config.effective_chunk_bytes();
    let tmp_dir = config
        .tmpdir
        .clone()
        .unwrap_or_else(|| std::env::temp_dir().join("geolith-sort"));

    // Cold-path collector: chunk paths are gathered once per source file,
    // NOT on the hot per-entry path. Lock contention is negligible.
    let all_chunk_paths: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());

    if !config.reuse.resume && config.disk_check {
        crate::disk::preflight(config, &tmp_dir)?;
    }

    let mut overture_read = true;
    if !config.reuse.resume {
        let phase1_timer = PhaseTimer::start("phase1");
        tracing::info!(
            "Phase 1: Read + Process (chunk_size={}MB, threads={:?})",
            chunk_bytes / (1024 * 1024),
            config.threads,
        );
        // Shared atomic counter for unique chunk file names across all threads.
        // Each thread gets its own ChunkSink with zero lock contention on writes.
        let chunk_counter = Arc::new(AtomicU32::new(0));
        std::fs::create_dir_all(&tmp_dir).map_err(|source| TilesError::CreateChunkDir {
            path: tmp_dir.clone(),
            source,
        })?;

        // Cold-path collector: chunk paths are gathered once per source file,
        // NOT on the hot per-entry path. Lock contention is negligible.

        let features_processed = AtomicU64::new(0);
        let tiles_emitted = AtomicU64::new(0);

        // Per-layer diagnostic counters (features dispatched + tile features generated)
        let layer_features: Vec<AtomicU64> = (0..11).map(|_| AtomicU64::new(0)).collect();
        let layer_tiles: Vec<AtomicU64> = (0..11).map(|_| AtomicU64::new(0)).collect();

        tracing::info!(
            "Source selection: buildings={}, roads={}, \
         divisions={}, landcover={}, bathymetry={}, \
         pois={}, water={}, landuse={}",
            config.buildings_source,
            config.roads_source,
            config.divisions_source,
            config.landcover_source,
            config.bathymetry_source,
            config.pois_source,
            config.water_source,
            config.landuse_source,
        );

        // The Survey of India features, read once: phase 1f draws them, and
        // their land masks every other country line inside India in the
        // phases before it (Overture, OSM, Natural Earth).
        let india_features = match &config.india_boundary {
            Some(path) => geolith::source::india_file::read_boundary(path)?,
            None => Vec::new(),
        };
        let india_mask = if config.india_boundary.is_some() {
            Some(
                IndiaMask::from_features(&india_features)
                    .ok_or(TilesError::IndiaBoundaryWithoutRing)?,
            )
        } else {
            None
        };
        let india_mask = india_mask.as_ref();

        let mut conflation_filter: Option<Arc<ConflationFilter>> = None;

        // 1a. Overture Parquet — stream features per-file (parallel across files)
        let all_sources = source::discover(config.data.as_path())?;
        let missing = source::missing_types(&all_sources, |layer| config.overture_enabled(layer));
        if !missing.is_empty() {
            if config.reclaim_source_after_read && !config.allow_missing_types {
                return Err(TilesError::MissingOvertureTypes {
                    data: config.data.clone(),
                    types: missing,
                });
            }
            tracing::warn!(
                types = %missing.join(", "),
                "the data folder holds no Parquet file of these Overture types: their layers are built without them"
            );
        }
        let sources: Vec<_> = all_sources
            .into_iter()
            .filter(|src| {
                src.target_layers
                    .iter()
                    .any(|&l| config.overture_enabled(l))
            })
            .collect();
        overture_read = !sources.is_empty();
        let overture_timer = PhaseTimer::start("overture");
        tracing::info!(
            "[overture] {} Parquet files after source filtering",
            sources.len()
        );
        if !sources.is_empty() {
            let overture_total = sources.len();
            let overture_done = AtomicU32::new(0);
            let pb = progress::feature_progress(overture_total as u64, "parquet files");
            let emitter = OvertureEmitter {
                config,
                max_zoom,
                tile_bounds: tile_bounds.as_ref(),
                india_mask,
                features_processed: &features_processed,
                tiles_emitted: &tiles_emitted,
                layer_features: &layer_features,
                layer_tiles: &layer_tiles,
            };
            let wkb_baseline = reader::skipped_wkb_totals();
            sources.par_iter().try_for_each(|src| -> Result<()> {
                // Per-thread sink — no Mutex, no lock contention on writes.
                let mut local_sink =
                    ChunkSink::with_counter(tmp_dir.clone(), chunk_counter.clone());
                let mut local_buffer = SortBuffer::with_max_bytes(chunk_bytes);
                let mut failure = Failure::default();
                let report = reader::read_parquet_file_reported(
                    &src.path,
                    src.overture_type,
                    bbox.as_ref(),
                    |feature| {
                        if failure.is_set() {
                            return;
                        }
                        failure.record(emitter.emit(
                            &feature,
                            src.target_layers,
                            &mut local_buffer,
                            &mut local_sink,
                        ));
                    },
                )?;
                failure.finish()?;
                if !local_buffer.is_empty() {
                    local_buffer.flush(&mut local_sink)?;
                }
                // Collect paths (cold path — once per file, not per entry)
                all_chunk_paths
                    .lock()
                    .map_err(|_| TilesError::LockPoisoned {
                        what: "sort chunk paths",
                    })?
                    .extend(local_sink.into_chunk_paths());
                let done = overture_done.fetch_add(1, Ordering::Relaxed) + 1;
                pb.inc(1);
                tracing::info!(
                    "Overture: {done}/{overture_total} files | {} features, {} tile features",
                    features_processed.load(Ordering::Relaxed),
                    tiles_emitted.load(Ordering::Relaxed),
                );
                reclaim_source_file(
                    &src.path,
                    config.reclaim_source_after_read && source_is_safe_to_reclaim(&report),
                );
                Ok(())
            })?;
            pb.finish_with_message("done");
            let (skipped, skipped_files) = reader::skipped_wkb_totals();
            if skipped > wkb_baseline.0 {
                tracing::warn!(
                    "[overture] {} geometries in {} files were not valid WKB and were skipped \
                     (limit {} per file)",
                    skipped - wkb_baseline.0,
                    skipped_files - wkb_baseline.1,
                    reader::MAX_BAD_WKB_PER_FILE
                );
            }
            overture_timer.finish_with_detail(&format!(
                "{} features, {} tile features",
                format_count(features_processed.load(Ordering::Relaxed)),
                format_count(tiles_emitted.load(Ordering::Relaxed)),
            ));
        }

        // 1b. OSM PBF — two-pass processing (skipped when --osm-pbf not provided)
        if let Some(osm_pbf) = &config.osm_pbf {
            let bridge_paths: Vec<PathBuf> = if config.no_conflate {
                tracing::info!("GERS conflation disabled via --no-conflate");
                Vec::new()
            } else {
                let paths = config.try_discover_bridge_files()?;
                if paths.is_empty() {
                    tracing::info!(
                        "No GERS bridge files found \u{2014} OSM features will not be deduplicated. \
                     Provide --bridge-dir or place bridge files in a gers-bridge/ sibling of --data"
                    );
                } else {
                    tracing::info!(
                        "Discovered {} GERS bridge files \u{2014} loading deferred until after OSM pass 1",
                        paths.len()
                    );
                }
                paths
            };

            let osm_extract = if let Some(ref b) = bbox {
                osmium::try_extract(osm_pbf, b, &tmp_dir)?
            } else {
                osmium::ExtractResult {
                    pbf_path: osm_pbf.clone(),
                    is_extracted: false,
                }
            };
            let osm_pbf_path = &osm_extract.pbf_path;
            tracing::info!("[osm] reading {}", osm_pbf_path.display());
            let node_store_path = config.node_store.clone().unwrap_or_else(|| {
                osm_pbf
                    .parent()
                    .unwrap_or(std::path::Path::new("."))
                    .join("geolith-nodes.bin")
            });

            let suppress_india = config.has_india_boundary();
            let (store, way_to_relations) = {
                let osm_pass1_timer = PhaseTimer::start("osm_pass1");
                let (pass1, cached) = osm::pass1_or_cached(
                    osm_pbf_path,
                    osm_pbf,
                    &node_store_path,
                    config.node_store.is_some(),
                    config.reuse.node_cache,
                    osm::Relations::Collect,
                )
                .map_err(|e| e.context(format!("node store {}", node_store_path.display())))?;
                osm_pass1_timer.finish_with_detail(&format!(
                    "{} nodes{}, {} ways with relations",
                    format_count(pass1.node_stats.nodes_stored),
                    if cached { " (cached)" } else { "" },
                    format_count(pass1.way_to_relations.len() as u64),
                ));
                (pass1.store, pass1.way_to_relations)
            };

            // Load GERS bridge files NOW — deferred from earlier to keep ~50-100 GB
            // of HashMap data out of memory during OSM pass 1 (node coordinate storage).
            conflation_filter = if bridge_paths.is_empty() {
                None
            } else {
                let bridge_timer = PhaseTimer::start("gers_bridge");
                tracing::info!(
                    "Loading {} GERS bridge files for OSM deduplication",
                    bridge_paths.len()
                );
                let mut bridges = Vec::with_capacity(bridge_paths.len());
                for path in &bridge_paths {
                    let index = BridgeIndex::load(path, None)?;
                    tracing::info!(
                        "  Loaded bridge file: {} ({} entries)",
                        path.display(),
                        index.len()
                    );
                    bridges.push(index);
                }
                bridge_timer.finish_with_detail(&format!(
                    "{} files, {} total entries",
                    bridges.len(),
                    format_count(bridges.iter().map(|b| b.len()).sum::<usize>() as u64),
                ));
                Some(Arc::new(ConflationFilter::new(bridges)))
            };
            let mut osm_total: u64 = 0;
            // Per-layer dispatch counters for diagnostics
            let osm_layer_dispatch: [AtomicU64; 11] = std::array::from_fn(|_| AtomicU64::new(0));
            let osm_layer_tiles: [AtomicU64; 11] = std::array::from_fn(|_| AtomicU64::new(0));
            {
                let osm_pass2_timer = PhaseTimer::start("osm_pass2");
                let osm_layers: Vec<Layer> = layer_routing::OSM_LAYERS
                    .iter()
                    .copied()
                    .filter(|&l| config.osm_enabled(l))
                    .collect();
                tracing::info!(
                    "[osm_pass2] processing {} layers after source filtering",
                    osm_layers.len()
                );
                let osm_pass2_pb = progress::phase_spinner("OSM pass 2");
                osm_pass2_pb.set_message("scanning elements...");
                let osm_elements = AtomicU64::new(0);
                let osm_features_found = AtomicU64::new(0);
                let blob_reader =
                    osmpbf::BlobReader::from_path(osm_pbf_path).map_err(|source| {
                        TilesError::OsmPbf {
                            step: "blob reader",
                            source,
                        }
                    })?;
                let worker_results: Vec<(ChunkSink, SortBuffer, u64)> = blob_reader
                .par_bridge()
                .try_fold(
                    || {
                        (
                            ChunkSink::with_counter(tmp_dir.clone(), chunk_counter.clone()),
                            SortBuffer::with_max_bytes(chunk_bytes),
                            0_u64,
                        )
                    },
                    |(mut sink, mut buffer, mut count), blob_result| -> Result<_> {
                        let blob =
                            blob_result.map_err(|source| TilesError::OsmPbf {
                                step: "blob read",
                                source,
                            })?;
                        if let osmpbf::blob::BlobDecode::OsmData(block) = blob
                            .decode()
                            .map_err(|source| TilesError::OsmPbf {
                                step: "decode",
                                source,
                            })?
                        {
                            for element in block.elements() {
                                let elem_count = osm_elements.fetch_add(1, Ordering::Relaxed) + 1;
                                if elem_count.is_multiple_of(10_000_000) {
                                    osm_pass2_pb.set_message(format!(
                                        "{} elements, {} features, {} tile features",
                                        elem_count,
                                        osm_features_found.load(Ordering::Relaxed),
                                        tiles_emitted.load(Ordering::Relaxed),
                                    ));
                                    tracing::info!(
                                        "[osm_pass2] {} elements, {} features, {} tile features",
                                        elem_count,
                                        osm_features_found.load(Ordering::Relaxed),
                                        tiles_emitted.load(Ordering::Relaxed)
                                    );
                                }
                                if let Some(feature) = osm::element_to_feature(
                                    element,
                                    &store,
                                    &way_to_relations,
                                    suppress_india,
                                ) {
                                    // Conflation: skip OSM features with GERS bridge matches
                                    if let Some(ref filter) = conflation_filter
                                        && filter.should_skip(feature.id)
                                    {
                                        count += 1;
                                        continue;
                                    }
                                    for &target_layer in &osm_layers {
                                        if target_layer == Layer::Buildings {
                                            let all = buildings::process_all(&feature);
                                            for processed in &all {
                                                osm_layer_dispatch[Layer::Buildings as usize]
                                                    .fetch_add(1, Ordering::Relaxed);
                                                features_processed.fetch_add(1, Ordering::Relaxed);
                                                layer_features[Layer::Buildings as usize]
                                                    .fetch_add(1, Ordering::Relaxed);
                                                let pre = tiles_emitted.load(Ordering::Relaxed);
                                                emit_tile_features(
                                                    processed,
                                                    max_zoom,
                                                    &mut buffer,
                                                    &mut sink,
                                                    &tiles_emitted,
                                                    tile_bounds.as_ref(),
                                                )?;
                                                let post = tiles_emitted.load(Ordering::Relaxed);
                                                osm_layer_tiles[Layer::Buildings as usize]
                                                    .fetch_add(post - pre, Ordering::Relaxed);
                                                layer_tiles[Layer::Buildings as usize]
                                                    .fetch_add(post - pre, Ordering::Relaxed);
                                            }
                                            continue;
                                        }
                                        let processed = match layers::dispatch(
                                            &feature,
                                            target_layer,
                                        )
                                        .and_then(|p| mask_india(india_mask, p))
                                        {
                                            Some(p) => p,
                                            None => continue,
                                        };
                                        osm_layer_dispatch[target_layer as usize]
                                            .fetch_add(1, Ordering::Relaxed);
                                        features_processed.fetch_add(1, Ordering::Relaxed);
                                        layer_features[processed.layer as usize]
                                            .fetch_add(1, Ordering::Relaxed);
                                        let pre = tiles_emitted.load(Ordering::Relaxed);
                                        emit_tile_features(
                                            &processed,
                                            max_zoom,
                                            &mut buffer,
                                            &mut sink,
                                            &tiles_emitted,
                                            tile_bounds.as_ref(),
                                        )?;
                                        let post = tiles_emitted.load(Ordering::Relaxed);
                                        osm_layer_tiles[target_layer as usize]
                                            .fetch_add(post - pre, Ordering::Relaxed);
                                        layer_tiles[processed.layer as usize]
                                            .fetch_add(post - pre, Ordering::Relaxed);
                                    }
                                    count += 1;
                                    osm_features_found.fetch_add(1, Ordering::Relaxed);
                                }
                            }
                        }
                        Ok((sink, buffer, count))
                    },
                )
                .collect::<Result<Vec<_>>>()?;
                for (mut sink, mut buffer, count) in worker_results {
                    if !buffer.is_empty() {
                        buffer.flush(&mut sink)?;
                    }
                    all_chunk_paths
                        .lock()
                        .map_err(|_| TilesError::LockPoisoned {
                            what: "sort chunk paths",
                        })?
                        .extend(sink.into_chunk_paths());
                    osm_total += count;
                }
                osm_pass2_pb.finish_with_message(format!(
                    "done: {} features, {} tile features",
                    format_count(osm_total),
                    format_count(tiles_emitted.load(Ordering::Relaxed)),
                ));
                osm_pass2_timer.finish_with_detail(&format!(
                    "{} features, {} tile features",
                    format_count(osm_total),
                    format_count(tiles_emitted.load(Ordering::Relaxed)),
                ));
                tracing::info!("[osm_pass2] per-layer dispatch counts:");
                for layer in Layer::ALL {
                    let dispatched = osm_layer_dispatch[layer as usize].load(Ordering::Relaxed);
                    let tiles = osm_layer_tiles[layer as usize].load(Ordering::Relaxed);
                    if dispatched > 0 || tiles > 0 {
                        tracing::info!(
                            "  {}: {} dispatched, {} tile features",
                            layer.name(),
                            format_count(dispatched),
                            format_count(tiles),
                        );
                    }
                }
            }
            // A node that could not be read looks like a node that is not
            // there: its ways would be missing from the archive. Fail instead.
            store
                .check_reads()
                .map_err(|e| e.context(format!("node store {}", node_store_path.display())))?;
            drop(store);
            osmium::cleanup(&osm_extract);
        } else {
            tracing::info!("Skipping OSM processing (--osm-pbf not provided)");
        }

        // 1c. Natural Earth SQLite — stream features
        let ne_timer = PhaseTimer::start("natural_earth");
        {
            let mut ne_sink = ChunkSink::with_counter(tmp_dir.clone(), chunk_counter.clone());
            let mut local_buffer = SortBuffer::with_max_bytes(chunk_bytes);
            let mut failure = Failure::default();
            natural_earth::read_natural_earth(config.natural_earth.as_path(), |feature| {
                if failure.is_set() {
                    return;
                }
                for &target_layer in layer_routing::NE_LAYERS {
                    let processed = match layers::dispatch(&feature, target_layer)
                        .and_then(|p| mask_india(india_mask, p))
                    {
                        Some(p) => p,
                        None => continue,
                    };
                    features_processed.fetch_add(1, Ordering::Relaxed);
                    layer_features[processed.layer as usize].fetch_add(1, Ordering::Relaxed);
                    let pre = tiles_emitted.load(Ordering::Relaxed);
                    failure.record(emit_tile_features(
                        &processed,
                        max_zoom,
                        &mut local_buffer,
                        &mut ne_sink,
                        &tiles_emitted,
                        tile_bounds.as_ref(),
                    ));
                    if failure.is_set() {
                        return;
                    }
                    let post = tiles_emitted.load(Ordering::Relaxed);
                    layer_tiles[processed.layer as usize].fetch_add(post - pre, Ordering::Relaxed);
                }
            })?;
            failure.finish()?;
            if !local_buffer.is_empty() {
                local_buffer.flush(&mut ne_sink)?;
            }

            all_chunk_paths
                .lock()
                .map_err(|_| TilesError::LockPoisoned {
                    what: "sort chunk paths",
                })?
                .extend(ne_sink.into_chunk_paths());
            ne_timer.finish_with_detail(&format!(
                "{} features, {} tile features",
                format_count(features_processed.load(Ordering::Relaxed)),
                format_count(tiles_emitted.load(Ordering::Relaxed)),
            ));
        }

        // 1d+1e. Land + Water polygons — read in parallel
        //
        // These two shapefiles are the slowest Phase 1 sources (102s + 129s
        // sequential on western-zone). Running them on separate threads cuts
        // wall time by ~100s since the bottleneck is per-file I/O + reprojection.
        let shapefile_timer = PhaseTimer::start("shapefile_reads");
        {
            let land_shp_path = find_shp_file(config.land_polygons.as_path())?;
            let water_shp_path = find_shp_file(config.water_polygons.as_path())?;

            tracing::info!(
                "Land + Water polygons: reading in parallel ({}, {})",
                config.land_polygons.as_path().display(),
                config.water_polygons.as_path().display()
            );

            let land_pb = progress::phase_spinner("Land polygons");
            land_pb.set_message("reading shapefile...");
            let water_pb = progress::phase_spinner("Water polygons");
            water_pb.set_message("reading shapefile...");
            let (land_result, water_result) = std::thread::scope(|s| {
                let land_handle = s.spawn(|| -> Result<Vec<PathBuf>> {
                    let mut sink = ChunkSink::with_counter(tmp_dir.clone(), chunk_counter.clone());
                    let mut buf = SortBuffer::with_max_bytes(chunk_bytes);
                    let mut land_count = 0_u64;
                    let mut failure = Failure::default();
                    shapefile_reader::read_land_polygons(
                        &land_shp_path,
                        bbox.as_ref(),
                        |feature| {
                            if failure.is_set() {
                                return;
                            }
                            let processed = match layers::dispatch(&feature, Layer::Earth) {
                                Some(p) => p,
                                None => return,
                            };
                            land_count += 1;
                            if land_count.is_multiple_of(100_000) {
                                land_pb.set_message(format!("{land_count} features"));
                                tracing::info!("[land_polygons] {land_count} features");
                            }
                            features_processed.fetch_add(1, Ordering::Relaxed);
                            layer_features[Layer::Earth as usize].fetch_add(1, Ordering::Relaxed);
                            let pre = tiles_emitted.load(Ordering::Relaxed);
                            failure.record(emit_tile_features(
                                &processed,
                                max_zoom,
                                &mut buf,
                                &mut sink,
                                &tiles_emitted,
                                tile_bounds.as_ref(),
                            ));
                            let post = tiles_emitted.load(Ordering::Relaxed);
                            layer_tiles[Layer::Earth as usize]
                                .fetch_add(post - pre, Ordering::Relaxed);
                        },
                    )?;
                    failure.finish()?;
                    if !buf.is_empty() {
                        buf.flush(&mut sink)?;
                    }
                    land_pb.finish_with_message(format!("done: {land_count} features"));
                    Ok(sink.into_chunk_paths())
                });

                let water_handle = s.spawn(|| -> Result<Vec<PathBuf>> {
                    let mut sink = ChunkSink::with_counter(tmp_dir.clone(), chunk_counter.clone());
                    let mut buf = SortBuffer::with_max_bytes(chunk_bytes);
                    let mut water_count = 0_u64;
                    let mut failure = Failure::default();
                    shapefile_reader::read_water_polygons(
                        &water_shp_path,
                        bbox.as_ref(),
                        |feature| {
                            if failure.is_set() {
                                return;
                            }
                            let processed = match layers::dispatch(&feature, Layer::Water) {
                                Some(p) => p,
                                None => return,
                            };
                            water_count += 1;
                            if water_count.is_multiple_of(100_000) {
                                water_pb.set_message(format!("{water_count} features"));
                                tracing::info!("[water_polygons] {water_count} features");
                            }
                            features_processed.fetch_add(1, Ordering::Relaxed);
                            layer_features[Layer::Water as usize].fetch_add(1, Ordering::Relaxed);
                            let pre = tiles_emitted.load(Ordering::Relaxed);
                            failure.record(emit_tile_features(
                                &processed,
                                max_zoom,
                                &mut buf,
                                &mut sink,
                                &tiles_emitted,
                                tile_bounds.as_ref(),
                            ));
                            let post = tiles_emitted.load(Ordering::Relaxed);
                            layer_tiles[Layer::Water as usize]
                                .fetch_add(post - pre, Ordering::Relaxed);
                        },
                    )?;
                    failure.finish()?;
                    if !buf.is_empty() {
                        buf.flush(&mut sink)?;
                    }
                    water_pb.finish_with_message(format!("done: {water_count} features"));
                    Ok(sink.into_chunk_paths())
                });

                (land_handle.join(), water_handle.join())
            });

            let land_chunks = land_result.map_err(|payload| TilesError::ThreadPanicked {
                thread: "land polygon",
                message: panic_message(payload.as_ref()),
            })??;
            let water_chunks = water_result.map_err(|payload| TilesError::ThreadPanicked {
                thread: "water polygon",
                message: panic_message(payload.as_ref()),
            })??;

            all_chunk_paths
                .lock()
                .map_err(|_| TilesError::LockPoisoned {
                    what: "sort chunk paths",
                })?
                .extend(land_chunks.into_iter().chain(water_chunks));
            shapefile_timer.finish_with_detail(&format!(
                "{} features, {} tile features",
                format_count(features_processed.load(Ordering::Relaxed)),
                format_count(tiles_emitted.load(Ordering::Relaxed)),
            ));
        }
        // 1f. India boundary GeoJSON (optional, tiny file, read above)
        if config.india_boundary.is_some() {
            let india_timer = PhaseTimer::start("india_boundary");
            tracing::info!("India boundary: {} features", india_features.len());

            let mut india_sink = ChunkSink::with_counter(tmp_dir.clone(), chunk_counter.clone());
            let mut local_buffer = SortBuffer::with_max_bytes(chunk_bytes);
            for feature in &india_features {
                let processed = match layers::dispatch(feature, Layer::Boundaries) {
                    Some(p) => p,
                    None => continue,
                };
                features_processed.fetch_add(1, Ordering::Relaxed);
                layer_features[Layer::Boundaries as usize].fetch_add(1, Ordering::Relaxed);
                let pre = tiles_emitted.load(Ordering::Relaxed);
                emit_tile_features(
                    &processed,
                    max_zoom,
                    &mut local_buffer,
                    &mut india_sink,
                    &tiles_emitted,
                    tile_bounds.as_ref(),
                )?;
                let post = tiles_emitted.load(Ordering::Relaxed);
                layer_tiles[Layer::Boundaries as usize].fetch_add(post - pre, Ordering::Relaxed);
            }
            if !local_buffer.is_empty() {
                local_buffer.flush(&mut india_sink)?;
            }

            all_chunk_paths
                .lock()
                .map_err(|_| TilesError::LockPoisoned {
                    what: "sort chunk paths",
                })?
                .extend(india_sink.into_chunk_paths());
            india_timer.finish_with_detail(&format!(
                "{} features, {} tile features",
                format_count(features_processed.load(Ordering::Relaxed)),
                format_count(tiles_emitted.load(Ordering::Relaxed)),
            ));
        }
        let total_features = features_processed.load(Ordering::Relaxed);
        let total_tile_features = tiles_emitted.load(Ordering::Relaxed);
        phase1_timer.finish_with_detail(&format!(
            "{} features → {} tile features",
            format_count(total_features),
            format_count(total_tile_features),
        ));
        tracing::info!("[phase1] per-layer summary:");
        for layer in Layer::ALL {
            let feats = layer_features[layer as usize].load(Ordering::Relaxed);
            let tiles = layer_tiles[layer as usize].load(Ordering::Relaxed);
            if feats > 0 || tiles > 0 {
                tracing::info!(
                    "  {:12} {:>10} features → {:>10} tile features",
                    layer.name(),
                    format_count(feats),
                    format_count(tiles),
                );
            }
        }
        log_geometry_failures();
        if let Some(ref filter) = conflation_filter {
            filter.log_summary();
            tracing::info!(
                "Conflation: {} OSM features deduplicated via bridge files, \
                 0 via spatial matching",
                filter.skipped_count()
            );
        }
    } // end if !config.reuse.resume

    // Collect chunk paths: from Phase 1 output or discovered from --tmpdir (resume).
    let chunk_paths: Vec<PathBuf> = if config.reuse.resume {
        tracing::info!(
            "Resume mode: skipping Phase 1, discovering chunks from {}",
            tmp_dir.display()
        );
        if !tmp_dir.is_dir() {
            return Err(TilesError::ResumeDirMissing { path: tmp_dir });
        }
        // An entry that cannot be read is an error: a run left out of the
        // merge would leave its tiles out of the archive.
        let mut paths: Vec<PathBuf> = Vec::new();
        for entry in std::fs::read_dir(&tmp_dir)? {
            let path = entry?.path();
            if path.is_file() && path.extension().is_some_and(|e| e == RUN_EXTENSION) {
                paths.push(path);
            }
        }
        paths.sort();
        if paths.is_empty() {
            return Err(TilesError::NoChunksToResume { path: tmp_dir });
        }
        crate::sort::manifest::check_resumable(&tmp_dir, paths.len())?;
        tracing::info!("Resume: found {} chunk files", paths.len());
        paths
    } else {
        let paths = all_chunk_paths
            .into_inner()
            .map_err(|_| TilesError::LockPoisoned {
                what: "sort chunk paths",
            })?;
        if paths.is_empty() {
            return Err(TilesError::NothingToWrite);
        }
        crate::sort::manifest::mark_phase1_complete(&tmp_dir, paths.len())?;
        paths
    };

    // The merge opens every run at once: check the open-file limit before the
    // first run is touched (a `--reclaim-chunks` merge cannot be resumed).
    crate::fd_limit::ensure_open_files(chunk_paths.len())?;

    let phase2_timer = PhaseTimer::start("phase2_merge");
    let merge_pb = progress::phase_spinner("Merge sort");
    merge_pb.set_message(format!("merging {} chunks...", chunk_paths.len()));
    let mut merger = if config.reclaim_chunks {
        // Before the first run is touched: from here no resume is possible.
        crate::sort::manifest::mark_reclaiming(&tmp_dir)?;
        KWayMerge::open_reclaiming(&chunk_paths)?
    } else {
        KWayMerge::open(&chunk_paths)?
    };
    merge_pb.set_message(format!("opened {} chunks", chunk_paths.len()));

    // Phase 3: Write PMTiles
    let phase3_timer = PhaseTimer::start("phase3_write");
    tracing::info!(
        "[phase3_write] writing PMTiles → {}",
        config.output.as_path().display()
    );

    let use_mlt = config.tile_format == "mlt";
    let (tile_type, tile_compression) = if use_mlt {
        (TileType::Mlt, PmtCompression::None)
    } else {
        (TileType::Mvt, PmtCompression::Gzip)
    };
    tracing::info!(
        "[phase3_write] tile format: {}",
        if use_mlt { "MLT" } else { "MVT" }
    );

    // `create` truncates the file, so from here the old content is gone; if the
    // build fails before the archive is whole, remove it rather than leave a
    // short archive that looks like a result.
    let mut partial = PartialArchive::new(config.output.as_path());
    let mut writer = PmtilesWriter::create(
        config.output.as_path(),
        tile_compression,
        tile_type,
        0,
        max_zoom,
    )?;
    if let Some(b) = &bbox {
        writer.set_bounds(b.min_lon, b.min_lat, b.max_lon, b.max_lat);
    }

    let mut current_tile_key: Option<(u8, u64)> = None;
    let mut tile_features: Vec<TileFeature> = Vec::with_capacity(256);
    let mut tiles_written: u64 = 0;
    let mut batch: Vec<PendingTile> = Vec::with_capacity(ENCODE_BATCH_SIZE);

    let write_pb = progress::phase_spinner("Tile encode");
    write_pb.set_message("encoding + compressing tiles...");
    let mut merge_entries: u64 = 0;
    while let Some(entry) = merger.next_entry()? {
        merge_entries += 1;
        if merge_entries.is_multiple_of(1_000_000) {
            merge_pb.set_message(format!("{} entries merged", merge_entries));
            tracing::info!("[merge_sort] {} entries merged", merge_entries);
        }
        let (z, tid) = sort_key::decode_tile_id(entry.key);
        let tile_key = (z, tid);
        match current_tile_key {
            Some(cur) if cur == tile_key => {
                tile_features.push(entry.feature);
            }
            _ => {
                if let Some(prev_key) = current_tile_key
                    && !tile_features.is_empty()
                {
                    batch.push(PendingTile {
                        tile_key: prev_key,
                        features: std::mem::replace(&mut tile_features, Vec::with_capacity(256)),
                    });

                    if batch.len() >= ENCODE_BATCH_SIZE {
                        tiles_written += flush_batch(&mut writer, &mut batch, use_mlt)?;
                        if tiles_written.is_multiple_of(10_000) {
                            write_pb.set_message(format!("{tiles_written} tiles encoded"));
                            tracing::info!("[tile_encode] {tiles_written} tiles encoded");
                        }
                    }
                }
                current_tile_key = Some(tile_key);
                tile_features.push(entry.feature);
            }
        }
    }

    // Push final tile into batch
    if !tile_features.is_empty()
        && let Some(key) = current_tile_key
    {
        batch.push(PendingTile {
            tile_key: key,
            features: tile_features,
        });
    }

    // Flush remaining batch
    if !batch.is_empty() {
        tiles_written += flush_batch(&mut writer, &mut batch, use_mlt)?;
    }

    merge_pb.finish_with_message(format!("done: {} entries merged", merge_entries));
    write_pb.finish_with_message(format!("{tiles_written} tiles encoded"));

    // Finalize with metadata
    tracing::info!(
        "[pmtiles_finalize] finalizing {} tiles → {}",
        tiles_written,
        config.output.as_path().display()
    );
    // OpenStreetMap is always read: the land and water polygons are made from
    // it. Natural Earth is a required input. Overture is read when the data
    // folder holds a file for an enabled layer (a resumed build assumes it:
    // `--reclaim-source-after-read` may have deleted the files by now). The
    // Survey of India lines of DataMeet are read when `--india-boundary` is set.
    let credited = geolith::attribution::DataSources::new(
        true,
        overture_read,
        config.india_boundary.is_some(),
    )
    .with_natural_earth();
    let metadata = build_metadata(max_zoom, use_mlt, credited).map_err(TilesError::Metadata)?;
    writer.finalize(metadata.as_bytes())?;
    partial.disarm();
    tracing::info!(
        "[pmtiles_finalize] done: {} tiles written to {}",
        tiles_written,
        config.output.as_path().display()
    );

    phase2_timer.finish_with_detail(&format!(
        "{} entries merged from {} chunks",
        format_count(merge_entries),
        chunk_paths.len(),
    ));
    phase3_timer.finish_with_detail(&format!(
        "{} tiles written to {}",
        format_count(tiles_written),
        config.output.as_path().display(),
    ));
    log_geometry_failures();
    // Cleanup temp chunks. The archive is written, synced and closed by now,
    // so a leftover sort folder costs disk only; failing here would throw away
    // a finished archive. The warning names the folder. Only the files this
    // build wrote go: `--tmpdir` is the user's folder.
    if let Err(e) = crate::sort::manifest::clean_up(&tmp_dir) {
        tracing::warn!(
            "Failed to clean up the sort folder {}: {e}",
            tmp_dir.display()
        );
    }

    Ok(())
}

/// Find the `.shp` file inside a directory (or return the path if it's a file).
///
/// With several `.shp` files the first by path is used, so the choice does
/// not depend on the filesystem's `read_dir` order.
fn find_shp_file(path: &std::path::Path) -> Result<PathBuf> {
    if path.is_file() {
        return Ok(path.to_path_buf());
    }

    if path.is_dir() {
        let mut shapefiles = Vec::new();
        for entry in std::fs::read_dir(path)? {
            let p = entry?.path();
            if p.extension().is_some_and(|ext| ext == "shp") {
                shapefiles.push(p);
            }
        }
        return shapefiles
            .into_iter()
            .min()
            .ok_or_else(|| TilesError::NoShapefile {
                path: path.to_path_buf(),
            });
    }

    Err(TilesError::ShapefileMissing {
        path: path.to_path_buf(),
    })
}

/// Whether a source file that was read may be deleted by
/// `--reclaim-source-after-read`: it produced at least one feature and no
/// geometry was skipped. A file that gave nothing, or that was only partly
/// read, stays on disk so the data is not lost with the evidence.
fn source_is_safe_to_reclaim(report: &reader::ReadReport) -> bool {
    report.features > 0 && report.skipped_wkb == 0
}

/// Release an Overture source file whose features are already committed to chunks.
///
/// Best effort by design: a failed unlink is logged, never propagated. Losing a
/// re-downloadable input must not fail a build that has already run for hours,
/// and the chunks that file produced remain valid regardless.
fn reclaim_source_file(path: &std::path::Path, enabled: bool) {
    if !enabled {
        return;
    }
    if let Err(e) = std::fs::remove_file(path) {
        tracing::warn!("could not reclaim {}: {e}", path.display());
    }
}

/// Per-tile ring collection: maps each tile to its rings with exterior/interior flag.
type TileRingMap = HashMap<TileCoord, Vec<(bool, Vec<(i32, i32)>)>>;

/// Removes the archive when the build ends before the archive is complete.
struct PartialArchive<'a> {
    path: &'a std::path::Path,
    armed: bool,
}

impl<'a> PartialArchive<'a> {
    const fn new(path: &'a std::path::Path) -> Self {
        Self { path, armed: true }
    }

    /// The archive is whole: keep it.
    const fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for PartialArchive<'_> {
    fn drop(&mut self) {
        if self.armed {
            // The build is already failing with its own error; a leftover that
            // cannot be removed adds nothing to it, so the result is ignored.
            let _ = std::fs::remove_file(self.path);
        }
    }
}

/// The first error of a reader that drives a callback: the callback cannot
/// return an error, so it parks the first one here, skips the rest of the
/// source, and the caller raises it once the reader returns.
#[derive(Default)]
struct Failure(Option<TilesError>);

impl Failure {
    const fn is_set(&self) -> bool {
        self.0.is_some()
    }

    fn record(&mut self, result: Result<()>) {
        if let Err(e) = result {
            self.0.get_or_insert(e);
        }
    }

    fn finish(self) -> Result<()> {
        self.0.map_or(Ok(()), Err)
    }
}

/// Shared state for turning Overture features into sort entries.
///
/// Holds only shared references, so one instance serves every rayon worker;
/// each worker passes its own buffer and sink.
struct OvertureEmitter<'a> {
    config: &'a TilesConfig,
    max_zoom: u8,
    tile_bounds: Option<&'a TileBounds>,
    /// Survey of India land, when `--india-boundary` is set.
    india_mask: Option<&'a IndiaMask>,
    features_processed: &'a AtomicU64,
    tiles_emitted: &'a AtomicU64,
    layer_features: &'a [AtomicU64],
    layer_tiles: &'a [AtomicU64],
}

impl OvertureEmitter<'_> {
    /// Dispatch `feature` to every enabled target layer and emit its tiles.
    ///
    /// A layer may produce several features from one input (a building and
    /// its address point, or a road split where a bridge begins). Each one is
    /// counted against the layer it lands in.
    ///
    /// # Errors
    ///
    /// The first failed write of a sort run stops the emit: a feature whose
    /// tiles are not in a run would be missing from the archive.
    fn emit(
        &self,
        feature: &InputFeature,
        target_layers: &[Layer],
        buffer: &mut SortBuffer,
        sink: &mut ChunkSink,
    ) -> Result<()> {
        for &target_layer in target_layers {
            if !self.config.overture_enabled(target_layer) {
                continue;
            }
            for processed in layers::dispatch_all(feature, target_layer)
                .into_iter()
                .filter_map(|p| mask_india(self.india_mask, p))
            {
                self.features_processed.fetch_add(1, Ordering::Relaxed);
                self.layer_features[processed.layer as usize].fetch_add(1, Ordering::Relaxed);
                let pre = self.tiles_emitted.load(Ordering::Relaxed);
                emit_tile_features(
                    &processed,
                    self.max_zoom,
                    buffer,
                    sink,
                    self.tiles_emitted,
                    self.tile_bounds,
                )?;
                let post = self.tiles_emitted.load(Ordering::Relaxed);
                self.layer_tiles[processed.layer as usize].fetch_add(post - pre, Ordering::Relaxed);
            }
        }
        Ok(())
    }
}

/// Apply the Survey of India land to a feature when there is one (see
/// [`IndiaMask::clip`]); every feature leaves without its private owner mark.
fn mask_india(mask: Option<&IndiaMask>, feature: ProcessedFeature) -> Option<ProcessedFeature> {
    match mask {
        Some(mask) => mask.clip(feature),
        None => Some(layers::take_owner(feature).0),
    }
}

/// Project a `ProcessedFeature` to all zoom levels, clip to tiles, encode
/// MVT geometry, and push `SortEntries` into the buffer.
///
/// Per-zoom: simplify geometry (Douglas-Peucker in world-space), drop
/// sub-pixel features, then clip → snap → encode as before.
///
/// Takes a direct `&mut ChunkSink` — no Mutex. Each thread owns its
/// own sink instance, so writes are lock-free.
fn emit_tile_features(
    processed: &ProcessedFeature,
    global_max_zoom: u8,
    buffer: &mut SortBuffer,
    chunk_sink: &mut ChunkSink,
    counter: &AtomicU64,
    tile_bounds: Option<&TileBounds>,
) -> Result<()> {
    // A clipper panic inside is caught, counted against this feature and
    // logged by `guard`; the build stops once too many features lost pieces.
    let scope = guard::enter(processed.id, processed.layer.name());
    let emitted = emit_tile_features_inner(
        processed,
        global_max_zoom,
        buffer,
        chunk_sink,
        counter,
        tile_bounds,
    );
    drop(scope);
    emitted?;
    guard::exceeded().map_or(Ok(()), |over| Err(geometry_failures_error(over)))
}

/// The error for a build that lost more features than it may.
fn geometry_failures_error(over: guard::Exceeded) -> TilesError {
    TilesError::GeometryFailures {
        count: over.count,
        allowed: over.allowed,
        first: guard::first_failures()
            .first()
            .map(|f| format!("; first: {f}"))
            .unwrap_or_default(),
    }
}

/// Log how many features lost a piece to a caught clipper panic.
fn log_geometry_failures() {
    let count = guard::build_failures();
    let allowed = guard::allowed();
    if count == 0 {
        tracing::info!("geometry failures: 0 features skipped (limit {allowed})");
    } else {
        tracing::warn!(
            "geometry failures: {count} features skipped (limit {allowed}); \
             their clipped pieces are missing from the archive"
        );
    }
}

fn emit_tile_features_inner(
    processed: &ProcessedFeature,
    global_max_zoom: u8,
    buffer: &mut SortBuffer,
    chunk_sink: &mut ChunkSink,
    counter: &AtomicU64,
    tile_bounds: Option<&TileBounds>,
) -> Result<()> {
    let max_zoom = processed.max_zoom.min(global_max_zoom);
    let (geom_type, world_coords_sets, exterior_indices) =
        geometry_to_world_coords(&processed.geometry);
    if world_coords_sets.is_empty() {
        return Ok(());
    }
    let mvt_geom_type: u8 = match geom_type {
        GeomType::Point => 1,
        GeomType::Line => 2,
        GeomType::Polygon => 3,
        _ => return Ok(()),
    };
    let shared_props: Arc<Vec<(String, PropValue)>> = Arc::new(
        processed
            .properties
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect(),
    );
    for zoom in processed.min_zoom..=max_zoom {
        // Multi-ring polygon path: preserves interior rings (holes) through
        // clip → snap → encode. Rings are grouped per tile so that exterior +
        // interior rings encode as a single MVT multi-ring polygon feature.
        if geom_type == GeomType::Polygon && world_coords_sets.len() > 1 {
            let skip_simplify = processed.layer.skips_simplification();
            let epsilon = mercator::simplify_tolerance(zoom) * processed.layer.pixel_tolerance();
            let min_pts = 4usize;

            // Simplify each ring individually, tracking exterior/interior status.
            // If an exterior ring simplifies away, its interior rings are still
            // processed — winding order ensures correct MVT interpretation.
            let mut simplified_rings: Vec<Vec<[f64; 2]>> =
                Vec::with_capacity(world_coords_sets.len());
            let mut ring_is_exterior: Vec<bool> = Vec::with_capacity(world_coords_sets.len());

            for (i, ring) in world_coords_sets.iter().enumerate() {
                let simplified = if skip_simplify {
                    ring.clone()
                } else {
                    dp_simplify(ring, epsilon)
                };
                if simplified.len() >= min_pts {
                    simplified_rings.push(simplified);
                    ring_is_exterior.push(exterior_indices.contains(&i));
                }
            }

            if simplified_rings.is_empty() {
                continue;
            }

            // Area check on combined bounding box (layer-aware thresholds)
            if !skip_simplify
                && is_below_min_area(&simplified_rings, zoom, geom_type, processed.layer)
            {
                continue;
            }

            // Group simplified rings into polygons (exterior + its holes), then
            // clip each polygon AS A UNIT. Clipping rings independently lets a
            // hole survive in a tile without its exterior and render as a
            // standalone fill (the MVT-nonzero "phantom landmass" bug); clipping
            // the whole polygon makes BooleanOps subtract holes correctly.
            let polygons = group_rings_into_polygons(&simplified_rings, &ring_is_exterior);

            let mut tile_rings: TileRingMap = HashMap::new();

            for (exterior_w, interiors_w) in &polygons {
                let to_tile = |ring: &[[f64; 2]]| -> Vec<[f64; 2]> {
                    ring.iter()
                        .map(|&[wx, wy]| {
                            let (tx, ty) = mercator::world_to_tile_frac(wx, wy, zoom);
                            [tx, ty]
                        })
                        .collect()
                };
                let ext_tile = to_tile(exterior_w);
                let int_tile: Vec<Vec<[f64; 2]>> = interiors_w.iter().map(|r| to_tile(r)).collect();

                let clipped = stripe_clip::stripe_clip_polygon(&ext_tile, &int_tile, zoom);
                for (tile, cp) in &clipped {
                    if let Some(bounds) = tile_bounds
                        && !bounds.contains(tile)
                    {
                        continue;
                    }
                    let snap_ring = |ring: &[[f64; 2]]| -> Vec<(i32, i32)> {
                        let snapped: Vec<(i32, i32)> = ring
                            .iter()
                            .map(|&[cx, cy]| {
                                let n = (1u32 << zoom) as f64;
                                snap::world_to_tile_int(cx / n, cy / n, *tile)
                            })
                            .collect();
                        snap::dedup_consecutive(&snapped)
                    };

                    let ext_snapped = snap_ring(&cp.exterior);
                    if ext_snapped.len() < 3 {
                        continue;
                    }
                    let group = tile_rings.entry(*tile).or_default();
                    group.push((true, ext_snapped));
                    for hole in &cp.interiors {
                        let hole_snapped = snap_ring(hole);
                        if hole_snapped.len() >= 3 {
                            group.push((false, hole_snapped));
                        }
                    }
                }
            }

            // Encode each tile's ring group as a single multi-ring polygon.
            // Ring insertion order preserves exterior-before-interior ordering
            // from the source geometry, which matches MVT convention.
            for (tile, rings_data) in &tile_rings {
                let Some(geometry_cmds) = encode_tile_ring_group(rings_data) else {
                    continue;
                };
                let tile_feature = TileFeature {
                    layer: processed.layer,
                    id: processed.id,
                    geom_type,
                    geometry: geometry_cmds,
                    properties: shared_props.clone(),
                    sort_key: processed.sort_rank,
                };
                let sort_key = sort_key::encode(*tile, processed.layer, processed.sort_rank);
                let entry = SortEntry::new(sort_key, tile_feature);
                if buffer.push(entry) {
                    buffer.flush(chunk_sink)?;
                }
                counter.fetch_add(1, Ordering::Relaxed);
            }
        } else {
            // ── Single-part path: points, lines, single-ring polygons ──
            let simplified_holder;
            let coords_for_zoom: &[Vec<[f64; 2]>] =
                if geom_type == GeomType::Point || processed.layer.skips_simplification() {
                    &world_coords_sets
                } else {
                    simplified_holder = simplify_world_coords(
                        &world_coords_sets,
                        zoom,
                        geom_type,
                        processed.layer.pixel_tolerance(),
                    );
                    if simplified_holder.is_empty() {
                        continue;
                    }
                    if is_below_min_area(&simplified_holder, zoom, geom_type, processed.layer) {
                        continue;
                    }
                    &simplified_holder
                };

            for world_coords in coords_for_zoom {
                let tile_coords: Vec<[f64; 2]> = world_coords
                    .iter()
                    .map(|&[wx, wy]| {
                        let (tx, ty) = mercator::world_to_tile_frac(wx, wy, zoom);
                        [tx, ty]
                    })
                    .collect();

                let clipped = stripe_clip::stripe_clip(&tile_coords, zoom, mvt_geom_type);
                for (tile, clipped_coords) in &clipped {
                    if let Some(bounds) = tile_bounds
                        && !bounds.contains(tile)
                    {
                        continue;
                    }
                    let snapped: Vec<(i32, i32)> = clipped_coords
                        .iter()
                        .map(|&[cx, cy]| {
                            let n = (1u32 << zoom) as f64;
                            let wx = cx / n;
                            let wy = cy / n;
                            snap::world_to_tile_int(wx, wy, *tile)
                        })
                        .collect();

                    let deduped = snap::dedup_consecutive(&snapped);

                    let geometry_cmds = encode_geometry(geom_type, &deduped);
                    if geometry_cmds.is_empty() {
                        continue;
                    }
                    let tile_feature = TileFeature {
                        layer: processed.layer,
                        id: processed.id,
                        geom_type,
                        geometry: geometry_cmds,
                        properties: shared_props.clone(),
                        sort_key: processed.sort_rank,
                    };

                    let sort_key = sort_key::encode(*tile, processed.layer, processed.sort_rank);

                    let entry = SortEntry::new(sort_key, tile_feature);
                    if buffer.push(entry) {
                        buffer.flush(chunk_sink)?;
                    }
                    counter.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
    }
    Ok(())
}

/// Simplify world-space coordinate sets for a given zoom using Douglas-Peucker.
///
/// `pixel_tol` is the per-layer tolerance in pixel units (e.g. 0.1 or 0.2).
/// Each `Vec<[f64; 2]>` represents a ring or path in world \[0,1\] coordinates.
/// Returns only non-degenerate coordinate sets (lines ≥ 2 pts, polygons ≥ 4 pts).
fn simplify_world_coords(
    world_coords_sets: &[Vec<[f64; 2]>],
    zoom: u8,
    geom_type: GeomType,
    pixel_tol: f64,
) -> Vec<Vec<[f64; 2]>> {
    let epsilon = mercator::simplify_tolerance(zoom) * pixel_tol;
    let min_pts = match geom_type {
        GeomType::Polygon => 4, // closed ring needs ≥ 4 pts
        GeomType::Line => 2,
        GeomType::Point => return world_coords_sets.to_vec(),
        _ => return world_coords_sets.to_vec(),
    };

    let mut result = Vec::with_capacity(world_coords_sets.len());
    for coords in world_coords_sets {
        let simplified = dp_simplify(coords, epsilon);
        if simplified.len() >= min_pts {
            result.push(simplified);
        }
    }
    result
}

/// Check whether coordinate sets are below the minimum area/size for a layer.
///
/// Uses `Layer::min_pixel_area(zoom)` for polygon area thresholds, which
/// varies by layer (e.g. landuse needs 400–800 pixel² at low zoom,
/// matching Planetiler's post-process area filtering).
///
/// Returns `true` if the feature should be dropped.
fn is_below_min_area(
    world_coords_sets: &[Vec<[f64; 2]>],
    zoom: u8,
    geom_type: GeomType,
    layer: Layer,
) -> bool {
    let pixel = mercator::simplify_tolerance(zoom);

    let mut min_x = f64::MAX;
    let mut max_x = f64::MIN;
    let mut min_y = f64::MAX;
    let mut max_y = f64::MIN;

    for coords in world_coords_sets {
        for &[x, y] in coords {
            min_x = min_x.min(x);
            max_x = max_x.max(x);
            min_y = min_y.min(y);
            max_y = max_y.max(y);
        }
    }

    let dx = max_x - min_x;
    let dy = max_y - min_y;

    match geom_type {
        GeomType::Polygon => {
            let min_area = pixel * pixel * layer.min_pixel_area(zoom);
            dx * dy < min_area
        }
        GeomType::Line => dx < pixel && dy < pixel,
        GeomType::Point => false,
        _ => false,
    }
}

/// Douglas-Peucker simplification on world-space `[f64; 2]` coordinates.
///
/// Operates directly on `&[[f64; 2]]` slices to avoid allocating `geo` types.
/// Uses squared perpendicular distance to avoid `sqrt` on the hot path.
fn dp_simplify(coords: &[[f64; 2]], epsilon: f64) -> Vec<[f64; 2]> {
    let n = coords.len();
    if n <= 2 {
        return coords.to_vec();
    }

    let eps_sq = epsilon * epsilon;
    let mut keep = vec![false; n];
    keep[0] = true;
    keep[n - 1] = true;

    dp_recurse(coords, 0, n - 1, eps_sq, &mut keep);

    coords
        .iter()
        .zip(keep.iter())
        .filter_map(|(pt, &k)| if k { Some(*pt) } else { None })
        .collect()
}

/// Recursive Douglas-Peucker subdivision.
///
/// Finds the point with maximum perpendicular distance from the line
/// between `start` and `end`, and recurses if it exceeds `eps_sq`.
fn dp_recurse(coords: &[[f64; 2]], start: usize, end: usize, eps_sq: f64, keep: &mut [bool]) {
    if end <= start + 1 {
        return;
    }

    let [ax, ay] = coords[start];
    let [bx, by] = coords[end];

    let dx = bx - ax;
    let dy = by - ay;
    let line_len_sq = dx * dx + dy * dy;

    let mut max_dist_sq = 0.0_f64;
    let mut max_idx = start;

    for (i, coord) in coords
        .iter()
        .enumerate()
        .skip(start + 1)
        .take(end - start - 1)
    {
        let [px, py] = *coord;
        let dist_sq = if line_len_sq < 1e-30 {
            // Start and end are the same point — use distance to that point
            let ex = px - ax;
            let ey = py - ay;
            ex * ex + ey * ey
        } else {
            // Perpendicular distance² from point to line segment
            let cross = (px - ax) * dy - (py - ay) * dx;
            (cross * cross) / line_len_sq
        };
        if dist_sq > max_dist_sq {
            max_dist_sq = dist_sq;
            max_idx = i;
        }
    }

    if max_dist_sq > eps_sq {
        keep[max_idx] = true;
        dp_recurse(coords, start, max_idx, eps_sq, keep);
        dp_recurse(coords, max_idx, end, eps_sq, keep);
    }
}

/// Convert a `geo::Geometry` to world-space coordinate arrays.
///
/// Returns `(geom_type, rings, exterior_indices)` where:
/// - `rings`: list of coordinate rings/paths in world [0,1] coordinates.
/// - `exterior_indices`: for polygon types, indices into `rings` that mark
///   exterior ring starts (interior rings follow their exterior). Empty for
///   non-polygon types.
fn geometry_to_world_coords(
    geom: &geo::Geometry<f64>,
) -> (GeomType, Vec<Vec<[f64; 2]>>, Vec<usize>) {
    match geom {
        geo::Geometry::Point(pt) => {
            let (wx, wy) = mercator::wgs84_to_world(pt.x(), pt.y());
            (GeomType::Point, vec![vec![[wx, wy]]], vec![])
        }
        geo::Geometry::MultiPoint(mp) => {
            let coords: Vec<[f64; 2]> =
                mp.0.iter()
                    .map(|pt| {
                        let (wx, wy) = mercator::wgs84_to_world(pt.x(), pt.y());
                        [wx, wy]
                    })
                    .collect();
            if coords.is_empty() {
                return (GeomType::Point, Vec::new(), vec![]);
            }
            (GeomType::Point, vec![coords], vec![])
        }
        geo::Geometry::LineString(ls) => {
            let coords = linestring_to_world(ls);
            if coords.len() < 2 {
                return (GeomType::Line, Vec::new(), vec![]);
            }
            (GeomType::Line, vec![coords], vec![])
        }
        geo::Geometry::MultiLineString(mls) => {
            let sets: Vec<Vec<[f64; 2]>> = mls
                .0
                .iter()
                .map(linestring_to_world)
                .filter(|c| c.len() >= 2)
                .collect();
            (GeomType::Line, sets, vec![])
        }
        geo::Geometry::Polygon(poly) => {
            let rings = polygon_rings_to_world(poly);
            if rings.is_empty() {
                return (GeomType::Polygon, Vec::new(), vec![]);
            }
            (GeomType::Polygon, rings, vec![0])
        }
        geo::Geometry::MultiPolygon(mp) => {
            let mut all_rings = Vec::with_capacity(mp.0.len());
            let mut exterior_indices = Vec::with_capacity(mp.0.len());
            for poly in &mp.0 {
                let rings = polygon_rings_to_world(poly);
                if !rings.is_empty() {
                    exterior_indices.push(all_rings.len());
                    all_rings.extend(rings);
                }
            }
            (GeomType::Polygon, all_rings, exterior_indices)
        }
        _ => {
            tracing::trace!("Unsupported geometry type, skipping");
            (GeomType::Point, Vec::new(), vec![])
        }
    }
}

/// Convert a geo `LineString` to world [0,1] coordinate array.
fn linestring_to_world(ls: &LineString<f64>) -> Vec<[f64; 2]> {
    ls.0.iter()
        .map(|c| {
            let (wx, wy) = mercator::wgs84_to_world(c.x, c.y);
            [wx, wy]
        })
        .collect()
}

/// Convert a single polygon ring (`LineString`) to world [0,1] coordinate array.
fn ring_to_world(ring: &LineString<f64>) -> Vec<[f64; 2]> {
    ring.0
        .iter()
        .map(|c| {
            let (wx, wy) = mercator::wgs84_to_world(c.x, c.y);
            [wx, wy]
        })
        .collect()
}

/// Convert all rings of a Polygon to world [0,1] coordinate arrays.
///
/// Returns exterior ring first, then interior rings. Only includes rings
/// with ≥ 4 points. If the exterior ring is degenerate, returns empty.
fn polygon_rings_to_world(poly: &Polygon<f64>) -> Vec<Vec<[f64; 2]>> {
    let mut rings = Vec::with_capacity(1 + poly.interiors().len());
    let exterior = ring_to_world(poly.exterior());
    if exterior.len() >= 4 {
        rings.push(exterior);
        for interior in poly.interiors() {
            let ring = ring_to_world(interior);
            if ring.len() >= 4 {
                rings.push(ring);
            }
        }
    }
    rings
}

/// Compute 2× signed area of a polygon ring in integer tile coordinates.
///
/// Negative = clockwise in screen space (Y-down), positive = counter-clockwise.
/// Uses the shoelace formula without division to stay in integer arithmetic.
#[must_use]
fn signed_area_2x(coords: &[(i32, i32)]) -> i64 {
    let n = coords.len();
    if n < 3 {
        return 0;
    }
    let mut area: i64 = 0;
    for i in 0..n {
        let (x1, y1) = coords[i];
        let (x2, y2) = coords[(i + 1) % n];
        area += (x2 as i64 - x1 as i64) * (y2 as i64 + y1 as i64);
    }
    area
}

/// Ensure a polygon ring has the specified winding order.
///
/// If `clockwise` is true, ensures CW (negative signed area in screen space).
/// If false, ensures CCW (positive signed area). Reverses in-place if needed.
fn ensure_ring_winding(coords: &mut [(i32, i32)], clockwise: bool) {
    let area = signed_area_2x(coords);
    if (clockwise && area > 0) || (!clockwise && area < 0) {
        coords.reverse();
    }
}

/// Group a flat ring list into polygons, each `(exterior, interiors)`.
///
/// Interior rings (holes) attach to the most recent exterior ring. Leading
/// holes with no preceding exterior are dropped — a hole with no exterior is
/// not a valid polygon and would otherwise render as a spurious fill.
type RingGroups = Vec<(Vec<[f64; 2]>, Vec<Vec<[f64; 2]>>)>;

fn group_rings_into_polygons(rings: &[Vec<[f64; 2]>], is_exterior: &[bool]) -> RingGroups {
    let mut groups: RingGroups = Vec::new();
    for (ring, &is_ext) in rings.iter().zip(is_exterior.iter()) {
        if is_ext {
            groups.push((ring.clone(), Vec::new()));
        } else if let Some(last) = groups.last_mut() {
            last.1.push(ring.clone());
        }
    }
    groups
}

/// Encode one tile's clipped ring group into MVT polygon commands.
///
/// `rings_data` is `(is_exterior, snapped_ring)` per ring. Rings clip to tiles
/// independently, so a hole can land in a tile whose exterior ring's piece was
/// dropped, leaving a group of only holes. A lone interior ring is invalid MVT
/// and gets nonzero-FILLED by renderers (the z2 phantom-landmass triangle over
/// the South Pacific), so a group with no exterior ring is rejected (`None`).
/// Each kept ring is wound per the MVT spec (exterior CW, interior CCW, Y-down).
fn encode_tile_ring_group(rings_data: &[(bool, Vec<(i32, i32)>)]) -> Option<Vec<u32>> {
    if !rings_data.iter().any(|(is_ext, _)| *is_ext) {
        return None;
    }

    let mut encoded_rings: Vec<Vec<(i32, i32)>> = Vec::with_capacity(rings_data.len());
    for (is_ext, ring) in rings_data {
        let mut ring = ring.clone();
        ensure_ring_winding(&mut ring, *is_ext);
        encoded_rings.push(ring);
    }

    let cmds = mvt::encode_polygon(&encoded_rings);
    if cmds.is_empty() { None } else { Some(cmds) }
}

/// Encode snapped integer coords into MVT geometry commands.
///
/// For single-ring polygons, normalizes winding order to CW (exterior).
fn encode_geometry(geom_type: GeomType, coords: &[(i32, i32)]) -> Vec<u32> {
    match geom_type {
        GeomType::Point => mvt::encode_points(coords),
        GeomType::Line => mvt::encode_linestring(coords),
        GeomType::Polygon => {
            let mut ring = coords.to_vec();
            ensure_ring_winding(&mut ring, true);
            mvt::encode_polygon(&[ring])
        }
        _ => Vec::new(),
    }
}

/// Encode and write a complete tile (all features for one `tile_id`).
#[cfg(test)]
fn flush_tile(
    writer: &mut PmtilesWriter,
    tile_key: (u8, u64),
    features: &[TileFeature],
) -> Result<()> {
    let (z, tid) = tile_key;
    let (x, y) = sort_key::tile_id_to_xy(tid, z);

    let mvt_bytes = mvt::encode_tile(features);

    // Gzip compress
    let mut encoder = GzEncoder::new(Vec::with_capacity(mvt_bytes.len()), Compression::fast());
    encoder.write_all(&mvt_bytes)?;
    let compressed = encoder.finish()?;

    let tile = TileCoord::new(z, x, y);
    let pmtiles_id = hilbert::tile_to_pmtiles_id(tile);
    writer.write_tile(pmtiles_id, &compressed)?;

    Ok(())
}

/// Encode and write a batch of complete tiles.
///
/// MVT protobuf encoding and gzip compression run in parallel across
/// rayon's thread pool. Compressed tiles are then written sequentially
/// to the `PMTiles` file to maintain Hilbert order.
///
/// Returns the number of tiles written.
fn flush_batch(
    writer: &mut PmtilesWriter,
    batch: &mut Vec<PendingTile>,
    use_mlt: bool,
) -> Result<u64> {
    let encoded: Vec<EncodedTile> = batch
        .par_drain(..)
        .map(|tile| {
            let (z, tid) = tile.tile_key;
            let (x, y) = sort_key::tile_id_to_xy(tid, z);
            // The per-tile merge runs `geo` boolean operations. A tile cannot
            // be skipped (the archive would have a hole), so a panic here
            // fails the build and names the tile.
            let features = guard::catch("merge tile features", || {
                crate::tile::postprocess::postprocess_tile(tile.features, z)
            })
            .ok_or(TilesError::TileMerge { z, x, y })?;
            let tile_bytes = if use_mlt {
                crate::mlt::encode_tile(&features).map_err(|e| TilesError::TileEncode {
                    z,
                    x,
                    y,
                    source: Box::new(e),
                })?
            } else {
                let mvt_bytes = mvt::encode_tile(&features);
                let mut encoder =
                    GzEncoder::new(Vec::with_capacity(mvt_bytes.len()), Compression::fast());
                encoder.write_all(&mvt_bytes)?;
                encoder.finish()?
            };

            let tile_coord = TileCoord::new(z, x, y);
            let pmtiles_id = hilbert::tile_to_pmtiles_id(tile_coord);

            Ok(EncodedTile {
                pmtiles_id,
                compressed: tile_bytes,
            })
        })
        .collect::<Result<Vec<_>>>()?;

    let count = encoded.len() as u64;

    for tile in &encoded {
        writer.write_tile(tile.pmtiles_id, &tile.compressed)?;
    }

    batch.clear();
    Ok(count)
}

/// Build `PMTiles` metadata JSON (`TileJSON`) for protomaps basemap schema.
///
/// Generates a complete `TileJSON` metadata object with:
/// - Per-layer field declarations (name → type mapping)
/// - Per-layer `minzoom` / `maxzoom` values
/// - Attribution for data sources (OSM, Overture, Natural Earth)
/// - Generator identification
fn build_metadata(
    max_zoom: u8,
    use_mlt: bool,
    sources: geolith::attribution::DataSources,
) -> serde_json::Result<String> {
    use serde_json::{Map, Value, json};

    /// Build a single `vector_layer` entry with field declarations.
    fn layer_desc(id: &str, min_zoom: u8, max_zoom: u8, fields: &[(&str, &str)]) -> Value {
        let mut field_map = Map::new();
        for &(name, ty) in fields {
            field_map.insert(name.to_string(), Value::String(ty.to_string()));
        }
        json!({
            "id": id,
            "fields": Value::Object(field_map),
            "minzoom": min_zoom,
            "maxzoom": max_zoom,
        })
    }

    // Layer field declarations — sorted alphabetically to match Planetiler output.
    // Field types follow TileJSON spec: "String", "Number", "Boolean".
    // Transit features emit into the "roads" layer, so no separate transit entry.
    let vector_layers = vec![
        layer_desc(
            "bathymetry",
            0,
            max_zoom,
            &[("kind", "String"), ("depth", "Number")],
        ),
        layer_desc(
            "boundaries",
            0,
            max_zoom,
            &[
                ("kind", "String"),
                ("kind_detail", "Number"),
                ("disputed", "Boolean"),
                ("disputed_by", "String"),
                ("claimed_by", "String"),
                ("name", "String"),
            ],
        ),
        layer_desc(
            "buildings",
            11,
            max_zoom,
            &[
                ("kind", "String"),
                ("height", "Number"),
                ("name", "String"),
                ("addr_housenumber", "String"),
                ("addr_street", "String"),
            ],
        ),
        layer_desc(
            "earth",
            0,
            max_zoom,
            &[("kind", "String"), ("name", "String")],
        ),
        layer_desc(
            "landcover",
            0,
            max_zoom,
            &[("kind", "String"), ("sort_key", "Number")],
        ),
        layer_desc(
            "landuse",
            4,
            max_zoom,
            &[("kind", "String"), ("name", "String")],
        ),
        layer_desc(
            "places",
            5,
            max_zoom,
            &[
                ("kind", "String"),
                ("kind_detail", "String"),
                ("name", "String"),
                ("population", "Number"),
                ("population_rank", "Number"),
                ("capital", "String"),
                ("wikidata", "String"),
                ("class", "String"),
                ("min_zoom", "Number"),
            ],
        ),
        layer_desc(
            "pois",
            10,
            max_zoom,
            &[
                ("kind", "String"),
                ("kind_detail", "String"),
                ("name", "String"),
                ("confidence", "Number"),
                ("min_zoom", "Number"),
                ("elevation", "Number"),
                ("iata", "String"),
                ("religion", "String"),
                ("sport", "String"),
                ("cuisine", "String"),
            ],
        ),
        layer_desc(
            "roads",
            3,
            max_zoom,
            &[
                ("kind", "String"),
                ("kind_detail", "String"),
                ("name", "String"),
                ("ref", "String"),
                ("network", "String"),
                ("shield_text", "String"),
                ("network_1", "String"),
                ("shield_text_1", "String"),
                ("network_2", "String"),
                ("shield_text_2", "String"),
                ("network_3", "String"),
                ("shield_text_3", "String"),
                ("network_4", "String"),
                ("shield_text_4", "String"),
                ("network_5", "String"),
                ("shield_text_5", "String"),
                ("network_6", "String"),
                ("shield_text_6", "String"),
                ("is_bridge", "Boolean"),
                ("is_tunnel", "Boolean"),
                ("is_link", "Boolean"),
                ("oneway", "String"),
                ("sort_rank", "Number"),
                ("min_zoom", "Number"),
            ],
        ),
        layer_desc(
            "water",
            0,
            max_zoom,
            &[
                ("kind", "String"),
                ("kind_detail", "String"),
                ("name", "String"),
            ],
        ),
    ];

    // The OSM credit is a link here (a TileJSON attribution is HTML); the
    // credits of the other data the build read follow, the way the docs write
    // the line users show.
    let attribution = geolith::attribution::with_credit(
        &geolith::attribution::data_credit_with_osm(
            sources,
            r#"<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors (ODbL)</a>"#,
        ),
    );

    let mut metadata = json!({
        "name": "geolith",
        "description": "Basemap layers derived from OpenStreetMap, Overture Maps, and Natural Earth",
        "version": env!("CARGO_PKG_VERSION"),
        "type": "baselayer",
        "format": "pbf",
        "minzoom": "0",
        "maxzoom": max_zoom.to_string(),
        "generator": format!("geolith v{}", env!("CARGO_PKG_VERSION")),
        "attribution": attribution,
        "vector_layers": vector_layers,
    });

    if use_mlt {
        metadata["encoding"] = json!("mlt");
    }

    // serde_json::to_string produces compact JSON (no extra whitespace),
    // which is optimal for gzip-compressed PMTiles metadata.
    serde_json::to_string(&metadata)
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::layers::Layer;
    use crate::source::input::DataSource;
    use crate::tile::feature::PropValue;
    use geo::{Coord, MultiLineString, MultiPoint, Point};

    #[test]
    fn find_shp_file_picks_the_first_shapefile_by_path() {
        let dir = tempfile::tempdir().expect("tmp");
        for name in ["water_b.shp", "water_a.dbf", "water_c.shp", "water_a.shp"] {
            std::fs::write(dir.path().join(name), b"").expect("write");
        }
        let found = find_shp_file(dir.path()).expect("a shapefile exists");
        assert_eq!(found, dir.path().join("water_a.shp"));
    }

    #[test]
    fn find_shp_file_reports_a_directory_without_shapefiles() {
        let dir = tempfile::tempdir().expect("tmp");
        std::fs::write(dir.path().join("water.dbf"), b"").expect("write");
        let err = find_shp_file(dir.path()).expect_err("no .shp");
        assert!(format!("{err}").contains("No .shp file"), "{err}");
    }

    fn config_with_roads(source: &str) -> TilesConfig {
        let mut config = TilesConfig::new(
            "/tmp/data",
            "/tmp/ne.sqlite",
            "/tmp/water",
            "/tmp/land",
            "/tmp/out.pmtiles",
        );
        config.roads_source = source.to_owned();
        config
    }

    /// The Overture emitter drops a country line inside the Survey of India
    /// land and keeps one outside it (the Line of Control case).
    #[test]
    fn overture_emitter_masks_country_lines_inside_india() {
        let _shared = guard_state()
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let config = config_with_roads("overture");
        assert!(config.overture_enabled(Layer::Boundaries));
        let ring = geo::LineString::from(vec![
            (74.0, 32.0),
            (78.0, 32.0),
            (78.0, 36.0),
            (74.0, 36.0),
            (74.0, 32.0),
        ]);
        let soi = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::MultiLineString(MultiLineString::new(vec![
                ring,
            ]))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        let mask = IndiaMask::from_features(&[soi]).expect("closed ring");
        let country_line = |coords: Vec<(f64, f64)>| {
            let mut properties = HashMap::new();
            properties.insert("subtype".to_string(), PropValue::Str("country".into()));
            InputFeature {
                id: 9,
                geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(coords))),
                properties,
                bbox: None,
                source: DataSource::Overture {
                    theme: "divisions".into(),
                    otype: "division_boundary".into(),
                },
            }
        };
        let emitted = |feature: &InputFeature| {
            let features_processed = AtomicU64::new(0);
            let tiles_emitted = AtomicU64::new(0);
            let layer_features: Vec<AtomicU64> = (0..11).map(|_| AtomicU64::new(0)).collect();
            let layer_tiles: Vec<AtomicU64> = (0..11).map(|_| AtomicU64::new(0)).collect();
            let emitter = OvertureEmitter {
                config: &config,
                max_zoom: 8,
                tile_bounds: None,
                india_mask: Some(&mask),
                features_processed: &features_processed,
                tiles_emitted: &tiles_emitted,
                layer_features: &layer_features,
                layer_tiles: &layer_tiles,
            };
            let dir = tempfile::tempdir().expect("tempdir");
            let mut buffer = SortBuffer::with_max_bytes(64 * 1024 * 1024);
            let mut sink =
                ChunkSink::with_counter(dir.path().to_path_buf(), Arc::new(AtomicU32::new(0)));
            emitter
                .emit(feature, &[Layer::Boundaries], &mut buffer, &mut sink)
                .expect("emit");
            layer_features[Layer::Boundaries as usize].load(Ordering::Relaxed)
        };
        // Inside the square (a Line of Control): gone.
        assert_eq!(emitted(&country_line(vec![(75.0, 33.0), (77.0, 35.0)])), 0);
        // Outside it (the Pakistan-Afghanistan line): kept.
        assert_eq!(emitted(&country_line(vec![(66.0, 30.0), (70.0, 34.0)])), 1);
    }

    /// A primary road near London with a bridge on its middle 20%-50%.
    fn partially_bridged_road() -> InputFeature {
        let mut properties = HashMap::new();
        properties.insert("subtype".to_string(), PropValue::Str("road".into()));
        properties.insert("class".to_string(), PropValue::Str("primary".into()));
        properties.insert(
            "road_flags.is_bridge".to_string(),
            PropValue::Str("0.2:0.5".into()),
        );
        InputFeature {
            id: 7,
            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
                (-0.10, 51.50),
                (-0.09, 51.50),
            ]))),
            properties,
            bbox: None,
            source: DataSource::Overture {
                theme: "transportation".into(),
                otype: "segment".into(),
            },
        }
    }

    struct EmitRun {
        features: u64,
        tiles: u64,
        roads_features: u64,
        roads_tiles: u64,
        buffered: usize,
    }

    fn run_emitter(config: &TilesConfig, feature: &InputFeature) -> EmitRun {
        let dir = tempfile::tempdir().expect("tempdir");
        let (run, result) =
            run_emitter_into(config, feature, dir.path().to_path_buf(), 64 * 1024 * 1024);
        result.expect("emit");
        run
    }

    fn run_emitter_into(
        config: &TilesConfig,
        feature: &InputFeature,
        chunk_dir: PathBuf,
        buffer_bytes: usize,
    ) -> (EmitRun, Result<()>) {
        let features_processed = AtomicU64::new(0);
        let tiles_emitted = AtomicU64::new(0);
        let layer_features: Vec<AtomicU64> = (0..11).map(|_| AtomicU64::new(0)).collect();
        let layer_tiles: Vec<AtomicU64> = (0..11).map(|_| AtomicU64::new(0)).collect();
        let emitter = OvertureEmitter {
            config,
            max_zoom: 14,
            tile_bounds: None,
            india_mask: None,
            features_processed: &features_processed,
            tiles_emitted: &tiles_emitted,
            layer_features: &layer_features,
            layer_tiles: &layer_tiles,
        };
        let mut buffer = SortBuffer::with_max_bytes(buffer_bytes);
        let mut sink = ChunkSink::with_counter(chunk_dir, Arc::new(AtomicU32::new(0)));
        let result = emitter.emit(feature, &[Layer::Roads], &mut buffer, &mut sink);
        let run = EmitRun {
            features: features_processed.load(Ordering::Relaxed),
            tiles: tiles_emitted.load(Ordering::Relaxed),
            roads_features: layer_features[Layer::Roads as usize].load(Ordering::Relaxed),
            roads_tiles: layer_tiles[Layer::Roads as usize].load(Ordering::Relaxed),
            buffered: buffer.len(),
        };
        (run, result)
    }

    /// The bridge splits the road into three pieces, and all three are
    /// counted and emitted into the roads layer.
    #[test]
    fn overture_emitter_emits_every_piece_of_a_split_road() {
        let _shared = guard_state()
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let run = run_emitter(&config_with_roads("overture"), &partially_bridged_road());
        assert_eq!(run.features, 3);
        assert_eq!(run.roads_features, 3);
        assert!(run.tiles > 0);
        assert_eq!(run.roads_tiles, run.tiles);
        assert_eq!(run.buffered as u64, run.tiles);
    }

    /// A chunk write that fails (here: the chunk directory does not exist)
    /// stops the emit with an error that names the path. Going on would
    /// leave the tiles of the feature out of the archive without a trace.
    #[test]
    fn overture_emitter_stops_when_a_chunk_write_fails() {
        let _shared = guard_state()
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let dir = tempfile::tempdir().expect("tempdir");
        let missing = dir.path().join("does-not-exist");
        let (run, result) = run_emitter_into(
            &config_with_roads("overture"),
            &partially_bridged_road(),
            missing.clone(),
            1,
        );
        let err = result.expect_err("a failed chunk write is an error");
        let TilesError::SortRun(crate::sort::error::SortRunError::Io { op, path, .. }) = &err
        else {
            panic!("expected a sort run I/O error, got {err}");
        };
        assert_eq!(*op, "create");
        assert!(path.starts_with(&missing), "{}", path.display());
        assert!(err.to_string().contains("does-not-exist"), "{err}");
        assert_eq!(run.features, 1, "the emit stopped at the first piece");
        assert!(!missing.exists(), "no chunk directory was created");
    }

    /// The callback readers park their first error in `Failure`; it comes out
    /// once, whatever follows, and a clean run comes out clean.
    #[test]
    fn a_callback_failure_keeps_the_first_error() {
        let mut clean = Failure::default();
        clean.record(Ok(()));
        assert!(!clean.is_set());
        assert!(clean.finish().is_ok());

        let mut failure = Failure::default();
        failure.record(Err(TilesError::NothingToWrite));
        assert!(failure.is_set());
        failure.record(Err(TilesError::NoShapefile {
            path: PathBuf::from("later"),
        }));
        failure.record(Ok(()));
        assert!(matches!(failure.finish(), Err(TilesError::NothingToWrite)));
    }

    #[test]
    fn overture_emitter_skips_layers_not_sourced_from_overture() {
        let _shared = guard_state()
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let run = run_emitter(&config_with_roads("osm"), &partially_bridged_road());
        assert_eq!(run.features, 0);
        assert_eq!(run.tiles, 0);
        assert_eq!(run.buffered, 0);
    }

    #[test]
    fn point_to_world_coords() {
        let pt = geo::Geometry::Point(Point::new(0.0, 0.0));
        let (gt, coords, _) = geometry_to_world_coords(&pt);
        assert_eq!(gt, GeomType::Point);
        assert_eq!(coords.len(), 1);
        assert!((coords[0][0][0] - 0.5).abs() < 1e-6);
        assert!((coords[0][0][1] - 0.5).abs() < 1e-6);
    }

    #[test]
    fn linestring_to_world_coords() {
        let ls = geo::Geometry::LineString(LineString::new(vec![
            Coord { x: -180.0, y: 0.0 },
            Coord { x: 180.0, y: 0.0 },
        ]));
        let (gt, coords, _) = geometry_to_world_coords(&ls);
        assert_eq!(gt, GeomType::Line);
        assert_eq!(coords.len(), 1);
        assert_eq!(coords[0].len(), 2);
    }

    #[test]
    fn polygon_to_world_coords_closed_ring() {
        let poly = geo::Geometry::Polygon(Polygon::new(
            LineString::new(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 10.0, y: 0.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 0.0, y: 10.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![],
        ));
        let (gt, coords, _) = geometry_to_world_coords(&poly);
        assert_eq!(gt, GeomType::Polygon);
        assert_eq!(coords.len(), 1);
        assert_eq!(coords[0].len(), 5);
    }

    #[test]
    fn empty_multipoint_returns_empty() {
        let mp = geo::Geometry::MultiPoint(MultiPoint(vec![]));
        let (_, coords, _) = geometry_to_world_coords(&mp);
        assert!(coords.is_empty());
    }

    #[test]
    fn multilinestring_filters_short_lines() {
        let mls = geo::Geometry::MultiLineString(MultiLineString::new(vec![
            LineString::new(vec![Coord { x: 0.0, y: 0.0 }]),
            LineString::new(vec![Coord { x: 0.0, y: 0.0 }, Coord { x: 1.0, y: 1.0 }]),
        ]));
        let (gt, coords, _) = geometry_to_world_coords(&mls);
        assert_eq!(gt, GeomType::Line);
        assert_eq!(coords.len(), 1);
    }

    #[test]
    fn ring_to_world_converts_coords() {
        let ring = LineString::new(vec![
            Coord { x: 0.0, y: 0.0 },
            Coord { x: 10.0, y: 0.0 },
            Coord { x: 10.0, y: 10.0 },
            Coord { x: 0.0, y: 0.0 },
        ]);
        let world = ring_to_world(&ring);
        assert_eq!(world.len(), 4);
        // (0,0) in WGS84 → (0.5, 0.5) in world space
        assert!((world[0][0] - 0.5).abs() < 1e-6);
        assert!((world[0][1] - 0.5).abs() < 1e-6);
    }

    #[test]
    fn polygon_rings_to_world_exterior_only() {
        let poly = Polygon::new(
            LineString::new(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 10.0, y: 0.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 0.0, y: 10.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![],
        );
        let rings = polygon_rings_to_world(&poly);
        assert_eq!(rings.len(), 1); // exterior only
        assert_eq!(rings[0].len(), 5);
    }

    #[test]
    fn polygon_rings_to_world_with_hole() {
        let poly = Polygon::new(
            LineString::new(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 20.0, y: 0.0 },
                Coord { x: 20.0, y: 20.0 },
                Coord { x: 0.0, y: 20.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![LineString::new(vec![
                Coord { x: 5.0, y: 5.0 },
                Coord { x: 10.0, y: 5.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 5.0, y: 10.0 },
                Coord { x: 5.0, y: 5.0 },
            ])],
        );
        let rings = polygon_rings_to_world(&poly);
        assert_eq!(rings.len(), 2); // exterior + 1 interior
        assert_eq!(rings[0].len(), 5);
        assert_eq!(rings[1].len(), 5);
    }

    #[test]
    fn polygon_rings_to_world_degenerate_interior_skipped() {
        let poly = Polygon::new(
            LineString::new(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 10.0, y: 0.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 0.0, y: 10.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            // Interior ring with only 3 points (degenerate — needs ≥4)
            vec![LineString::new(vec![
                Coord { x: 2.0, y: 2.0 },
                Coord { x: 5.0, y: 2.0 },
                Coord { x: 2.0, y: 2.0 },
            ])],
        );
        let rings = polygon_rings_to_world(&poly);
        assert_eq!(rings.len(), 1); // degenerate interior dropped
    }

    #[test]
    fn signed_area_2x_degenerate() {
        assert_eq!(signed_area_2x(&[]), 0);
        assert_eq!(signed_area_2x(&[(0, 0)]), 0);
        assert_eq!(signed_area_2x(&[(0, 0), (1, 1)]), 0);
    }

    #[test]
    fn ring_group_rewinds_exterior_cw_and_hole_ccw() {
        // Exterior given CCW and hole given CW (Y down), so both are reversed.
        // Expected commands by hand from the MVT 2.1 spec: MoveTo(1) = 9,
        // LineTo(3) = 26, ClosePath(1) = 15, zigzag deltas from the cursor.
        let exterior = vec![(0, 0), (0, 100), (100, 100), (100, 0)];
        let hole = vec![(25, 25), (75, 25), (75, 75), (25, 75)];
        let group = vec![(true, exterior), (false, hole)];
        assert_eq!(
            encode_tile_ring_group(&group),
            Some(vec![
                9, 200, 0, 26, 0, 200, 199, 0, 0, 199, 15, // (100,0) (100,100) (0,100) (0,0)
                9, 50, 150, 26, 100, 0, 0, 99, 99, 0, 15, // (25,75) (75,75) (75,25) (25,25)
            ])
        );
    }

    #[test]
    fn ring_group_holes_only_is_dropped() {
        // Regression: a clipped hole landing in a tile without its exterior ring
        // must NOT be emitted — a lone interior ring is nonzero-filled by
        // MapLibre into a phantom landmass (the z2 South-Pacific triangle).
        let hole_a = vec![(10, 10), (10, 50), (50, 50), (50, 10)];
        let hole_b = vec![(60, 60), (60, 90), (90, 90), (90, 60)];
        let group = vec![(false, hole_a), (false, hole_b)];
        assert!(
            encode_tile_ring_group(&group).is_none(),
            "ring group with no exterior ring must be dropped"
        );
    }

    #[test]
    fn ensure_ring_winding_makes_cw() {
        // Start CCW (positive area)
        let mut ccw = vec![(0, 0), (0, 100), (100, 100), (100, 0)];
        assert!(signed_area_2x(&ccw) > 0);
        ensure_ring_winding(&mut ccw, true);
        assert!(signed_area_2x(&ccw) < 0);
    }

    #[test]
    fn ensure_ring_winding_makes_ccw() {
        // Start CW (negative area)
        let mut cw = vec![(0, 0), (100, 0), (100, 100), (0, 100)];
        assert!(signed_area_2x(&cw) < 0);
        ensure_ring_winding(&mut cw, false);
        assert!(signed_area_2x(&cw) > 0);
    }

    #[test]
    fn ensure_ring_winding_noop_if_correct() {
        let mut cw = vec![(0, 0), (100, 0), (100, 100), (0, 100)];
        let original = cw.clone();
        ensure_ring_winding(&mut cw, true);
        assert_eq!(cw, original); // already CW, no change needed
    }

    #[test]
    fn geometry_to_world_coords_polygon_with_hole() {
        let poly = geo::Geometry::Polygon(Polygon::new(
            LineString::new(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 20.0, y: 0.0 },
                Coord { x: 20.0, y: 20.0 },
                Coord { x: 0.0, y: 20.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![LineString::new(vec![
                Coord { x: 5.0, y: 5.0 },
                Coord { x: 10.0, y: 5.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 5.0, y: 10.0 },
                Coord { x: 5.0, y: 5.0 },
            ])],
        ));
        let (gt, coords, ext_idx) = geometry_to_world_coords(&poly);
        assert_eq!(gt, GeomType::Polygon);
        assert_eq!(coords.len(), 2); // exterior + interior
        assert_eq!(ext_idx, vec![0]); // only index 0 is exterior
    }

    #[test]
    fn geometry_to_world_coords_multipolygon_with_holes() {
        let mp = geo::Geometry::MultiPolygon(geo::MultiPolygon::new(vec![
            Polygon::new(
                LineString::new(vec![
                    Coord { x: 0.0, y: 0.0 },
                    Coord { x: 10.0, y: 0.0 },
                    Coord { x: 10.0, y: 10.0 },
                    Coord { x: 0.0, y: 10.0 },
                    Coord { x: 0.0, y: 0.0 },
                ]),
                vec![],
            ),
            Polygon::new(
                LineString::new(vec![
                    Coord { x: 20.0, y: 0.0 },
                    Coord { x: 30.0, y: 0.0 },
                    Coord { x: 30.0, y: 10.0 },
                    Coord { x: 20.0, y: 10.0 },
                    Coord { x: 20.0, y: 0.0 },
                ]),
                vec![LineString::new(vec![
                    Coord { x: 22.0, y: 2.0 },
                    Coord { x: 28.0, y: 2.0 },
                    Coord { x: 28.0, y: 8.0 },
                    Coord { x: 22.0, y: 8.0 },
                    Coord { x: 22.0, y: 2.0 },
                ])],
            ),
        ]));
        let (gt, coords, ext_idx) = geometry_to_world_coords(&mp);
        assert_eq!(gt, GeomType::Polygon);
        // poly1: 1 ring, poly2: 2 rings = 3 total
        assert_eq!(coords.len(), 3);
        // Exterior indices: ring 0 (poly1 ext), ring 1 (poly2 ext)
        assert_eq!(ext_idx, vec![0, 1]);
    }

    #[test]
    fn encode_point_geometry_is_one_move_to() {
        // MoveTo(1) = 9, zigzag(100) = 200, zigzag(200) = 400 (MVT 2.1 spec).
        assert_eq!(
            encode_geometry(GeomType::Point, &[(100, 200)]),
            vec![9, 200, 400]
        );
    }

    #[test]
    fn encode_line_geometry_is_move_to_then_line_to() {
        // MoveTo(1) = 9, LineTo(1) = 10 (MVT 2.1 spec).
        assert_eq!(
            encode_geometry(GeomType::Line, &[(0, 0), (100, 100)]),
            vec![9, 0, 0, 10, 200, 200]
        );
    }

    #[test]
    fn encode_polygon_geometry_winds_a_ccw_ring_clockwise() {
        // Given CCW (Y down), written CW: (0,0) (100,0) (100,100) (0,100), with
        // the closing point left to ClosePath(1) = 15; LineTo(3) = 26.
        assert_eq!(
            encode_geometry(
                GeomType::Polygon,
                &[(0, 0), (0, 100), (100, 100), (100, 0), (0, 0)],
            ),
            vec![9, 0, 0, 26, 200, 0, 0, 200, 199, 0, 15]
        );
    }

    #[test]
    fn metadata_json_valid() {
        let meta = build_metadata(
            15,
            false,
            geolith::attribution::DataSources::new(true, true, false),
        )
        .unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&meta).expect("metadata must be valid JSON");

        // Top-level fields
        assert_eq!(parsed["name"], "geolith");
        assert_eq!(parsed["type"], "baselayer");
        assert_eq!(parsed["format"], "pbf");
        assert_eq!(parsed["minzoom"], "0");
        assert_eq!(parsed["maxzoom"], "15");
        let attribution = parsed["attribution"].as_str().unwrap();
        assert_eq!(
            attribution,
            "<a href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\">&copy; OpenStreetMap contributors (ODbL)</a>, Overture Maps Foundation | © geolith"
        );
        assert!(
            parsed["attribution"]
                .as_str()
                .unwrap()
                .contains("openstreetmap.org")
        );
        assert!(
            parsed["generator"]
                .as_str()
                .unwrap()
                .starts_with("geolith v")
        );
        assert!(
            parsed["description"]
                .as_str()
                .unwrap()
                .contains("OpenStreetMap")
        );

        // Vector layers
        let layers = parsed["vector_layers"]
            .as_array()
            .expect("vector_layers must be array");
        assert_eq!(layers.len(), 10); // 11 internal layers minus transit

        // Layers must be alphabetically sorted
        let ids: Vec<&str> = layers.iter().map(|l| l["id"].as_str().unwrap()).collect();
        assert_eq!(
            ids,
            vec![
                "bathymetry",
                "boundaries",
                "buildings",
                "earth",
                "landcover",
                "landuse",
                "places",
                "pois",
                "roads",
                "water"
            ]
        );

        // Transit features go into "roads" layer — no separate "transit" entry
        assert!(!ids.contains(&"transit"));

        // Per-layer field declarations are populated (not empty)
        for layer in layers {
            let fields = layer["fields"].as_object().expect("fields must be object");
            assert!(
                !fields.is_empty(),
                "layer {} must have field declarations",
                layer["id"]
            );
            // Every layer declares a "kind" field
            assert!(
                fields.contains_key("kind"),
                "layer {} must declare kind field",
                layer["id"]
            );
        }

        // Per-layer minzoom values
        let buildings = layers.iter().find(|l| l["id"] == "buildings").unwrap();
        assert_eq!(buildings["minzoom"], 11);
        let roads = layers.iter().find(|l| l["id"] == "roads").unwrap();
        assert_eq!(roads["minzoom"], 3);
        let earth = layers.iter().find(|l| l["id"] == "earth").unwrap();
        assert_eq!(earth["minzoom"], 0);

        // Roads layer declares bridge/tunnel/ref fields
        let road_fields = roads["fields"].as_object().unwrap();
        assert!(road_fields.contains_key("is_bridge"));
        assert!(road_fields.contains_key("is_tunnel"));
        assert!(road_fields.contains_key("ref"));
        assert_eq!(road_fields["is_bridge"], "Boolean");
    }

    #[test]
    fn flush_tile_produces_valid_output() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let path = tmp.path().to_owned();

        let mut writer =
            PmtilesWriter::create(&path, PmtCompression::None, TileType::Mvt, 0, 2).unwrap();

        let features = vec![TileFeature {
            layer: Layer::Buildings,
            id: 1,
            geom_type: GeomType::Polygon,
            geometry: mvt::encode_polygon(&[vec![(0, 0), (100, 0), (100, 100), (0, 100), (0, 0)]]),
            properties: Arc::new(vec![(
                "kind".to_string(),
                PropValue::Str("building".to_string()),
            )]),
            sort_key: 0,
        }];

        flush_tile(&mut writer, (0, 0), &features).unwrap();
        assert_eq!(writer.tiles_written(), 1);
    }

    #[test]
    fn dp_simplify_preserves_short_coords() {
        let coords = vec![[0.0, 0.0], [1.0, 1.0]];
        let result = dp_simplify(&coords, 0.1);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn dp_simplify_removes_collinear_points() {
        // Three collinear points — middle one should be removed
        let coords = vec![[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]];
        let result = dp_simplify(&coords, 0.01);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], [0.0, 0.0]);
        assert_eq!(result[1], [1.0, 1.0]);
    }

    #[test]
    fn dp_simplify_keeps_significant_deviation() {
        // Point deviates significantly — should be kept
        let coords = vec![[0.0, 0.0], [0.5, 1.0], [1.0, 0.0]];
        let result = dp_simplify(&coords, 0.01);
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn simplify_world_coords_filters_degenerate() {
        // A polygon ring that simplifies to < 4 points gets dropped
        let tiny_ring = vec![
            [0.5, 0.5],
            [0.5 + 1e-10, 0.5],
            [0.5 + 1e-10, 0.5 + 1e-10],
            [0.5, 0.5 + 1e-10],
            [0.5, 0.5],
        ];
        let result = simplify_world_coords(&[tiny_ring], 0, GeomType::Polygon, 0.1);
        // At zoom 0, tolerance is ~0.0039, ring extent ~1e-10 — simplified to < 4 pts
        assert!(result.is_empty());
    }

    #[test]
    fn is_below_min_area_drops_tiny_polygon() {
        let tiny = vec![vec![
            [0.5, 0.5],
            [0.5 + 1e-6, 0.5],
            [0.5 + 1e-6, 0.5 + 1e-6],
            [0.5, 0.5],
        ]];
        assert!(is_below_min_area(&tiny, 0, GeomType::Polygon, Layer::Earth));
    }

    #[test]
    fn is_below_min_area_keeps_large_polygon() {
        let big = vec![vec![
            [0.0, 0.0],
            [0.5, 0.0],
            [0.5, 0.5],
            [0.0, 0.5],
            [0.0, 0.0],
        ]];
        assert!(!is_below_min_area(&big, 0, GeomType::Polygon, Layer::Earth));
    }

    #[test]
    fn is_below_min_area_never_drops_points() {
        let pt = vec![vec![[0.5, 0.5]]];
        assert!(!is_below_min_area(&pt, 15, GeomType::Point, Layer::Earth));
    }

    #[test]
    fn landuse_area_filter_at_low_zoom() {
        // Medium polygon that passes 1px² check but fails 800px² landuse threshold
        let pixel_z0 = 1.0 / 256.0; // ~0.0039
        let side = pixel_z0 * 10.0; // 10 pixels wide → 100px² area
        let medium = vec![vec![
            [0.5, 0.5],
            [0.5 + side, 0.5],
            [0.5 + side, 0.5 + side],
            [0.5, 0.5 + side],
            [0.5, 0.5],
        ]];
        // 100px² < 800px² threshold at z0 → should be dropped for landuse
        assert!(is_below_min_area(
            &medium,
            0,
            GeomType::Polygon,
            Layer::Landuse
        ));
        // Same polygon passes for earth (threshold = 1px²)
        assert!(!is_below_min_area(
            &medium,
            0,
            GeomType::Polygon,
            Layer::Earth
        ));
    }

    #[test]
    fn reclaim_source_file_removes_the_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("part-00000.zstd.parquet");
        std::fs::write(&path, b"parquet").expect("write");

        reclaim_source_file(&path, true);

        assert!(!path.exists(), "source file must be released once read");
    }

    #[test]
    fn reclaim_source_file_keeps_the_file_when_disabled() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("part-00000.zstd.parquet");
        std::fs::write(&path, b"parquet").expect("write");

        reclaim_source_file(&path, false);

        assert!(
            path.exists(),
            "reclamation is opt-in, so the source must survive when disabled"
        );
    }

    #[test]
    fn reclaim_source_file_survives_a_failed_removal() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("not-a-file.zstd.parquet");
        std::fs::create_dir(&path).expect("create dir");

        reclaim_source_file(&path, true);

        assert!(
            path.is_dir(),
            "a failed unlink must be swallowed, never destructive and never fatal"
        );
    }

    /// The clip-failure counters and limit are process wide. A test that sets
    /// the limit takes the write lock; every test that emits features takes
    /// the read lock, so none sees a limit it did not set.
    fn guard_state() -> &'static std::sync::RwLock<()> {
        static STATE: std::sync::RwLock<()> = std::sync::RwLock::new(());
        &STATE
    }

    /// A polygon with a NaN vertex: the clipper panics on it. It is in the
    /// roads layer because that layer skips simplification; Douglas-Peucker
    /// drops a NaN vertex, and a ring that loses it has too few points to
    /// reach the clipper, so no other layer lets this ring through. It crosses
    /// the tile edge at 45 degrees east: a ring inside one stripe is not
    /// clipped at all.
    fn nan_polygon(id: u64) -> ProcessedFeature {
        ProcessedFeature {
            id,
            geometry: Arc::new(geo::Geometry::Polygon(Polygon::new(
                LineString::from(vec![
                    (40.0, 1.0),
                    (f64::NAN, 1.5),
                    (50.0, 2.0),
                    (50.0, 1.0),
                    (40.0, 1.0),
                ]),
                vec![],
            ))),
            layer: Layer::Roads,
            min_zoom: 3,
            max_zoom: 3,
            sort_rank: 0,
            properties: Vec::new(),
        }
    }

    /// Emit `feature` into a fresh sort buffer.
    fn emit_alone(feature: &ProcessedFeature) -> Result<()> {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut sink = ChunkSink::new(dir.path().join("sort")).expect("sink");
        let mut buffer = SortBuffer::with_max_bytes(1 << 20);
        emit_tile_features(feature, 3, &mut buffer, &mut sink, &AtomicU64::new(0), None)
    }

    /// A caught clipper panic skips the feature and counts it; the count is
    /// within the limit, so the build goes on. One feature more than the
    /// limit stops it, and the error names the first failure.
    #[test]
    fn a_feature_whose_clip_panics_is_counted_and_the_limit_stops_the_build() {
        let _exclusive = guard_state()
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard::begin_build(1);
        emit_alone(&nan_polygon(11)).expect("one failed feature is within the limit of one");
        assert_eq!(guard::build_failures(), 1);

        let err = emit_alone(&nan_polygon(12)).expect_err("the second one passes the limit");
        match &err {
            TilesError::GeometryFailures {
                count,
                allowed,
                first,
            } => {
                assert_eq!((*count, *allowed), (2, 1));
                assert!(first.contains("feature 11"), "{first}");
                assert!(first.contains("roads"), "{first}");
            }
            other => panic!("wrong error: {other}"),
        }
        assert!(err.to_string().contains("2 features"), "{err}");
        guard::begin_build(u64::MAX);
    }

    #[test]
    fn a_source_is_reclaimed_only_when_it_gave_features_and_lost_none() {
        let read = |features, skipped_wkb| reader::ReadReport {
            features,
            skipped_wkb,
        };
        assert!(source_is_safe_to_reclaim(&read(10, 0)));
        assert!(!source_is_safe_to_reclaim(&read(0, 0)), "zero features");
        assert!(
            !source_is_safe_to_reclaim(&read(10, 1)),
            "a skipped geometry"
        );
        assert!(!source_is_safe_to_reclaim(&read(0, 5)));
    }

    /// `--threads` used to build rayon's global pool, which exists once per
    /// process: a second run (or an embedder's own pool) kept the first
    /// count and the error was dropped.
    #[test]
    fn each_run_gets_the_thread_count_it_asked_for() {
        assert_eq!(run_in_pool(Some(2), rayon::current_num_threads).unwrap(), 2);
        assert_eq!(run_in_pool(Some(5), rayon::current_num_threads).unwrap(), 5);
        assert_eq!(run_in_pool(Some(1), rayon::current_num_threads).unwrap(), 1);
    }

    #[test]
    fn without_a_thread_count_the_default_pool_runs_the_build() {
        let default = rayon::current_num_threads();
        assert_eq!(
            run_in_pool(None, rayon::current_num_threads).unwrap(),
            default
        );
    }

    #[test]
    fn a_panic_payload_is_named_in_the_error() {
        let handle = std::thread::spawn(|| {
            if true {
                panic!("clipper exploded on way 42");
            }
        });
        let payload = handle.join().expect_err("the thread panicked");
        assert_eq!(
            panic_message(payload.as_ref()),
            "clipper exploded on way 42"
        );
        let owned = std::thread::spawn(|| {
            if true {
                panic!("{}", String::from("formatted 7"));
            }
        })
        .join()
        .expect_err("panicked");
        assert_eq!(panic_message(owned.as_ref()), "formatted 7");
    }
}