tylertoo-core 0.7.0

Core library for converting GeoParquet to PMTiles vector tiles
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
//! Geometry clipping to tile bounds.
//!
//! Clips geometries to tile boundaries with a configurable buffer zone to prevent
//! visual seams when rendering adjacent tiles.
//!
//! # Tippecanoe Alignment
//!
//! This module matches tippecanoe's clipping behavior:
//! - **Buffer**: Default 8 pixels (configurable via `--buffer` in tippecanoe)
//!   Buffer is measured in "screen pixels" where 1 pixel = 1/256th of tile width
//! - **Clipping method**: Features are clipped to tile boundary + buffer zone
//! - **Duplication**: Features may appear in multiple tiles if they span boundaries
//! - **Algorithm**: Uses Sutherland-Hodgman for polygon clipping against axis-aligned
//!   tile boundaries (same approach as tippecanoe's clip.cpp). This is O(n) and
//!   specialized for rectangle clipping. For edge cases where S-H produces invalid
//!   output (self-intersecting polygons, U-shapes that split), we fall back to
//!   i_overlay's robust boolean operations.
//!
//! # Edge Case Handling (Issue #94)
//!
//! Sutherland-Hodgman cannot handle:
//! - Self-intersecting input polygons
//! - U-shaped polygons clipped across the opening (should produce MultiPolygon)
//! - Polygons with holes that intersect the exterior ring
//!
//! When S-H produces output with structural issues (detected via cheap O(n) checks),
//! we fall back to i_overlay which handles these cases correctly.
//!
//! See: https://github.com/felt/tippecanoe (clipping documentation)

use geo::algorithm::sweep::Intersections;
use geo::{
    BooleanOps, BoundingRect, Coord, Geometry, Line, LineString, MultiLineString, MultiPolygon,
    Point, Polygon, Rect,
};

use crate::ioverlay_clip;
use crate::sutherland_hodgman;
use crate::tile::TileBounds;

/// Default buffer in pixels (matches tippecanoe's common usage)
/// Tippecanoe default is 5, but CLAUDE.md specifies 8 for this project
pub const DEFAULT_BUFFER_PIXELS: u32 = 8;

/// Default tile extent in pixels
pub const DEFAULT_EXTENT: u32 = 4096;

// ============================================================================
// Structural Validity Checks (Issue #94)
// ============================================================================

/// Check if a polygon has structural issues that indicate clipping failure.
///
/// This performs cheap O(n) checks for problems that Sutherland-Hodgman
/// can produce when clipping invalid or complex geometries:
///
/// - **Degenerate rings**: Less than 4 vertices (minimum for valid polygon)
/// - **Duplicate consecutive vertices**: Self-touching at a point
/// - **Self-intersecting edges**: Edges that cross each other
///
/// # `assume_simple` (issue #237, RC3)
///
/// The self-intersecting-edges test (an O((n + m) log n) sweep, issue #241) runs
/// on every clip. When the caller has already established that the source
/// feature's rings are simple (no self-intersections) — computed **once per
/// feature** via [`geometry_is_simple`] — pass `assume_simple = true` to skip
/// that check here. A continental admin polygon covering thousands of tiles thus
/// pays the sweep once instead of once per tile. This is byte-identical, not
/// merely an approximation: `assume_simple` is only ever `true` when
/// [`has_self_intersecting_edges`] would have returned `false`, so the branch it
/// skips could not have changed the result. The cheap O(n) degenerate/duplicate
/// checks always run.
///
/// # Performance
///
/// - O(n) for the vertex checks (always run)
/// - O((n + m) log n) sweep for edge intersection (skipped when `assume_simple`)
fn has_structural_issues(poly: &Polygon<f64>, assume_simple: bool) -> bool {
    let ring = poly.exterior();

    // Check for degenerate ring (need at least 4 vertices for valid closed polygon)
    if ring.0.len() < 4 {
        return true;
    }

    // Check for duplicate consecutive vertices (self-touching)
    // Skip checking the closing vertex which legitimately matches the first
    for i in 0..ring.0.len() - 1 {
        let curr = ring.0[i];
        let next = ring.0[i + 1];
        // Use epsilon comparison for floating point
        if (curr.x - next.x).abs() < 1e-10 && (curr.y - next.y).abs() < 1e-10 {
            // This is only okay for the closing vertex
            if i != ring.0.len() - 2 {
                return true;
            }
        }
    }

    // Check for self-intersecting edges (O((n + m) log n) sweepline). Skipped
    // when the feature was pre-validated as simple — see the `assume_simple`
    // note above.
    if !assume_simple && has_self_intersecting_edges(&ring.0) {
        return true;
    }

    false
}

/// Check if a ring has self-intersecting edges (any two non-adjacent edges that
/// *properly* cross).
///
/// # Sweepline (issue #241)
///
/// This runs a Bentley–Ottmann sweep (`geo::algorithm::sweep::Intersections`) to
/// enumerate candidate intersecting edge pairs in **O((n + m) log n)** — where
/// `m` is the number of x-overlapping pairs — instead of the previous
/// **O(n²)** pairwise scan. The sweep replaced a capped scan (issue #237 skipped
/// rings above 2048 vertices to keep the export from stalling on continental
/// admin rings); with the sweep the cap is gone, so even a genuinely
/// self-intersecting giant ring is now detected and routed to i_overlay repair.
///
/// ## Byte-identical decision
///
/// The sweep only decides which pairs to *test*; the accept/reject decision is
/// the unchanged [`edges_intersect_properly`] predicate applied to each
/// candidate. A proper crossing meets at a point interior to both edges, so its
/// two edges always overlap in x and are therefore always surfaced by the sweep
/// — no proper crossing is missed. Adjacent edges (sharing a vertex) and
/// collinear overlaps yield a zero cross-product and are rejected by the
/// predicate exactly as before, so the boolean result matches the old scan on
/// every real (simple) ring. Degenerate zero-length edges are dropped up front,
/// matching the old scan's `continue`.
fn has_self_intersecting_edges(coords: &[Coord<f64>]) -> bool {
    let n = coords.len();
    if n < 4 {
        return false;
    }

    // Ring edges as sweep-line segments, dropping degenerate (zero-length)
    // edges just as the previous pairwise scan skipped them.
    let segments: Vec<Line<f64>> = coords
        .windows(2)
        .filter_map(|w| {
            let (a, b) = (w[0], w[1]);
            if (a.x - b.x).abs() < 1e-10 && (a.y - b.y).abs() < 1e-10 {
                None
            } else {
                Some(Line::new(a, b))
            }
        })
        .collect();

    // The sweep yields every edge pair that overlaps in x and meets; re-apply
    // the exact proper-crossing predicate to keep the result byte-identical to
    // the old O(n²) scan (see the note above).
    Intersections::from_iter(segments)
        .any(|(a, b, _)| edges_intersect_properly(a.start, a.end, b.start, b.end))
}

/// Check if two line segments intersect properly (crossing, not touching at endpoints).
///
/// Uses the cross-product orientation test.
fn edges_intersect_properly(
    a1: Coord<f64>,
    a2: Coord<f64>,
    b1: Coord<f64>,
    b2: Coord<f64>,
) -> bool {
    let d1 = cross_product_sign(b1, b2, a1);
    let d2 = cross_product_sign(b1, b2, a2);
    let d3 = cross_product_sign(a1, a2, b1);
    let d4 = cross_product_sign(a1, a2, b2);

    // Segments cross if endpoints are on opposite sides of each other's lines
    ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0))
        && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
}

/// Compute the cross product sign for orientation test.
fn cross_product_sign(a: Coord<f64>, b: Coord<f64>, c: Coord<f64>) -> f64 {
    (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}

/// Check if a geometry (Polygon or MultiPolygon) has structural issues.
/// See [`has_structural_issues`] for the meaning of `assume_simple`.
fn geometry_has_structural_issues(geom: &Geometry<f64>, assume_simple: bool) -> bool {
    match geom {
        Geometry::Polygon(p) => has_structural_issues(p, assume_simple),
        Geometry::MultiPolygon(mp) => mp.0.iter().any(|p| has_structural_issues(p, assume_simple)),
        _ => false,
    }
}

/// Whether a geometry's polygon exterior rings are **simple** (free of
/// self-intersecting edges).
///
/// This runs the same self-intersection sweep as [`has_structural_issues`] (an
/// O((n + m) log n) Bentley–Ottmann pass, issue #241), but is meant to be called
/// **once per feature** rather than once per clip. Threading the result into the
/// clip pipeline as `assume_simple` lets the hot path skip that check on every
/// tile the feature touches (issue #237, RC3): a continental admin polygon
/// covering thousands of tiles pays the cost once instead of thousands of times.
///
/// Only exterior rings are inspected, matching what [`has_structural_issues`]
/// (and hence the S-H validity gate) actually checks. Non-polygon geometries
/// are trivially simple for the purposes of rectangle clipping.
pub fn geometry_is_simple(geom: &Geometry<f64>) -> bool {
    match geom {
        Geometry::Polygon(p) => !has_self_intersecting_edges(&p.exterior().0),
        Geometry::MultiPolygon(mp) => {
            mp.0.iter()
                .all(|p| !has_self_intersecting_edges(&p.exterior().0))
        }
        _ => true,
    }
}

/// Check if a polygon has edges that run along the clip boundary.
///
/// This detects the case where S-H incorrectly connects disconnected regions
/// by tracing along the clip boundary. For example, a U-shaped polygon clipped
/// across its opening will have an edge running along the bottom of the clip
/// region, connecting the two arms.
///
/// Returns true if any edge lies entirely on a boundary (same x or y coordinate
/// for both endpoints, matching a boundary value).
fn has_boundary_connecting_edges(poly: &Polygon<f64>, bounds: &TileBounds) -> bool {
    let ring = poly.exterior();
    let eps = 1e-10;

    for window in ring.0.windows(2) {
        let p1 = window[0];
        let p2 = window[1];

        // Skip if this is a degenerate (zero-length) edge
        if (p1.x - p2.x).abs() < eps && (p1.y - p2.y).abs() < eps {
            continue;
        }

        // Check if edge lies on left boundary (both x == lng_min)
        if (p1.x - bounds.lng_min).abs() < eps && (p2.x - bounds.lng_min).abs() < eps {
            // Edge runs along left boundary - this is connecting
            return true;
        }

        // Check if edge lies on right boundary (both x == lng_max)
        if (p1.x - bounds.lng_max).abs() < eps && (p2.x - bounds.lng_max).abs() < eps {
            return true;
        }

        // Check if edge lies on bottom boundary (both y == lat_min)
        if (p1.y - bounds.lat_min).abs() < eps && (p2.y - bounds.lat_min).abs() < eps {
            return true;
        }

        // Check if edge lies on top boundary (both y == lat_max)
        if (p1.y - bounds.lat_max).abs() < eps && (p2.y - bounds.lat_max).abs() < eps {
            return true;
        }
    }

    false
}

// ============================================================================
// Public Clipping API
// ============================================================================

pub fn clip_geometry(
    geom: &Geometry<f64>,
    bounds: &TileBounds,
    buffer: f64,
) -> Option<Geometry<f64>> {
    // Backward-compatible entry point: validate simplicity per clip (the
    // pre-#237 behavior). Hot export paths should call `clip_geometry_simple`
    // with a per-feature `assume_simple` flag instead.
    clip_geometry_simple(geom, bounds, buffer, false, false)
}

/// Clip a geometry to buffered tile bounds, with caller-supplied hints that skip
/// redundant validity work on features already proven simple.
///
/// # `assume_simple` (issue #237, RC3)
///
/// Pass `true` **only** when the source feature's rings have already been proven
/// simple via [`geometry_is_simple`]. It skips the O(V²) self-intersection
/// re-scan per clip; under its precondition that scan would always have returned
/// "no issue", so the result is byte-identical to [`clip_geometry`].
///
/// # `skip_boundary_fallback` (issue #239)
///
/// Consulted **only when `assume_simple` is also true**. It additionally skips
/// the O(V) `has_boundary_connecting_edges` gate, so a simple polygon whose S-H
/// clip runs an edge along the tile boundary keeps the (cheap) S-H result
/// instead of routing to i_overlay. For simple rings that S-H "bridge" is a
/// self-touching ring that is area- and fill-equivalent to i_overlay's split
/// under nonzero winding (measured — see `fastpath_u_render_equivalent`), so this
/// removes the ~94% fine-zoom i_overlay fallback without changing rendered
/// output. On non-simple inputs the gate always runs, preserving the #94 fix.
pub fn clip_geometry_simple(
    geom: &Geometry<f64>,
    bounds: &TileBounds,
    buffer: f64,
    assume_simple: bool,
    skip_boundary_fallback: bool,
) -> Option<Geometry<f64>> {
    let buffered = TileBounds::new(
        bounds.lng_min - buffer,
        bounds.lat_min - buffer,
        bounds.lng_max + buffer,
        bounds.lat_max + buffer,
    );

    match geom {
        Geometry::Point(p) => clip_point(p, &buffered).map(Geometry::Point),
        Geometry::LineString(ls) => clip_linestring(ls, &buffered),
        Geometry::Polygon(poly) => {
            clip_polygon(poly, &buffered, assume_simple, skip_boundary_fallback)
        }
        Geometry::MultiPolygon(mp) => {
            clip_multipolygon(mp, &buffered, assume_simple, skip_boundary_fallback)
                .map(Geometry::MultiPolygon)
        }
        Geometry::MultiLineString(mls) => clip_multilinestring(mls, &buffered),
        other => {
            // For other geometry types, use bounding box check
            if let Some(rect) = other.bounding_rect() {
                if intersects_bounds(&rect, &buffered) {
                    return Some(other.clone());
                }
            }
            None
        }
    }
}

/// Convert buffer from pixels to degrees based on tile bounds.
///
/// # Arguments
///
/// * `buffer_pixels` - Buffer size in pixels (e.g., 8)
/// * `tile_bounds` - The tile bounds to calculate pixel size from
/// * `extent` - Tile extent in pixels (e.g., 4096)
///
/// # Returns
///
/// Buffer size in degrees (same units as tile bounds)
pub fn buffer_pixels_to_degrees(buffer_pixels: u32, tile_bounds: &TileBounds, extent: u32) -> f64 {
    // Buffer is specified in "screen pixels" where the tile is extent pixels wide
    // Convert to the same units as bounds (degrees)
    tile_bounds.width() * buffer_pixels as f64 / extent as f64
}

/// Check if a rectangle intersects the given bounds
fn intersects_bounds(rect: &Rect<f64>, bounds: &TileBounds) -> bool {
    rect.max().x >= bounds.lng_min
        && rect.min().x <= bounds.lng_max
        && rect.max().y >= bounds.lat_min
        && rect.min().y <= bounds.lat_max
}

/// Check if a rectangle is fully contained within the given bounds
fn is_fully_inside(rect: &Rect<f64>, bounds: &TileBounds) -> bool {
    rect.min().x >= bounds.lng_min
        && rect.max().x <= bounds.lng_max
        && rect.min().y >= bounds.lat_min
        && rect.max().y <= bounds.lat_max
}

// ============================================================================
// Geometry Clipping Functions
// ============================================================================

/// Clip a point to bounds (simple containment check)
fn clip_point(point: &Point<f64>, bounds: &TileBounds) -> Option<Point<f64>> {
    if point.x() >= bounds.lng_min
        && point.x() <= bounds.lng_max
        && point.y() >= bounds.lat_min
        && point.y() <= bounds.lat_max
    {
        Some(*point)
    } else {
        None
    }
}

/// Clip a linestring to bounds using BooleanOps.
///
/// IMPORTANT: Uses correct signature - `polygon.clip(&linestring, invert)`
/// NOT `linestring.clip(&polygon)` which doesn't exist.
fn clip_linestring(ls: &LineString<f64>, bounds: &TileBounds) -> Option<Geometry<f64>> {
    // Quick rejection test
    if let Some(rect) = ls.bounding_rect() {
        if !intersects_bounds(&rect, bounds) {
            return None;
        }
    }

    let clip_rect = Rect::new(
        Coord {
            x: bounds.lng_min,
            y: bounds.lat_min,
        },
        Coord {
            x: bounds.lng_max,
            y: bounds.lat_max,
        },
    );
    let clip_poly = clip_rect.to_polygon();

    // Correct usage: polygon.clip(&multilinestring, invert)
    // invert=false means keep the parts INSIDE the polygon
    let mls = MultiLineString::new(vec![ls.clone()]);
    let clipped = clip_poly.clip(&mls, false);

    if clipped.0.is_empty() {
        None
    } else if clipped.0.len() == 1 {
        Some(Geometry::LineString(clipped.0.into_iter().next().unwrap()))
    } else {
        Some(Geometry::MultiLineString(clipped))
    }
}

/// Clip a multilinestring to bounds
fn clip_multilinestring(mls: &MultiLineString<f64>, bounds: &TileBounds) -> Option<Geometry<f64>> {
    // Quick rejection test
    if let Some(rect) = mls.bounding_rect() {
        if !intersects_bounds(&rect, bounds) {
            return None;
        }
    }

    let clip_rect = Rect::new(
        Coord {
            x: bounds.lng_min,
            y: bounds.lat_min,
        },
        Coord {
            x: bounds.lng_max,
            y: bounds.lat_max,
        },
    );
    let clip_poly = clip_rect.to_polygon();

    // Correct usage: polygon.clip(&multilinestring, invert)
    let clipped = clip_poly.clip(mls, false);

    if clipped.0.is_empty() {
        None
    } else {
        Some(Geometry::MultiLineString(clipped))
    }
}

fn clip_polygon(
    poly: &Polygon<f64>,
    bounds: &TileBounds,
    assume_simple: bool,
    skip_boundary_fallback: bool,
) -> Option<Geometry<f64>> {
    // Quick rejection test using bounding box
    let poly_rect = poly.bounding_rect()?;
    if !intersects_bounds(&poly_rect, bounds) {
        return None;
    }

    // Check if input polygon has structural issues (self-intersecting, etc.)
    // If so, we MUST use i_overlay even for "fully inside" polygons because
    // i_overlay will repair the geometry while S-H cannot. When the feature was
    // pre-validated as simple (issue #237), the O(V²) self-intersection scan is
    // skipped here — see `has_structural_issues`.
    let input_has_issues = has_structural_issues(poly, assume_simple);

    // FAST PATH: If polygon is fully inside bounds AND valid, return as-is
    if is_fully_inside(&poly_rect, bounds) && !input_has_issues {
        return Some(Geometry::Polygon(poly.clone()));
    }

    // If input has structural issues, go directly to i_overlay (skip S-H)
    // i_overlay handles self-intersecting polygons by splitting them into valid parts
    if input_has_issues {
        return ioverlay_clip::clip_polygon_ioverlay(poly, bounds);
    }

    // Primary path: Use Sutherland-Hodgman for O(n) rectangle clipping
    let sh_result = sutherland_hodgman::clip_polygon_sh(poly, bounds);

    // Validate S-H output and fall back to i_overlay on structural issues or
    // boundary-connecting bridges. `assume_simple` (issue #237) only suppresses
    // the O(V²) self-intersection re-scan inside `geometry_has_structural_issues`.
    //
    // `skip_boundary_fallback` (issue #239) additionally suppresses the O(V)
    // `has_boundary_connecting_edges` gate, but ONLY when `assume_simple` — for a
    // ring proven simple, S-H's boundary-following "bridge" is a self-touching
    // ring that is area- and fill-identical to the i_overlay result under nonzero
    // winding (measured: `fastpath_u_render_equivalent`), so the fallback is pure
    // wasted work. On non-simple inputs the gate always runs, preserving #94.
    let skip_boundary = assume_simple && skip_boundary_fallback;
    match &sh_result {
        Some(Geometry::Polygon(p)) => {
            // Check for structural issues OR boundary-connecting edges
            // (the latter indicates S-H connected disconnected regions)
            if geometry_has_structural_issues(sh_result.as_ref().unwrap(), assume_simple)
                || (!skip_boundary && has_boundary_connecting_edges(p, bounds))
            {
                ioverlay_clip::clip_polygon_ioverlay(poly, bounds)
            } else {
                sh_result
            }
        }
        Some(Geometry::MultiPolygon(mp)) => {
            // Check each polygon for issues
            let has_issues = mp.0.iter().any(|p| {
                has_structural_issues(p, assume_simple)
                    || (!skip_boundary && has_boundary_connecting_edges(p, bounds))
            });
            if has_issues {
                ioverlay_clip::clip_polygon_ioverlay(poly, bounds)
            } else {
                sh_result
            }
        }
        Some(_) => {
            // Other geometry type - shouldn't happen for polygon clipping
            sh_result
        }
        None => {
            // S-H returned None - polygon doesn't intersect bounds
            // (This shouldn't happen given the bbox check above, but handle it)
            None
        }
    }
}

fn clip_multipolygon(
    mp: &MultiPolygon<f64>,
    bounds: &TileBounds,
    assume_simple: bool,
    skip_boundary_fallback: bool,
) -> Option<MultiPolygon<f64>> {
    // Level 1: Quick rejection using overall MultiPolygon bbox
    let mp_rect = mp.bounding_rect()?;
    if !intersects_bounds(&mp_rect, bounds) {
        return None;
    }

    // FAST PATH: If entire multipolygon is fully inside bounds, return as-is
    if is_fully_inside(&mp_rect, bounds) {
        return Some(mp.clone());
    }

    // Level 2: Per-polygon bbox filter + clip
    // Each polygon is individually tested with its own bounding box before
    // any clipping is attempted. This avoids expensive operations for
    // sub-polygons that are far from the tile.
    let mut clipped_polys = Vec::new();
    for poly in &mp.0 {
        // Per-polygon bbox filter: compute each polygon's bbox and check
        // intersection before calling into the clip pipeline
        let poly_rect = match poly.bounding_rect() {
            Some(r) => r,
            None => continue, // Degenerate polygon, skip
        };

        if !intersects_bounds(&poly_rect, bounds) {
            // This polygon's bbox doesn't intersect the tile -- skip entirely.
            // This is the key optimization: for a MultiPolygon with 7453 polygons
            // where only ~100 intersect the tile, we skip 7353 polygons here
            // without any clipping work.
            continue;
        }

        // FAST PATH: If this polygon is fully inside bounds, add as-is
        if is_fully_inside(&poly_rect, bounds) {
            clipped_polys.push(poly.clone());
            continue;
        }

        // Polygon intersects but isn't fully inside -- needs clipping. The
        // clip may split one part into several disjoint pieces (a tile edge
        // crossing a wiggly boundary more than once, or the i_overlay
        // fallback resolving an S-H bridge into its true parts) — keep every
        // piece. Discarding the MultiPolygon case here silently deleted
        // boundary-straddling parts from individual tiles (#244).
        match clip_polygon(poly, bounds, assume_simple, skip_boundary_fallback) {
            Some(Geometry::Polygon(clipped)) => clipped_polys.push(clipped),
            Some(Geometry::MultiPolygon(pieces)) => clipped_polys.extend(pieces.0),
            Some(other) => debug_assert!(false, "polygon clip returned {other:?}"),
            None => {}
        }
    }

    if clipped_polys.is_empty() {
        None
    } else {
        Some(MultiPolygon::new(clipped_polys))
    }
}

// ============================================================================
// WorldCoord-based Clipping Functions (Phase 1)
// ============================================================================
//
// These functions provide WorldCoord-native clipping that operates in
// 32-bit integer world coordinate space. They eliminate the floating-point
// precision issues in buffer calculation and tile boundary comparisons.
//
// PHASE 1: Additive -- the f64 versions above remain the primary API.
// Phase 2 will migrate the pipeline to call these instead.

use crate::world_coord::{lng_lat_to_world, WorldBounds, WorldCoord};

/// Compute buffer size in world coordinate units for a given tile.
///
/// This is the integer-precision replacement for `buffer_pixels_to_degrees`.
/// The calculation is exact: `buffer_world = tile_size * buffer_pixels / extent`
///
/// # Arguments
/// * `zoom` - Zoom level of the tile
/// * `buffer_pixels` - Buffer size in pixels (e.g., 8)
/// * `extent` - Tile extent in pixels (e.g., 4096)
///
/// # Returns
/// Buffer size in world coordinate units
pub fn buffer_pixels_to_world(zoom: u8, buffer_pixels: u32, extent: u32) -> u32 {
    let tile_size_world: u64 = if zoom == 0 {
        crate::world_coord::WORLD_SCALE
    } else {
        1_u64 << (32 - zoom as u32)
    };
    (tile_size_world * buffer_pixels as u64 / extent as u64) as u32
}

/// Clip a point in WorldCoord space to WorldBounds.
///
/// # Returns
/// The point if inside the bounds, or `None` if outside.
pub fn clip_point_world(point: &WorldCoord, bounds: &WorldBounds) -> Option<WorldCoord> {
    if bounds.contains(point) {
        Some(*point)
    } else {
        None
    }
}

/// Clip a polygon in WorldCoord space using Sutherland-Hodgman.
///
/// This is the integer-coordinate equivalent of `clip_polygon`. It uses
/// the WorldCoord-based SH algorithm for exact clipping in world space.
///
/// # Arguments
/// * `exterior` - Exterior ring as WorldCoord points
/// * `interiors` - Interior rings (holes) as WorldCoord points
/// * `bounds` - Tile bounds in world coordinate space
///
/// # Returns
/// Clipped exterior and interior rings, or `None` if no intersection
///
/// # Fast Paths
/// - Returns `None` immediately if the polygon's bbox doesn't intersect bounds
/// - Returns the polygon as-is if fully inside bounds
pub fn clip_polygon_world(
    exterior: &[WorldCoord],
    interiors: &[Vec<WorldCoord>],
    bounds: &WorldBounds,
) -> Option<(Vec<WorldCoord>, Vec<Vec<WorldCoord>>)> {
    // Quick bbox rejection
    let poly_bounds = worldcoord_bbox(exterior)?;
    if !bounds.intersects(&poly_bounds) {
        return None;
    }

    // Fast path: fully inside
    if bounds.contains_bounds(&poly_bounds) {
        return Some((exterior.to_vec(), interiors.to_vec()));
    }

    // Clip with Sutherland-Hodgman
    sutherland_hodgman::clip_polygon_sh_world(exterior, interiors, bounds)
}

/// Compute the axis-aligned bounding box of a WorldCoord ring.
fn worldcoord_bbox(coords: &[WorldCoord]) -> Option<WorldBounds> {
    if coords.is_empty() {
        return None;
    }

    let mut x_min = u32::MAX;
    let mut y_min = u32::MAX;
    let mut x_max = 0u32;
    let mut y_max = 0u32;

    for c in coords {
        x_min = x_min.min(c.x);
        y_min = y_min.min(c.y);
        x_max = x_max.max(c.x);
        y_max = y_max.max(c.y);
    }

    Some(WorldBounds::new(x_min, y_min, x_max, y_max))
}

/// Convert a geo::Polygon<f64> to WorldCoord rings for clipping.
///
/// This is a convenience function for the Phase 1 migration -- it converts
/// from the existing f64 representation to WorldCoord for clipping, then
/// results can be converted back. In Phase 2, geometries will already be
/// in WorldCoord format.
pub fn polygon_to_world_rings(poly: &Polygon<f64>) -> (Vec<WorldCoord>, Vec<Vec<WorldCoord>>) {
    let exterior: Vec<WorldCoord> = poly
        .exterior()
        .coords()
        .map(|c| lng_lat_to_world(c.x, c.y))
        .collect();

    let interiors: Vec<Vec<WorldCoord>> = poly
        .interiors()
        .iter()
        .map(|ring| ring.coords().map(|c| lng_lat_to_world(c.x, c.y)).collect())
        .collect();

    (exterior, interiors)
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo::point;

    // ========== MultiPolygon part-splitting clips (issue #244) ==========

    /// A one-part MultiPolygon whose part is a U: two vertical prongs
    /// (x ∈ [0,1] and x ∈ [3,4], rising to y=5) joined by a base (y ∈ [0,1]).
    fn u_multipolygon() -> MultiPolygon<f64> {
        MultiPolygon::new(vec![Polygon::new(
            LineString::from(vec![
                (0.0, 0.0),
                (4.0, 0.0),
                (4.0, 5.0),
                (3.0, 5.0),
                (3.0, 1.0),
                (1.0, 1.0),
                (1.0, 5.0),
                (0.0, 5.0),
                (0.0, 0.0),
            ]),
            vec![],
        )])
    }

    #[test]
    fn multipolygon_part_splitting_into_pieces_is_kept() {
        // Clip window covering only the prong tips: the single U part clips
        // into TWO disjoint pieces. `clip_polygon` correctly reports that as a
        // MultiPolygon; the part collector must keep both pieces instead of
        // silently dropping the result (#244 — the field failure dropped
        // boundary-straddling admin polygons from individual tiles, cutting
        // them off along razor-straight tile-boundary lines).
        let mp = u_multipolygon();
        let window = TileBounds::new(-0.5, 3.0, 4.5, 6.0);
        let clipped = clip_multipolygon(&mp, &window, false, false)
            .expect("clip must not drop a genuinely-overlapping feature");
        assert_eq!(clipped.0.len(), 2, "both prong pieces must survive");
        // Same through the public geometry entry point, simple-path flavor.
        let via_public =
            clip_geometry_simple(&Geometry::MultiPolygon(mp), &window, 0.0, true, false)
                .expect("public entry point must keep the feature");
        match via_public {
            Geometry::MultiPolygon(m) => assert_eq!(m.0.len(), 2),
            other => panic!("expected MultiPolygon, got {other:?}"),
        }
    }

    #[test]
    fn tielt_winge_boundary_sliver_regression() {
        // Real-data regression for #244: Tielt-Winge (fieldmaps Belgium adm4,
        // 401 verts, valid, simple) overlaps six z12 tiles; its eastern sliver
        // in tile 12/2104/1372 clips into two disjoint pieces and was silently
        // dropped, cutting the municipality off along lon 4.921875. Verifies
        // both the direct leaf clip and the export cascade's ancestor chain.
        use geo::Contains;
        use geozero::ToGeo;
        let path = std::path::Path::new("../../tests/fixtures/realdata/tielt-winge-adm4.wkb");
        if !path.exists() {
            eprintln!("Skipping: fixture not found");
            return;
        }
        let geom: Geometry<f64> = geozero::wkb::Wkb(std::fs::read(path).unwrap())
            .to_geo()
            .unwrap();
        let simple = geometry_is_simple(&geom);
        let buf = |b: &TileBounds| b.width() * 8.0 / 4096.0;

        // The user-reported hole: this point is inside the municipality and
        // inside tile 12/2104/1372.
        let hole = point!(x: 4.9265, y: 50.9468);
        let contains_hole = |g: &Geometry<f64>| match g {
            Geometry::MultiPolygon(m) => m.contains(&hole),
            Geometry::Polygon(p) => p.contains(&hole),
            other => panic!("unexpected clip output {other:?}"),
        };
        let leaf = crate::tile::tile_bounds(2104, 1372, 12);

        let direct = clip_geometry_simple(&geom, &leaf, buf(&leaf), simple, false)
            .expect("direct leaf clip must keep the eastern sliver");
        assert!(
            contains_hole(&direct),
            "clipped sliver must cover the reported hole point"
        );

        // Export cascade replay: ancestors of (2104,1372) below the z8
        // covering tile. Every ancestor clip must retain the sliver region.
        let mut cur = geom;
        for (x, y, z) in [(263u32, 171u32, 9u8), (526, 343, 10), (1052, 686, 11)] {
            let nb = crate::tile::tile_bounds(x, y, z);
            cur = clip_geometry_simple(&cur, &nb, buf(&nb), simple, false)
                .unwrap_or_else(|| panic!("cascade lost the feature at z{z} ({x},{y})"));
        }
        let casc = clip_geometry_simple(&cur, &leaf, buf(&leaf), simple, false)
            .expect("cascade leaf clip must keep the eastern sliver");
        assert!(
            contains_hole(&casc),
            "cascade-clipped sliver must cover the reported hole point"
        );
    }

    // ========== Simplicity fast-path (issue #237, RC3) ==========

    fn square(minx: f64, miny: f64, maxx: f64, maxy: f64) -> Polygon<f64> {
        Polygon::new(
            LineString::from(vec![
                (minx, miny),
                (maxx, miny),
                (maxx, maxy),
                (minx, maxy),
                (minx, miny),
            ]),
            vec![],
        )
    }

    #[test]
    fn geometry_is_simple_true_for_simple_polygon() {
        let g = Geometry::Polygon(square(0.0, 0.0, 4.0, 4.0));
        assert!(geometry_is_simple(&g));
    }

    #[test]
    fn geometry_is_simple_false_for_bowtie() {
        // Figure-eight: edges (0,0)->(2,2) and (2,0)->(0,2) cross.
        let bowtie = Polygon::new(
            LineString::from(vec![
                (0.0, 0.0),
                (2.0, 2.0),
                (2.0, 0.0),
                (0.0, 2.0),
                (0.0, 0.0),
            ]),
            vec![],
        );
        assert!(!geometry_is_simple(&Geometry::Polygon(bowtie)));
    }

    #[test]
    fn geometry_is_simple_multipolygon_all_or_nothing() {
        let good = square(0.0, 0.0, 1.0, 1.0);
        let bowtie = Polygon::new(
            LineString::from(vec![
                (0.0, 0.0),
                (2.0, 2.0),
                (2.0, 0.0),
                (0.0, 2.0),
                (0.0, 0.0),
            ]),
            vec![],
        );
        assert!(geometry_is_simple(&Geometry::MultiPolygon(
            MultiPolygon::new(vec![good.clone(), square(5.0, 5.0, 6.0, 6.0)])
        )));
        assert!(!geometry_is_simple(&Geometry::MultiPolygon(
            MultiPolygon::new(vec![good, bowtie])
        )));
    }

    /// A crossing ("bowtie") ring of `n` vertices: two dense diagonals that
    /// intersect. Used to exercise the sweepline self-intersection test at a
    /// range of ring sizes.
    fn crossing_ring(n: usize) -> Vec<Coord<f64>> {
        let half = n / 2;
        let mut v: Vec<Coord<f64>> = Vec::with_capacity(n + 1);
        // Diagonal A: (0,0) -> (10,10), the line y = x.
        for i in 0..half {
            let t = i as f64 / half as f64;
            v.push(Coord {
                x: 10.0 * t,
                y: 10.0 * t,
            });
        }
        // Diagonal B: (10,0.7) -> (0,10.7), the line y = 10.7 - x. A and B cross
        // transversally at (~5.35, ~5.35), which the 0.7 offset keeps off every
        // vertex so it is a *proper* self-intersection.
        for i in 0..half {
            let t = i as f64 / half as f64;
            v.push(Coord {
                x: 10.0 - 10.0 * t,
                y: 0.7 + 10.0 * t,
            });
        }
        v.push(v[0]); // close
        v
    }

    #[test]
    fn self_intersection_detected_small_ring() {
        let ring = crossing_ring(64);
        assert!(has_self_intersecting_edges(&ring));
    }

    #[test]
    fn large_self_intersecting_ring_detected() {
        // Issue #241: a genuinely self-intersecting ring far larger than the old
        // O(n²) cap (2048) must still be reported as self-intersecting. The
        // sweepline test carries no vertex cap, so the crossing is found
        // regardless of ring size — closing the latent correctness gap left by
        // the capped scan.
        let ring = crossing_ring(6_000);
        assert!(ring.len() > 2_048);
        assert!(has_self_intersecting_edges(&ring));
    }

    #[test]
    fn large_simple_ring_not_self_intersecting() {
        // A large convex ring (regular polygon approximating a circle), far
        // above the old cap, must be reported simple. This guards the sweepline
        // against false positives at scale and confirms it stays fast where the
        // old O(n²) scan would have stalled (issue #241).
        let n = 20_000usize;
        let mut ring: Vec<Coord<f64>> = (0..n)
            .map(|i| {
                let theta = std::f64::consts::TAU * (i as f64) / (n as f64);
                Coord {
                    x: theta.cos(),
                    y: theta.sin(),
                }
            })
            .collect();
        ring.push(ring[0]); // close
        assert!(ring.len() > 2_048);
        assert!(!has_self_intersecting_edges(&ring));
    }

    #[test]
    fn geometry_is_simple_true_for_non_polygon() {
        let g = Geometry::Point(point!(x: 1.0, y: 1.0));
        assert!(geometry_is_simple(&g));
    }

    #[test]
    fn clip_geometry_simple_byte_identical_on_simple_input() {
        // A simple polygon that straddles the clip bounds (so it is actually
        // clipped, exercising the S-H path + output validity gate). With a
        // simple input, `assume_simple = true` must produce output identical to
        // the default full-validation path — the RC3 guarantee.
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let buffer = 0.5;
        let cases = vec![
            Geometry::Polygon(square(-3.0, -3.0, 5.0, 5.0)),
            Geometry::Polygon(square(2.0, 2.0, 20.0, 8.0)),
            Geometry::MultiPolygon(MultiPolygon::new(vec![
                square(-2.0, -2.0, 4.0, 4.0),
                square(6.0, 6.0, 13.0, 13.0),
            ])),
        ];
        for g in cases {
            assert!(geometry_is_simple(&g));
            let default = clip_geometry(&g, &bounds, buffer);
            let fast = clip_geometry_simple(&g, &bounds, buffer, true, false);
            assert_eq!(default, fast, "assume_simple output diverged for {g:?}");
        }
    }

    // ========== Point Clipping Tests ==========

    #[test]
    fn test_clip_point_inside() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let point = point!(x: 5.0, y: 5.0);
        assert!(clip_point(&point, &bounds).is_some());
    }

    #[test]
    fn test_clip_point_outside() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let point = point!(x: 15.0, y: 5.0);
        assert!(clip_point(&point, &bounds).is_none());
    }

    #[test]
    fn test_clip_point_on_boundary() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let point = point!(x: 10.0, y: 5.0);
        assert!(clip_point(&point, &bounds).is_some());
    }

    // ========== Polygon Clipping Tests ==========

    #[test]
    fn test_clip_polygon_partial() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Polygon::new(
            LineString::from(vec![
                Coord { x: -5.0, y: -5.0 },
                Coord { x: 5.0, y: -5.0 },
                Coord { x: 5.0, y: 5.0 },
                Coord { x: -5.0, y: 5.0 },
                Coord { x: -5.0, y: -5.0 },
            ]),
            vec![],
        );

        let result = clip_polygon(&poly, &bounds, false, false);
        assert!(result.is_some());

        // Extract the polygon (should be single polygon for this simple case)
        let clipped = match result.unwrap() {
            Geometry::Polygon(p) => p,
            Geometry::MultiPolygon(mp) => mp.0.into_iter().next().unwrap(),
            _ => panic!("Expected polygon geometry"),
        };
        // Verify clipped polygon is within bounds
        for coord in clipped.exterior().coords() {
            assert!(
                coord.x >= 0.0 && coord.x <= 10.0,
                "x={} out of bounds",
                coord.x
            );
            assert!(
                coord.y >= 0.0 && coord.y <= 10.0,
                "y={} out of bounds",
                coord.y
            );
        }
    }

    #[test]
    fn test_clip_polygon_outside() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Polygon::new(
            LineString::from(vec![
                Coord { x: 20.0, y: 20.0 },
                Coord { x: 30.0, y: 20.0 },
                Coord { x: 30.0, y: 30.0 },
                Coord { x: 20.0, y: 30.0 },
                Coord { x: 20.0, y: 20.0 },
            ]),
            vec![],
        );
        assert!(clip_polygon(&poly, &bounds, false, false).is_none());
    }

    #[test]
    fn test_clip_polygon_fully_inside() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Polygon::new(
            LineString::from(vec![
                Coord { x: 2.0, y: 2.0 },
                Coord { x: 8.0, y: 2.0 },
                Coord { x: 8.0, y: 8.0 },
                Coord { x: 2.0, y: 8.0 },
                Coord { x: 2.0, y: 2.0 },
            ]),
            vec![],
        );

        let result = clip_polygon(&poly, &bounds, false, false);
        assert!(result.is_some());
    }

    // ========== LineString Clipping Tests ==========

    #[test]
    fn test_clip_linestring_crossing() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let ls = LineString::from(vec![Coord { x: -5.0, y: 5.0 }, Coord { x: 15.0, y: 5.0 }]);

        let result = clip_linestring(&ls, &bounds);
        assert!(result.is_some());
    }

    #[test]
    fn test_clip_linestring_outside() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let ls = LineString::from(vec![Coord { x: 20.0, y: 20.0 }, Coord { x: 30.0, y: 30.0 }]);

        let result = clip_linestring(&ls, &bounds);
        assert!(result.is_none());
    }

    #[test]
    fn test_clip_linestring_fully_inside() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let ls = LineString::from(vec![Coord { x: 2.0, y: 2.0 }, Coord { x: 8.0, y: 8.0 }]);

        let result = clip_linestring(&ls, &bounds);
        assert!(result.is_some());
    }

    // ========== Buffer Calculation Tests ==========

    #[test]
    fn test_buffer_pixels_to_degrees() {
        let bounds = TileBounds::new(0.0, 0.0, 1.0, 1.0);
        let buffer = buffer_pixels_to_degrees(8, &bounds, 4096);

        // 8 pixels / 4096 extent * 1.0 degree width = 0.001953125
        let expected = 8.0 / 4096.0;
        assert!(
            (buffer - expected).abs() < 1e-10,
            "buffer={} expected={}",
            buffer,
            expected
        );
    }

    #[test]
    fn test_buffer_affects_clipping() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let buffer = 2.0; // 2 degree buffer

        // Point just outside bounds but within buffer
        let point = point!(x: 11.0, y: 5.0);

        // Without buffer: should be outside
        assert!(clip_point(&point, &bounds).is_none());

        // With buffer via clip_geometry: should be inside
        let result = clip_geometry(&Geometry::Point(point), &bounds, buffer);
        assert!(result.is_some());
    }

    // ========== clip_geometry Integration Tests ==========

    #[test]
    fn test_clip_geometry_point() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let point = Geometry::Point(point!(x: 5.0, y: 5.0));

        let result = clip_geometry(&point, &bounds, 0.0);
        assert!(result.is_some());
        assert!(matches!(result.unwrap(), Geometry::Point(_)));
    }

    #[test]
    fn test_clip_geometry_polygon() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Geometry::Polygon(Polygon::new(
            LineString::from(vec![
                Coord { x: 5.0, y: 5.0 },
                Coord { x: 15.0, y: 5.0 },
                Coord { x: 15.0, y: 15.0 },
                Coord { x: 5.0, y: 15.0 },
                Coord { x: 5.0, y: 5.0 },
            ]),
            vec![],
        ));

        let result = clip_geometry(&poly, &bounds, 0.0);
        assert!(result.is_some());
    }

    #[test]
    fn test_clip_geometry_with_buffer() {
        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let buffer = 1.0;

        // Polygon just outside bounds but overlapping with buffer
        let poly = Geometry::Polygon(Polygon::new(
            LineString::from(vec![
                Coord { x: 10.5, y: 5.0 },
                Coord { x: 12.0, y: 5.0 },
                Coord { x: 12.0, y: 8.0 },
                Coord { x: 10.5, y: 8.0 },
                Coord { x: 10.5, y: 5.0 },
            ]),
            vec![],
        ));

        // Without buffer: should be outside
        let result_no_buffer = clip_geometry(&poly, &bounds, 0.0);
        assert!(result_no_buffer.is_none());

        // With buffer: should clip to buffered bounds
        let result_with_buffer = clip_geometry(&poly, &bounds, buffer);
        assert!(result_with_buffer.is_some());
    }

    // ========== Bounding Box Pre-filter Tests ==========

    #[test]
    fn test_multipolygon_bbox_prefilter_skips_distant_polygons() {
        // Simulates an "Antarctica-like" MultiPolygon: many sub-polygons spread
        // across a wide geographic area, clipped to a small tile that only
        // intersects a handful of them.
        //
        // This verifies that per-polygon bbox filtering correctly:
        // 1. Produces output only for the intersecting polygons
        // 2. Returns None for the non-intersecting ones
        //
        // The tile covers a 10x10 degree area at (0,0)-(10,10).
        // We create 1000 polygons:
        //   - 990 are outside the tile (spread from x=20..200)
        //   - 10 are inside the tile (at x=1..9, y=1..9)
        let tile_bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);

        let mut polygons = Vec::with_capacity(1000);

        // 10 polygons inside the tile
        for i in 0..10 {
            let x = 1.0 + (i as f64) * 0.8;
            let y = 1.0 + (i as f64) * 0.8;
            polygons.push(Polygon::new(
                LineString::from(vec![
                    Coord { x, y },
                    Coord { x: x + 0.5, y },
                    Coord {
                        x: x + 0.5,
                        y: y + 0.5,
                    },
                    Coord { x, y: y + 0.5 },
                    Coord { x, y },
                ]),
                vec![],
            ));
        }

        // 990 polygons outside the tile (far away, scattered in x=20..200)
        for i in 0..990 {
            let x = 20.0 + (i as f64) * 0.18;
            let y = -80.0 + (i as f64) * 0.16;
            polygons.push(Polygon::new(
                LineString::from(vec![
                    Coord { x, y },
                    Coord { x: x + 0.1, y },
                    Coord {
                        x: x + 0.1,
                        y: y + 0.1,
                    },
                    Coord { x, y: y + 0.1 },
                    Coord { x, y },
                ]),
                vec![],
            ));
        }

        let mp = MultiPolygon::new(polygons);

        // Clip to the tile
        let result = clip_multipolygon(&mp, &tile_bounds, false, false);

        // Should produce output (the 10 inside polygons)
        assert!(
            result.is_some(),
            "Should produce output for the intersecting polygons"
        );

        let clipped_mp = result.unwrap();
        // Should have approximately 10 polygons (the ones inside the tile)
        // Exact count may vary slightly due to clipping artifacts
        assert!(
            clipped_mp.0.len() >= 8 && clipped_mp.0.len() <= 12,
            "Expected ~10 output polygons, got {}",
            clipped_mp.0.len()
        );

        // All output coordinates should be within tile bounds
        for poly in &clipped_mp.0 {
            let bbox = poly.bounding_rect().unwrap();
            assert!(
                bbox.min().x >= 0.0 - 0.01 && bbox.max().x <= 10.0 + 0.01,
                "Output polygon x outside tile bounds: {:?}",
                bbox
            );
            assert!(
                bbox.min().y >= 0.0 - 0.01 && bbox.max().y <= 10.0 + 0.01,
                "Output polygon y outside tile bounds: {:?}",
                bbox
            );
        }
    }

    #[test]
    fn test_multipolygon_bbox_prefilter_all_outside() {
        // All polygons are outside the tile -- should return None quickly
        let tile_bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);

        let polygons: Vec<Polygon<f64>> = (0..500)
            .map(|i| {
                let x = 50.0 + (i as f64) * 0.2;
                let y = 50.0 + (i as f64) * 0.1;
                Polygon::new(
                    LineString::from(vec![
                        Coord { x, y },
                        Coord { x: x + 0.1, y },
                        Coord {
                            x: x + 0.1,
                            y: y + 0.1,
                        },
                        Coord { x, y: y + 0.1 },
                        Coord { x, y },
                    ]),
                    vec![],
                )
            })
            .collect();

        let mp = MultiPolygon::new(polygons);
        let result = clip_multipolygon(&mp, &tile_bounds, false, false);
        assert!(
            result.is_none(),
            "All-outside multipolygon should return None"
        );
    }

    #[test]
    fn test_bbox_prefilter_large_polygon_preclip() {
        // A single large polygon spanning a huge area (-180 to +180 longitude)
        // is clipped to a small 10-degree tile. The pre-clip optimization should
        // reduce the coordinate count before sending to the expensive i_overlay clipper.
        let tile_bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);

        // Build a large polygon with many coordinates spanning the entire globe.
        // This simulates a complex coastline polygon.
        let mut coords: Vec<Coord<f64>> = Vec::new();
        // Bottom edge: many points from -180 to +180
        for i in 0..360 {
            let x = -180.0 + i as f64;
            let y = -60.0 + (i as f64 * 0.1).sin() * 2.0; // Wavy bottom edge
            coords.push(Coord { x, y });
        }
        // Top edge: many points from +180 back to -180
        for i in (0..360).rev() {
            let x = -180.0 + i as f64;
            let y = 60.0 + (i as f64 * 0.1).cos() * 2.0; // Wavy top edge
            coords.push(Coord { x, y });
        }
        // Close the polygon
        coords.push(coords[0]);

        let large_poly = Polygon::new(LineString::from(coords.clone()), vec![]);

        // Total input coordinates
        let total_input_coords = coords.len();
        assert!(
            total_input_coords > 700,
            "Test polygon should have many coordinates, got {}",
            total_input_coords
        );

        // Clip to small tile
        let result = clip_polygon(&large_poly, &tile_bounds, false, false);
        assert!(result.is_some(), "Large polygon should intersect the tile");

        // Verify the clipped result is reasonable
        match result.unwrap() {
            Geometry::Polygon(p) => {
                let output_coords = p.exterior().coords().count();
                // The clipped polygon should have far fewer coordinates than input
                assert!(
                    output_coords < total_input_coords / 2,
                    "Clipped polygon should have fewer coords than input: {} vs {}",
                    output_coords,
                    total_input_coords
                );
            }
            Geometry::MultiPolygon(mp) => {
                let total_output: usize = mp.0.iter().map(|p| p.exterior().coords().count()).sum();
                assert!(
                    total_output < total_input_coords / 2,
                    "Clipped multipolygon should have fewer coords than input: {} vs {}",
                    total_output,
                    total_input_coords
                );
            }
            other => panic!("Expected Polygon or MultiPolygon, got {:?}", other),
        }
    }

    // ========== Sutherland-Hodgman Clipping Unit Tests ==========

    // ---- antimeridian-crossing geometries (issue #188 behavior pins) --------
    //
    // Geometries are stored verbatim, so a polygon whose vertices sit at
    // lng ±179.9 is, in coordinate space, a near-world-wide rectangle passing
    // through lng 0 — NOT two slivers at the antimeridian. These tests PIN
    // what export-time clipping does with such a geometry: every tile in the
    // world row intersects it ("smearing"). Documenting current behavior,
    // not desired behavior. See `context/ANTIMERIDIAN.md`.

    /// A polygon with vertices at lng ±179.9 — intended by the data author as
    /// a 0.2°-wide feature crossing the antimeridian, but stored (verbatim)
    /// as a 359.8°-wide rectangle.
    fn antimeridian_polygon() -> Geometry<f64> {
        Geometry::Polygon(Polygon::new(
            LineString::from(vec![
                Coord { x: -179.9, y: -0.1 },
                Coord { x: 179.9, y: -0.1 },
                Coord { x: 179.9, y: 0.1 },
                Coord { x: -179.9, y: 0.1 },
                Coord { x: -179.9, y: -0.1 },
            ]),
            vec![],
        ))
    }

    #[test]
    fn antimeridian_polygon_smears_into_prime_meridian_tile() {
        // A tile at lng ≈ 0 is ~180° from either "true" half of the feature,
        // yet clipping yields content there because the stored rectangle
        // passes straight through it.
        let tile = TileBounds::new(-1.0, -1.0, 1.0, 1.0);
        let clipped = clip_geometry(&antimeridian_polygon(), &tile, 0.0);
        let clipped = clipped.expect(
            "PIN: prime-meridian tile receives geometry from an \
             antimeridian-crossing polygon (smearing)",
        );
        // The smear fills the tile's full x-range.
        let rect = clipped.bounding_rect().unwrap();
        assert!(
            (rect.min().x - (-1.0)).abs() < 1e-9 && (rect.max().x - 1.0).abs() < 1e-9,
            "PIN: smear spans the entire tile width, got {rect:?}"
        );
    }

    #[test]
    fn antimeridian_polygon_clips_at_edge_tile() {
        // A tile adjacent to +180° also intersects — the geometry is present
        // where the author intended it, in addition to the world-row smear.
        let tile = TileBounds::new(178.0, -1.0, 180.0, 1.0);
        let clipped = clip_geometry(&antimeridian_polygon(), &tile, 0.0);
        assert!(
            clipped.is_some(),
            "tile at the +180° edge intersects the stored rectangle"
        );
    }

    #[test]
    fn test_sutherland_hodgman_fully_inside() {
        // Polygon fully inside clip bounds -- should be unchanged
        use crate::sutherland_hodgman::clip_polygon_sh;

        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Polygon::new(
            LineString::from(vec![
                Coord { x: 2.0, y: 2.0 },
                Coord { x: 8.0, y: 2.0 },
                Coord { x: 8.0, y: 8.0 },
                Coord { x: 2.0, y: 8.0 },
                Coord { x: 2.0, y: 2.0 },
            ]),
            vec![],
        );

        let result = clip_polygon_sh(&poly, &bounds);
        assert!(result.is_some(), "Fully inside polygon should be preserved");
        match result.unwrap() {
            Geometry::Polygon(p) => {
                // Should preserve all 4 vertices + closing
                assert_eq!(
                    p.exterior().0.len(),
                    5,
                    "Should have 5 coords (4 vertices + close)"
                );
            }
            other => panic!("Expected Polygon, got {:?}", other),
        }
    }

    #[test]
    fn test_sutherland_hodgman_fully_outside() {
        // Polygon fully outside clip bounds -- should return None
        use crate::sutherland_hodgman::clip_polygon_sh;

        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Polygon::new(
            LineString::from(vec![
                Coord { x: 20.0, y: 20.0 },
                Coord { x: 30.0, y: 20.0 },
                Coord { x: 30.0, y: 30.0 },
                Coord { x: 20.0, y: 30.0 },
                Coord { x: 20.0, y: 20.0 },
            ]),
            vec![],
        );

        let result = clip_polygon_sh(&poly, &bounds);
        assert!(result.is_none(), "Fully outside polygon should be empty");
    }

    #[test]
    fn test_sutherland_hodgman_partial_clip() {
        // Polygon overlapping the right edge of the bounds
        use crate::sutherland_hodgman::clip_polygon_sh;

        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);
        let poly = Polygon::new(
            LineString::from(vec![
                Coord { x: 5.0, y: 2.0 },
                Coord { x: 15.0, y: 2.0 },
                Coord { x: 15.0, y: 8.0 },
                Coord { x: 5.0, y: 8.0 },
                Coord { x: 5.0, y: 2.0 },
            ]),
            vec![],
        );

        let result = clip_polygon_sh(&poly, &bounds);
        assert!(
            result.is_some(),
            "Partially overlapping polygon should produce output"
        );
        // Verify all result coords are within bounds
        match result.unwrap() {
            Geometry::Polygon(p) => {
                for coord in p.exterior().coords() {
                    assert!(
                        coord.x >= 0.0 - 0.001 && coord.x <= 10.0 + 0.001,
                        "x out of bounds: {}",
                        coord.x
                    );
                    assert!(
                        coord.y >= 0.0 - 0.001 && coord.y <= 10.0 + 0.001,
                        "y out of bounds: {}",
                        coord.y
                    );
                }
            }
            other => panic!("Expected Polygon, got {:?}", other),
        }
    }

    #[test]
    fn test_sutherland_hodgman_large_polygon_reduction() {
        // A polygon with many coordinates spanning a large area, clipped to a
        // small box. Tests that Sutherland-Hodgman reduces coordinate count.
        use crate::sutherland_hodgman::clip_polygon_sh;

        let bounds = TileBounds::new(0.0, 0.0, 10.0, 10.0);

        // Create a polygon with 720 coords spanning -180 to +180
        let mut coords = Vec::new();
        for i in 0..360 {
            coords.push(Coord {
                x: -180.0 + i as f64,
                y: -50.0,
            });
        }
        for i in (0..360).rev() {
            coords.push(Coord {
                x: -180.0 + i as f64,
                y: 50.0,
            });
        }
        coords.push(coords[0]); // close

        let input_count = coords.len();
        let poly = Polygon::new(LineString::from(coords), vec![]);

        let result = clip_polygon_sh(&poly, &bounds);
        assert!(result.is_some(), "Clipped polygon should not be empty");

        match result.unwrap() {
            Geometry::Polygon(p) => {
                let output_count = p.exterior().0.len();
                assert!(
                    output_count < input_count / 10,
                    "Sutherland-Hodgman should dramatically reduce coordinates: {} -> {}",
                    input_count,
                    output_count
                );
            }
            other => panic!("Expected Polygon, got {:?}", other),
        }
    }

    #[test]
    fn test_clip_polygon_u_shape() {
        // U-shaped polygon clipped by a horizontal band.
        //
        // With i_overlay, clipping correctly produces two separate polygons
        // (the two arms of the U) as a MultiPolygon. This is the geometrically
        // correct result and avoids the self-touching polygon that S-H produces.
        let bounds = TileBounds::new(0.0, 4.0, 10.0, 6.0); // Horizontal band

        // U-shape: two vertical bars connected at the bottom
        let u_shape = Polygon::new(
            LineString::from(vec![
                Coord { x: 1.0, y: 0.0 },
                Coord { x: 2.0, y: 0.0 },
                Coord { x: 2.0, y: 10.0 },
                Coord { x: 1.0, y: 10.0 },
                Coord { x: 1.0, y: 2.0 },
                Coord { x: 8.0, y: 2.0 },
                Coord { x: 8.0, y: 10.0 },
                Coord { x: 9.0, y: 10.0 },
                Coord { x: 9.0, y: 0.0 },
                Coord { x: 1.0, y: 0.0 },
            ]),
            vec![],
        );

        let result = clip_polygon(&u_shape, &bounds, false, false);
        assert!(result.is_some(), "U-shape should intersect the band");

        // i_overlay correctly produces a MultiPolygon with 2 separate polygons
        match result.unwrap() {
            Geometry::MultiPolygon(mp) => {
                assert_eq!(
                    mp.0.len(),
                    2,
                    "U-shape clipped should produce 2 separate polygons"
                );
                // Verify all coords within bounds for each polygon
                for p in mp.0.iter() {
                    for coord in p.exterior().coords() {
                        assert!(
                            coord.x >= 0.0 && coord.x <= 10.0,
                            "x={} out of bounds",
                            coord.x
                        );
                        assert!(
                            coord.y >= 4.0 - 1e-10 && coord.y <= 6.0 + 1e-10,
                            "y={} out of bounds",
                            coord.y
                        );
                    }
                }
            }
            Geometry::Polygon(p) => {
                // Also acceptable if i_overlay produces single valid polygon
                for coord in p.exterior().coords() {
                    assert!(
                        coord.x >= 0.0 && coord.x <= 10.0,
                        "x={} out of bounds",
                        coord.x
                    );
                    assert!(
                        coord.y >= 4.0 - 1e-10 && coord.y <= 6.0 + 1e-10,
                        "y={} out of bounds",
                        coord.y
                    );
                }
            }
            other => panic!("Expected Polygon or MultiPolygon, got {:?}", other),
        }
    }

    // ========== Simple-clip fast path (issue #239) ==========
    //
    // The `simple_clip_fastpath` flag skips the i_overlay boundary-bridge
    // fallback for features whose rings are already simple. These tests pin the
    // behavior and the equivalence it relies on: on a simple concave polygon,
    // S-H's self-touching output is area- and fill-identical to i_overlay's
    // split under nonzero winding, so skipping the fallback changes nothing that
    // renders. The concave "U" cut across its mouth is the case #94's fallback
    // was built for; the flag deliberately keeps S-H there.

    /// A genuinely SIMPLE concave U (opening upward), non-self-intersecting.
    ///
    /// NOTE: the existing `test_clip_polygon_u_shape` fixture is *self-
    /// intersecting* (its inner edge at y=2 passes through the arm verticals at
    /// (2,2)/(8,2)), so `geometry_is_simple` is false for it and the self-
    /// intersection check — not the boundary gate — routes it to i_overlay. To
    /// isolate the boundary gate we need a clean simple U: solid base y∈[0,3]
    /// across x∈[0,10], arms x∈[0,3] and x∈[7,10] up to y=10, notch x∈[3,7].
    fn u_shape() -> Polygon<f64> {
        Polygon::new(
            LineString::from(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 10.0, y: 0.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 7.0, y: 10.0 },
                Coord { x: 7.0, y: 3.0 },
                Coord { x: 3.0, y: 3.0 },
                Coord { x: 3.0, y: 10.0 },
                Coord { x: 0.0, y: 10.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![],
        )
    }

    /// The flag's behavioral contract on a simple concave ring: OFF splits into
    /// clean parts (the #94 fallback), ON keeps S-H's single self-touching ring.
    /// Both are correct; the equivalence is proven by the two tests below.
    #[test]
    fn simple_u_fastpath_keeps_single_ring() {
        let u = u_shape();
        let bounds = TileBounds::new(0.0, 4.0, 10.0, 6.0);

        // The U-shape passes the simplicity check → `assume_simple` is true for
        // it in the real export path, so the flag applies to it.
        assert!(
            geometry_is_simple(&Geometry::Polygon(u.clone())),
            "U-shape is a simple polygon; assume_simple is true in prod"
        );

        // Flag OFF (default): the boundary gate fires even at assume_simple=true,
        // so the fallback yields the clean 2-part split.
        match clip_polygon(&u, &bounds, true, false).unwrap() {
            Geometry::MultiPolygon(mp) => assert_eq!(mp.0.len(), 2),
            other => panic!("flag off should split; got {other:?}"),
        }

        // Flag ON (#239): the boundary gate is skipped for this simple ring, so
        // S-H's single self-touching polygon is kept (no i_overlay).
        match clip_polygon(&u, &bounds, true, true).unwrap() {
            Geometry::Polygon(_) => {}
            other => panic!("flag on should keep the S-H single polygon; got {other:?}"),
        }
    }

    /// The equivalence the flag relies on: on a simple U, S-H's kept ring has the
    /// same enclosed AREA as i_overlay's split and leaves the mouth EMPTY under
    /// nonzero winding — so it renders identically despite being self-touching.
    #[test]
    fn fastpath_u_render_equivalent() {
        use geo::{Area, Contains};
        let u = u_shape();
        let bounds = TileBounds::new(0.0, 4.0, 10.0, 6.0);

        let sh = sutherland_hodgman::clip_polygon_sh(&u, &bounds).unwrap();
        let io = ioverlay_clip::clip_polygon_ioverlay(&u, &bounds).unwrap();

        // Notch center: inside the band, inside the mouth → NOT part of the U.
        let notch = Point::new(5.0, 5.0);
        assert!(!io.contains(&notch), "i_overlay: mouth empty");
        assert!(
            !sh.contains(&notch),
            "S-H: mouth also empty (winding cancels)"
        );
        assert!(
            (sh.unsigned_area() - io.unsigned_area()).abs() < 1e-9,
            "areas must match: sh={} io={}",
            sh.unsigned_area(),
            io.unsigned_area()
        );
    }

    /// Equivalence generalizes to a MULTI-mouth shape: a 3-tooth comb has two
    /// notches, and if S-H's bridge windings failed to cancel, area or fill would
    /// diverge here. They don't.
    #[test]
    fn fastpath_comb_render_equivalent() {
        use geo::{Area, Contains};
        // Base y∈[0,3] across x∈[0,15]; arms at x∈[0,3],[6,9],[12,15] up to y=10;
        // notches at x∈[3,6] and x∈[9,12].
        let comb = Polygon::new(
            LineString::from(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 15.0, y: 0.0 },
                Coord { x: 15.0, y: 10.0 },
                Coord { x: 12.0, y: 10.0 },
                Coord { x: 12.0, y: 3.0 },
                Coord { x: 9.0, y: 3.0 },
                Coord { x: 9.0, y: 10.0 },
                Coord { x: 6.0, y: 10.0 },
                Coord { x: 6.0, y: 3.0 },
                Coord { x: 3.0, y: 3.0 },
                Coord { x: 3.0, y: 10.0 },
                Coord { x: 0.0, y: 10.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![],
        );
        let bounds = TileBounds::new(0.0, 4.0, 15.0, 6.0);
        assert!(
            geometry_is_simple(&Geometry::Polygon(comb.clone())),
            "comb must be simple to be an assume_simple case"
        );

        let sh = sutherland_hodgman::clip_polygon_sh(&comb, &bounds).unwrap();
        let io = ioverlay_clip::clip_polygon_ioverlay(&comb, &bounds).unwrap();
        let notch1 = Point::new(4.5, 5.0);
        let notch2 = Point::new(10.5, 5.0);
        assert!(
            (sh.unsigned_area() - io.unsigned_area()).abs() < 1e-9,
            "areas must match across multiple mouths"
        );
        assert!(
            !sh.contains(&notch1) && !sh.contains(&notch2),
            "both mouths stay empty under S-H"
        );
    }

    // ========== WorldCoord-based Clipping Tests ==========

    mod world_tests {
        use super::*;
        use crate::tile::TileCoord;
        use crate::world_coord::{lng_lat_to_world, WorldBounds, WorldCoord};

        #[test]
        fn test_buffer_pixels_to_world_zoom0() {
            // At zoom 0, tile_size = 2^32, buffer = 2^32 * 8 / 4096
            let buffer = buffer_pixels_to_world(0, 8, 4096);
            let expected = (crate::world_coord::WORLD_SCALE * 8 / 4096) as u32;
            assert_eq!(buffer, expected);
        }

        #[test]
        fn test_buffer_pixels_to_world_zoom10() {
            // At zoom 10, tile_size = 2^22 = 4194304
            // buffer = 4194304 * 8 / 4096 = 8192
            let buffer = buffer_pixels_to_world(10, 8, 4096);
            assert_eq!(buffer, 8192);
        }

        #[test]
        fn test_buffer_pixels_to_world_consistency_with_degrees() {
            // Verify that the integer buffer is approximately consistent
            // with the f64 buffer for a specific tile
            let tile = TileCoord::new(512, 512, 10);
            let tile_bounds = tile.bounds();

            let f64_buffer = buffer_pixels_to_degrees(8, &tile_bounds, 4096);
            let world_buffer = buffer_pixels_to_world(10, 8, 4096);

            // Convert f64 buffer to approximate world units for comparison
            // At equator, 1 degree longitude ~ 2^32 / 360 world units
            let approx_world_from_f64 =
                (f64_buffer * crate::world_coord::WORLD_SCALE as f64 / 360.0) as u32;

            // Should be within ~10% (imprecise due to different calculation paths)
            let ratio = world_buffer as f64 / approx_world_from_f64 as f64;
            assert!(
                (0.8..=1.2).contains(&ratio),
                "Integer buffer ({}) should be roughly consistent with f64 buffer ({} -> ~{} world units), ratio={}",
                world_buffer, f64_buffer, approx_world_from_f64, ratio
            );
        }

        #[test]
        fn test_clip_point_world_inside() {
            let bounds = WorldBounds::new(1000, 1000, 5000, 5000);
            let point = WorldCoord::new(3000, 3000);
            assert!(clip_point_world(&point, &bounds).is_some());
        }

        #[test]
        fn test_clip_point_world_outside() {
            let bounds = WorldBounds::new(1000, 1000, 5000, 5000);
            let point = WorldCoord::new(6000, 3000);
            assert!(clip_point_world(&point, &bounds).is_none());
        }

        #[test]
        fn test_clip_point_world_on_boundary() {
            let bounds = WorldBounds::new(1000, 1000, 5000, 5000);
            let point = WorldCoord::new(5000, 3000);
            assert!(clip_point_world(&point, &bounds).is_some());
        }

        #[test]
        fn test_clip_polygon_world_fully_inside() {
            let bounds = WorldBounds::new(0, 0, 10000, 10000);
            let exterior = vec![
                WorldCoord::new(2000, 2000),
                WorldCoord::new(8000, 2000),
                WorldCoord::new(8000, 8000),
                WorldCoord::new(2000, 8000),
                WorldCoord::new(2000, 2000),
            ];

            let result = clip_polygon_world(&exterior, &[], &bounds);
            assert!(result.is_some());
            let (ext, _) = result.unwrap();
            // Fully inside -- should be returned as-is
            assert_eq!(ext.len(), exterior.len());
        }

        #[test]
        fn test_clip_polygon_world_fully_outside() {
            let bounds = WorldBounds::new(0, 0, 10000, 10000);
            let exterior = vec![
                WorldCoord::new(20000, 20000),
                WorldCoord::new(30000, 20000),
                WorldCoord::new(30000, 30000),
                WorldCoord::new(20000, 30000),
                WorldCoord::new(20000, 20000),
            ];

            let result = clip_polygon_world(&exterior, &[], &bounds);
            assert!(result.is_none());
        }

        #[test]
        fn test_clip_polygon_world_partial() {
            let bounds = WorldBounds::new(1000, 1000, 5000, 5000);
            // Polygon straddling the right edge
            let exterior = vec![
                WorldCoord::new(3000, 2000),
                WorldCoord::new(7000, 2000),
                WorldCoord::new(7000, 4000),
                WorldCoord::new(3000, 4000),
                WorldCoord::new(3000, 2000),
            ];

            let result = clip_polygon_world(&exterior, &[], &bounds);
            assert!(result.is_some());

            let (ext, _) = result.unwrap();
            for coord in &ext {
                assert!(
                    coord.x >= bounds.x_min && coord.x <= bounds.x_max,
                    "x={} out of bounds",
                    coord.x
                );
                assert!(
                    coord.y >= bounds.y_min && coord.y <= bounds.y_max,
                    "y={} out of bounds",
                    coord.y
                );
            }
        }

        #[test]
        fn test_polygon_to_world_rings_roundtrip() {
            // Verify that polygon_to_world_rings produces reasonable WorldCoord rings
            let poly = Polygon::new(
                LineString::from(vec![
                    Coord {
                        x: -73.985,
                        y: 40.748,
                    },
                    Coord {
                        x: -73.980,
                        y: 40.748,
                    },
                    Coord {
                        x: -73.980,
                        y: 40.752,
                    },
                    Coord {
                        x: -73.985,
                        y: 40.752,
                    },
                    Coord {
                        x: -73.985,
                        y: 40.748,
                    },
                ]),
                vec![],
            );

            let (ext, ints) = polygon_to_world_rings(&poly);
            assert_eq!(ext.len(), 5, "Should have 5 coords (4 vertices + close)");
            assert!(ints.is_empty(), "Should have no holes");

            // Verify coords are in expected range (NYC is in western hemisphere,
            // northern hemisphere, so x < WORLD_HALF, y < WORLD_HALF)
            for coord in &ext {
                assert!(
                    coord.x > 0 && coord.x < u32::MAX,
                    "x={} should be in valid range",
                    coord.x
                );
                assert!(
                    coord.y > 0 && coord.y < u32::MAX,
                    "y={} should be in valid range",
                    coord.y
                );
            }
        }

        #[test]
        fn test_worldcoord_bbox_computation() {
            let coords = vec![
                WorldCoord::new(100, 200),
                WorldCoord::new(500, 100),
                WorldCoord::new(300, 600),
            ];

            let bbox = worldcoord_bbox(&coords).unwrap();
            assert_eq!(bbox.x_min, 100);
            assert_eq!(bbox.y_min, 100);
            assert_eq!(bbox.x_max, 500);
            assert_eq!(bbox.y_max, 600);
        }

        #[test]
        fn test_worldcoord_bbox_empty() {
            let coords: Vec<WorldCoord> = vec![];
            assert!(worldcoord_bbox(&coords).is_none());
        }

        #[test]
        fn test_clip_polygon_world_with_real_tile() {
            // Test clipping a polygon in WorldCoord space using a real tile
            let tile = TileCoord::new(150, 192, 9);
            let bounds = WorldBounds::from_tile(&tile);
            let buffered = WorldBounds::from_tile_with_buffer(&tile, 8, 4096);

            // Create a polygon that spans the tile and slightly beyond
            let tile_f64 = tile.bounds();
            let center_lng = (tile_f64.lng_min + tile_f64.lng_max) / 2.0;
            let center_lat = (tile_f64.lat_min + tile_f64.lat_max) / 2.0;

            let exterior: Vec<WorldCoord> = vec![
                lng_lat_to_world(center_lng, center_lat),
                lng_lat_to_world(tile_f64.lng_max + 0.5, center_lat),
                lng_lat_to_world(tile_f64.lng_max + 0.5, tile_f64.lat_min - 0.5),
                lng_lat_to_world(center_lng, tile_f64.lat_min - 0.5),
                lng_lat_to_world(center_lng, center_lat),
            ];

            // Clip to unbuffered tile bounds
            let result = clip_polygon_world(&exterior, &[], &bounds);
            assert!(result.is_some(), "Should intersect the tile");

            // Clip to buffered tile bounds
            let result_buffered = clip_polygon_world(&exterior, &[], &buffered);
            assert!(
                result_buffered.is_some(),
                "Should intersect the buffered tile"
            );
        }
    }
}