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
//! Boundaries layer — country and administrative boundaries.
//!
//! Processes features from multiple data sources:
//! - **`NaturalEarth`** (z0-5): Admin boundary lines from `ne_10m_admin_*`
//! - **OSM** (z6+): Admin boundaries from relations with India bbox fix
//! - **`IndiaBoundary`**: Official Survey of India `GeoJSON` boundaries
//! - **Overture**: `divisions/division_boundary` features

use std::sync::Arc;

use geo::{BooleanOps, BoundingRect, Buffer, Intersects};

use crate::layers::{Layer, mark_foreign, take_owner};
use crate::source::input::{DataSource, InputFeature};
use crate::tile::feature::PropValue;

use super::buildings::ProcessedFeature;

/// How far the mask reaches past the Survey of India line, in degrees
/// (about 550 m at the equator), so a source's own copy of the same border
/// goes too and only the Survey of India line is drawn there.
const MASK_MARGIN_DEG: f64 = 0.005;

/// How far inside the Survey of India line a region or county line must
/// lie to count as inside India, in degrees (about 2 km): a line along the
/// border itself is a neighbour's own border and stays.
const INNER_MARGIN_DEG: f64 = 0.02;

/// How far a claim-marked line is kept away from India, in degrees: nothing of
/// it is drawn inside the land, and nothing within this distance outside the
/// edge, so a claim line that weaves along the border leaves no dashes
/// hugging it.
const CLAIM_MARGIN_DEG: f64 = 0.02;

/// The land inside the Survey of India outline (`--india-boundary`).
///
/// India is always the Survey of India map. Overture and Natural Earth draw
/// the Line of Control, and the lines around Aksai Chin, as country lines
/// (often without `is_disputed`), and OSM tags them `boundary=disputed`.
/// [`IndiaMask::clip`] removes every country line inside this land, so only
/// the Survey of India line marks India's border.
#[derive(Debug)]
pub struct IndiaMask {
    land: geo::MultiPolygon<f64>,
    /// The land shrunk by [`INNER_MARGIN_DEG`].
    inner: geo::MultiPolygon<f64>,
    /// The land grown by [`CLAIM_MARGIN_DEG`]: where no claim-marked line is
    /// drawn.
    claim_land: geo::MultiPolygon<f64>,
    bounds: geo::Rect<f64>,
    claim_bounds: geo::Rect<f64>,
}

impl IndiaMask {
    /// Build the mask from the `--india-boundary` features: every closed ring
    /// (or polygon exterior) is one piece of land. `None` when there is no
    /// closed ring.
    pub fn from_features(features: &[InputFeature]) -> Option<Self> {
        let pieces: Vec<geo::Polygon<f64>> = features
            .iter()
            .flat_map(|f| closed_rings(&f.geometry))
            .map(|ring| geo::Polygon::new(ring, vec![]))
            .collect();
        if pieces.is_empty() {
            return None;
        }
        let pieces = geo::MultiPolygon::new(pieces);
        let land = pieces.buffer(MASK_MARGIN_DEG);
        let inner = pieces.buffer(-INNER_MARGIN_DEG);
        let claim_land = pieces.buffer(CLAIM_MARGIN_DEG);
        let bounds = land.bounding_rect()?;
        let claim_bounds = claim_land.bounding_rect()?;
        Some(Self {
            land,
            inner,
            claim_land,
            bounds,
            claim_bounds,
        })
    }

    /// The Survey of India map inside India's land, in five rules.
    /// A boundary line of any kind carrying a claim (`disputed`,
    /// `disputed_by`, `claimed_by`) keeps only its part outside the land grown
    /// by the claim margin (`CLAIM_MARGIN_DEG`): no claim line is drawn inside
    /// India or hugging its edge from outside. Other `kind=country` lines keep
    /// only their part outside the mask. A region, county or locality line
    /// marked foreign by its source keeps only its part outside the land shrunk
    /// by the inner margin (`INNER_MARGIN_DEG`): inside India only the lines
    /// between Indian divisions are drawn, and they carry no claim. A places label marked
    /// foreign (a division of another country, or a claim name) inside the
    /// land is dropped. Every other feature passes unchanged. The private
    /// owner mark is removed from all.
    pub fn clip(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
        let (feature, foreign) = take_owner(feature);
        match feature.layer {
            Layer::Places => self.clip_label(feature, foreign),
            Layer::Boundaries if carries_claim(&feature) => self.clip_claim_line(feature),
            Layer::Boundaries if is_country(&feature) => self.clip_country_line(feature),
            Layer::Boundaries => self.clip_admin_line(feature, foreign),
            _ => Some(feature),
        }
    }

    /// A foreign admin label whose point is on the land is dropped.
    fn clip_label(&self, feature: ProcessedFeature, foreign: bool) -> Option<ProcessedFeature> {
        use geo::Contains;
        if !foreign {
            return Some(feature);
        }
        match feature.geometry.as_ref() {
            geo::Geometry::Point(point)
                if self.bounds.contains(point) && self.land.contains(point) =>
            {
                None
            }
            _ => Some(feature),
        }
    }

    /// The part of a `kind=country` line outside the mask.
    fn clip_country_line(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
        let lines = match feature.geometry.as_ref() {
            geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
            geo::Geometry::MultiLineString(lines) => lines.clone(),
            _ => return Some(feature),
        };
        match lines.bounding_rect() {
            Some(rect) if rect.intersects(&self.bounds) => {}
            _ => return Some(feature),
        }
        let outside = self.land.clip(&lines, true);
        if outside.0.is_empty() {
            return None;
        }
        Some(ProcessedFeature {
            geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
            ..feature
        })
    }

    /// The part of a claim-carrying line (any kind) outside the land grown by
    /// [`CLAIM_MARGIN_DEG`].
    fn clip_claim_line(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
        let lines = match feature.geometry.as_ref() {
            geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
            geo::Geometry::MultiLineString(lines) => lines.clone(),
            _ => return Some(feature),
        };
        match lines.bounding_rect() {
            Some(rect) if rect.intersects(&self.claim_bounds) => {}
            _ => return Some(feature),
        }
        let outside = self.claim_land.clip(&lines, true);
        if outside.0.is_empty() {
            return None;
        }
        Some(ProcessedFeature {
            geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
            ..feature
        })
    }

    /// The part of a foreign region, county or locality line outside the
    /// shrunk land.
    fn clip_admin_line(
        &self,
        feature: ProcessedFeature,
        foreign: bool,
    ) -> Option<ProcessedFeature> {
        if !foreign {
            return Some(feature);
        }
        let lines = match feature.geometry.as_ref() {
            geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
            geo::Geometry::MultiLineString(lines) => lines.clone(),
            _ => return Some(feature),
        };
        match lines.bounding_rect() {
            Some(rect) if rect.intersects(&self.bounds) => {}
            _ => return Some(feature),
        }
        let outside = self.inner.clip(&lines, true);
        if outside.0.is_empty() {
            return None;
        }
        Some(ProcessedFeature {
            geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
            ..feature
        })
    }
}

/// Whether a boundaries feature says its line is claimed or controlled by
/// someone: `disputed`, `disputed_by` or `claimed_by`.
fn carries_claim(feature: &ProcessedFeature) -> bool {
    feature.properties.iter().any(|(k, v)| {
        matches!(k.as_str(), "disputed_by" | "claimed_by")
            || (k == "disputed" && *v == PropValue::Bool(true))
    })
}

/// The closed rings of a line or polygon geometry.
fn closed_rings(geometry: &geo::Geometry<f64>) -> Vec<geo::LineString<f64>> {
    let is_ring = |line: &&geo::LineString<f64>| line.is_closed() && line.0.len() >= 4;
    match geometry {
        geo::Geometry::LineString(line) => [line].into_iter().filter(is_ring).cloned().collect(),
        geo::Geometry::MultiLineString(lines) => lines.0.iter().filter(is_ring).cloned().collect(),
        geo::Geometry::Polygon(polygon) => vec![polygon.exterior().clone()],
        geo::Geometry::MultiPolygon(polygons) => {
            polygons.0.iter().map(|p| p.exterior().clone()).collect()
        }
        _ => Vec::new(),
    }
}

/// Whether a boundaries feature is a `kind=country` line.
fn is_country(feature: &ProcessedFeature) -> bool {
    feature
        .properties
        .iter()
        .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
}

/// India bounding box \[`min_lon`, `min_lat`, `max_lon`, `max_lat`\].
///
/// OSM `admin_level=2` boundaries within this bbox are suppressed
/// and replaced by the official India boundary `GeoJSON`.
const INDIA_BBOX: [f64; 4] = [68.0, 6.5, 97.5, 37.2];

/// Process a feature into a boundaries layer feature.
///
/// Routes to the appropriate handler based on data source.
pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
    match &feature.source {
        DataSource::Overture { .. } => process_overture(feature),
        DataSource::NaturalEarth { .. } => process_ne(feature),
        DataSource::Osm { .. } => process_osm(feature),
        DataSource::IndiaBoundary => process_india(feature),
        _ => None,
    }
}

/// Process Overture `divisions/division_boundary` features.
///
/// The kind comes from `subtype`, not `admin_level`. Overture's
/// `admin_level` is a relative depth (country and region boundaries are
/// both 1, counties are 2), so reading it on the OSM scale drew counties as
/// national borders and dropped every country and region boundary.
/// `kind_detail` carries the OSM-equivalent level because the protomaps
/// style draws `kind_detail <= 2` as a national border.
fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
    let (kind, admin_level, min_zoom) = overture_subtype_to_kind(feature.get_str("subtype")?)?;

    let disputed = matches!(
        feature.properties.get("is_disputed"),
        Some(PropValue::Bool(true))
    );

    let sort_rank = if disputed { 288 } else { 289 };

    let mut properties = Vec::with_capacity(4);
    properties.push(("kind".into(), PropValue::Str(kind.into())));
    properties.push(("kind_detail".into(), PropValue::I64(admin_level)));

    if disputed {
        properties.push(("disputed".into(), PropValue::Bool(true)));
    }
    if feature
        .get_str("country")
        .is_some_and(|c| !c.eq_ignore_ascii_case("IN"))
    {
        mark_foreign(&mut properties);
    }

    Some(ProcessedFeature {
        id: feature.id,
        geometry: feature.geometry.clone(),
        layer: Layer::Boundaries,
        min_zoom,
        max_zoom: 15,
        sort_rank,
        properties,
    })
}

/// Process Natural Earth admin boundary lines (z0-5).
///
/// Maps NE `featurecla` attribute to kind and disputed status.
fn process_ne(feature: &InputFeature) -> Option<ProcessedFeature> {
    let source_layer = feature.ne_source_layer()?;

    let is_boundary_layer = source_layer.starts_with("ne_10m_admin_0_boundary")
        || source_layer.starts_with("ne_10m_admin_1");

    if !is_boundary_layer {
        return None;
    }

    let featurecla = feature.get_str("featurecla").unwrap_or("");

    let (kind, admin_level, disputed) = match featurecla {
        "International boundary (verify)" => ("country", 2i64, false),
        "Disputed (please verify)" => ("country", 2, true),
        "Line of control (please verify)" => ("country", 2, true),
        "Indefinite (please verify)" => ("country", 2, true),
        "Lease limit" => ("country", 2, true),
        "Overlay limit" => ("country", 2, true),
        "Admin-1 boundary" => ("region", 4, false),
        "Admin-1 statistical boundary" => ("region", 4, false),
        "Admin-1 region boundary" => ("region", 4, false),
        "Unrecognized" => ("country", 2, true),
        _ if featurecla.contains("disputed") || featurecla.contains("Disputed") => {
            ("country", 2, true)
        }
        _ if featurecla.contains("Admin-1") => ("region", 4, false),
        _ => ("country", 2, false),
    };

    let sort_rank = if disputed { 288 } else { 289 };

    let mut properties = Vec::with_capacity(4);
    properties.push(("kind".into(), PropValue::Str(kind.into())));
    properties.push(("kind_detail".into(), PropValue::I64(admin_level)));

    if disputed {
        properties.push(("disputed".into(), PropValue::Bool(true)));
    }
    // An admin-1 line of another country: `adm0_a3` is the country the
    // Natural Earth line belongs to.
    if kind == "region"
        && feature
            .get_str("adm0_a3")
            .is_some_and(|c| !c.eq_ignore_ascii_case("IND"))
    {
        mark_foreign(&mut properties);
    }

    // Respect NE data's per-feature min_zoom (Planetiler reads this field too).
    // NE features have different min_zoom values (0–5) controlling when each
    // boundary line first appears. Without this, ALL boundaries show at z0.
    let ne_min_zoom = feature
        .get_f64("min_zoom")
        .map(|v| (v as u8).min(5))
        .or_else(|| feature.get_i64("min_zoom").map(|v| (v as u8).min(5)))
        .unwrap_or(0);

    Some(ProcessedFeature {
        id: feature.id,
        geometry: feature.geometry.clone(),
        layer: Layer::Boundaries,
        min_zoom: ne_min_zoom,
        max_zoom: 5,
        sort_rank,
        properties,
    })
}

/// Process OSM admin boundary features (z6+).
///
/// Uses `admin_level` from parent relations. Suppresses `admin_level=2`
/// boundaries within the India bbox (replaced by official `GeoJSON`).
fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
    if !feature.can_be_line() {
        return None;
    }

    let relations = feature.osm_relations();
    if relations.is_empty() {
        // Fall back to tags on the way itself
        if feature.has_tag("boundary", "administrative") || feature.has_tag("boundary", "disputed")
        {
            let admin_level = feature
                .get_str("admin_level")
                .and_then(|v| v.parse::<i64>().ok())
                .unwrap_or(2);

            let disputed = feature.has_tag("boundary", "disputed")
                || feature.get_str("disputed").is_some_and(|v| v == "yes")
                || feature
                    .get_str("boundary")
                    .is_some_and(|v| v == "disputed" || v == "claim");

            if admin_level == 2 && is_within_india_bbox(feature) && !disputed {
                return None;
            }

            let (kind, min_zoom) = admin_level_to_kind(admin_level)?;
            let sort_rank = if disputed { 288 } else { 289 };

            let mut properties = Vec::with_capacity(4);
            properties.push(("kind".into(), PropValue::Str(kind.into())));
            properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
            if disputed {
                properties.push(("disputed".into(), PropValue::Bool(true)));
            }
            push_claim_tags(feature, &mut properties);

            return Some(ProcessedFeature {
                id: feature.id,
                geometry: feature.geometry.clone(),
                layer: Layer::Boundaries,
                min_zoom,
                max_zoom: 15,
                sort_rank,
                properties,
            });
        }
        return None;
    }

    // Use the highest-priority (lowest admin_level) relation
    let best_relation = relations
        .iter()
        .filter(|r| {
            r.tags.get("type").is_some_and(|t| t == "boundary")
                || r.tags
                    .get("boundary")
                    .is_some_and(|b| b == "administrative" || b == "disputed")
        })
        .min_by_key(|r| r.admin_level.unwrap_or(99));

    let rel = best_relation?;
    let admin_level = i64::from(rel.admin_level.unwrap_or(2));

    let disputed = rel.disputed
        || rel
            .tags
            .get("boundary")
            .is_some_and(|v| v == "disputed" || v == "claim")
        || rel.tags.get("disputed").is_some_and(|v| v == "yes");

    // India fix: skip admin_level=2 within India bbox
    if admin_level == 2 && is_within_india_bbox(feature) && !disputed {
        return None;
    }

    let (kind, min_zoom) = admin_level_to_kind(admin_level)?;
    let sort_rank = if disputed { 288 } else { 289 };

    let mut properties = Vec::with_capacity(5);
    properties.push(("kind".into(), PropValue::Str(kind.into())));
    properties.push(("kind_detail".into(), PropValue::I64(admin_level)));

    if disputed {
        properties.push(("disputed".into(), PropValue::Bool(true)));
    }

    push_claim_tags(feature, &mut properties);
    // A line that is a member of an admin relation of another country.
    if relations
        .iter()
        .filter_map(|r| relation_country(&r.tags))
        .any(|code| code != "IN")
    {
        mark_foreign(&mut properties);
    }

    Some(ProcessedFeature {
        id: feature.id,
        geometry: feature.geometry.clone(),
        layer: Layer::Boundaries,
        min_zoom,
        max_zoom: 15,
        sort_rank,
        properties,
    })
}

/// Copy the claim tags of an OSM way (`disputed_by`, `claimed_by`) into the
/// feature properties, so [`carries_claim`] sees them.
fn push_claim_tags(feature: &InputFeature, properties: &mut Vec<(String, PropValue)>) {
    for key in ["disputed_by", "claimed_by"] {
        if let Some(value) = feature.get_str(key) {
            properties.push((key.into(), PropValue::Str(value.to_string())));
        }
    }
}

/// The ISO 3166-1 code of the country an OSM admin relation belongs to: its
/// `ISO3166-1` tags, else the country part of `ISO3166-2` (`PK-GB`).
fn relation_country(tags: &std::collections::HashMap<String, String>) -> Option<String> {
    let code = ["ISO3166-1:alpha2", "ISO3166-1"]
        .iter()
        .find_map(|key| tags.get(*key))
        .or_else(|| tags.get("ISO3166-2"))?;
    let country = code.split(['-', ';']).next()?.trim().to_ascii_uppercase();
    (country.len() == 2).then_some(country)
}

/// Process India boundary `GeoJSON` features (z0+). From z0, because
/// [`IndiaMask`] removes the Natural Earth country lines inside India at
/// z0–z5 too.
fn process_india(feature: &InputFeature) -> Option<ProcessedFeature> {
    let kind = feature.get_str("kind").unwrap_or("country");
    let kind_detail = feature.get_i64("kind_detail").unwrap_or(2);

    let mut properties = Vec::with_capacity(3);
    properties.push(("kind".into(), PropValue::Str(kind.to_string())));
    properties.push(("kind_detail".into(), PropValue::I64(kind_detail)));

    if let Some(name) = feature.get_str("name") {
        properties.push(("name".into(), PropValue::Str(name.to_string())));
    }

    Some(ProcessedFeature {
        id: feature.id,
        geometry: feature.geometry.clone(),
        layer: Layer::Boundaries,
        min_zoom: 0,
        max_zoom: 15,
        sort_rank: 289,
        properties,
    })
}

/// Map an Overture division `subtype` to (kind, OSM-equivalent `admin_level`, `min_zoom`).
///
/// Levels match [`admin_level_to_kind`]: country 2, region 4, county 6,
/// locality 8. Subtypes finer than locality are dropped, as OSM levels
/// above 8 are.
fn overture_subtype_to_kind(subtype: &str) -> Option<(&'static str, i64, u8)> {
    match subtype {
        "country" | "dependency" => Some(("country", 2, 6)),
        "macroregion" | "region" => Some(("region", 4, 6)),
        "macrocounty" | "county" => Some(("county", 6, 8)),
        "localadmin" | "locality" | "borough" => Some(("locality", 8, 10)),
        _ => None,
    }
}

/// Map `admin_level` integer to (kind, `min_zoom`).
///
/// Returns `None` for `admin_level` > 8, matching Planetiler which drops
/// these entirely.
const fn admin_level_to_kind(admin_level: i64) -> Option<(&'static str, u8)> {
    match admin_level {
        2 => Some(("country", 6)),
        3 | 4 => Some(("region", 6)),
        5 | 6 => Some(("county", 8)),
        7 | 8 => Some(("locality", 10)),
        _ => None,
    }
}

/// Check if a feature's bbox or geometry centroid is within the India bbox.
fn is_within_india_bbox(feature: &InputFeature) -> bool {
    if let Some(bbox) = feature.bbox {
        let cx = (bbox[0] + bbox[2]) / 2.0;
        let cy = (bbox[1] + bbox[3]) / 2.0;
        return (INDIA_BBOX[0]..=INDIA_BBOX[2]).contains(&cx)
            && (INDIA_BBOX[1]..=INDIA_BBOX[3]).contains(&cy);
    }

    // Fall back to checking first coordinate of geometry
    match feature.geometry.as_ref() {
        geo::Geometry::LineString(ls) => {
            if let Some(coord) = ls.0.first() {
                return coord.x >= INDIA_BBOX[0]
                    && coord.x <= INDIA_BBOX[2]
                    && coord.y >= INDIA_BBOX[1]
                    && coord.y <= INDIA_BBOX[3];
            }
        }
        geo::Geometry::Point(pt) => {
            return pt.x() >= INDIA_BBOX[0]
                && pt.x() <= INDIA_BBOX[2]
                && pt.y() >= INDIA_BBOX[1]
                && pt.y() <= INDIA_BBOX[3];
        }
        _ => {}
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::input::{DataSource, OsmElementType, RelationInfo};
    use std::collections::HashMap;
    use std::sync::Arc;

    fn props_map(props: &[(&str, PropValue)]) -> HashMap<String, PropValue> {
        let mut m = HashMap::new();
        for (k, v) in props {
            m.insert(k.to_string(), v.clone());
        }
        m
    }

    fn line_geom() -> Arc<geo::Geometry<f64>> {
        Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
            (0.0, 0.0),
            (1.0, 1.0),
        ])))
    }

    fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
        InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: props_map(props),
            bbox: None,
            source: DataSource::Overture {
                theme: String::new(),
                otype: String::new(),
            },
        }
    }

    fn make_ne_feature(layer: &str, props: &[(&str, PropValue)]) -> InputFeature {
        InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: props_map(props),
            bbox: None,
            source: DataSource::NaturalEarth {
                source_layer: layer.to_string(),
            },
        }
    }

    fn make_osm_way(props: &[(&str, PropValue)], relations: Vec<RelationInfo>) -> InputFeature {
        InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: props_map(props),
            bbox: None,
            source: DataSource::Osm {
                element_type: OsmElementType::Way,
                relations,
            },
        }
    }

    fn make_india_feature(props: &[(&str, PropValue)]) -> InputFeature {
        InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: props_map(props),
            bbox: None,
            source: DataSource::IndiaBoundary,
        }
    }

    fn rel_with(admin_level: Option<i32>, disputed: bool, tags: &[(&str, &str)]) -> RelationInfo {
        let mut t = HashMap::new();
        for (k, v) in tags {
            t.insert(k.to_string(), v.to_string());
        }
        RelationInfo {
            id: 1,
            admin_level,
            disputed,
            role: String::new(),
            tags: t,
        }
    }

    // ─── dispatch (process) ────────────────────────────────────────────

    #[test]
    fn dispatch_unsupported_source_returns_none() {
        let feat = InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::LandPolygons,
        };
        assert!(process(&feat).is_none());

        let feat2 = InputFeature {
            source: DataSource::WaterPolygons,
            ..feat
        };
        assert!(process(&feat2).is_none());
    }

    // ─── process_overture ──────────────────────────────────────────────

    fn kind_of(result: &ProcessedFeature) -> Option<&PropValue> {
        result
            .properties
            .iter()
            .find(|(k, _)| k == "kind")
            .map(|(_, v)| v)
    }

    fn detail_of(result: &ProcessedFeature) -> Option<&PropValue> {
        result
            .properties
            .iter()
            .find(|(k, _)| k == "kind_detail")
            .map(|(_, v)| v)
    }

    /// Values observed in the 2026-08-19.0 release: a US county boundary
    /// carries `admin_level = 2`. It must still be a county, not a country.
    #[test]
    fn overture_county_with_relative_admin_level_2_is_not_a_country() {
        let feat = make_feature(&[
            ("subtype", PropValue::Str("county".into())),
            ("admin_level", PropValue::I64(2)),
        ]);
        let result = process(&feat).unwrap();
        assert_eq!(kind_of(&result), Some(&PropValue::Str("county".into())));
        assert_eq!(detail_of(&result), Some(&PropValue::I64(6)));
        assert_eq!(result.min_zoom, 8);
    }

    /// Country and region boundaries carry `admin_level = 1` in Overture.
    /// On the OSM scale that level was dropped; both must now survive.
    #[test]
    fn overture_country_with_relative_admin_level_1_is_kept() {
        let feat = make_feature(&[
            ("subtype", PropValue::Str("country".into())),
            ("admin_level", PropValue::I64(1)),
        ]);
        let result = process(&feat).unwrap();
        assert_eq!(result.layer, Layer::Boundaries);
        assert_eq!(kind_of(&result), Some(&PropValue::Str("country".into())));
        assert_eq!(detail_of(&result), Some(&PropValue::I64(2)));
        assert_eq!(result.min_zoom, 6);
        assert_eq!(result.sort_rank, 289);
    }

    #[test]
    fn overture_region_with_relative_admin_level_1_is_kept() {
        let feat = make_feature(&[
            ("subtype", PropValue::Str("region".into())),
            ("admin_level", PropValue::I64(1)),
        ]);
        let result = process(&feat).unwrap();
        assert_eq!(kind_of(&result), Some(&PropValue::Str("region".into())));
        assert_eq!(detail_of(&result), Some(&PropValue::I64(4)));
    }

    #[test]
    fn overture_subtype_levels_follow_the_osm_scale() {
        let cases = [
            ("dependency", "country", 2, 6),
            ("macroregion", "region", 4, 6),
            ("macrocounty", "county", 6, 8),
            ("localadmin", "locality", 8, 10),
            ("locality", "locality", 8, 10),
            ("borough", "locality", 8, 10),
        ];
        for (subtype, kind, level, zoom) in cases {
            let feat = make_feature(&[("subtype", PropValue::Str(subtype.into()))]);
            let result = process(&feat).unwrap();
            assert_eq!(
                kind_of(&result),
                Some(&PropValue::Str(kind.into())),
                "{subtype}"
            );
            assert_eq!(
                detail_of(&result),
                Some(&PropValue::I64(level)),
                "{subtype}"
            );
            assert_eq!(result.min_zoom, zoom, "{subtype}");
        }
    }

    #[test]
    fn overture_neighborhood_boundaries_are_dropped() {
        for subtype in ["macrohood", "neighborhood", "microhood"] {
            let feat = make_feature(&[("subtype", PropValue::Str(subtype.into()))]);
            assert!(process(&feat).is_none(), "{subtype}");
        }
    }

    #[test]
    fn overture_boundary_without_subtype_is_dropped() {
        let feat = make_feature(&[("admin_level", PropValue::I64(2))]);
        assert!(process(&feat).is_none());
    }

    /// `is_disputed` is a boolean column in the Overture schema.
    #[test]
    fn overture_disputed_boolean_lowers_sort_rank() {
        let feat = make_feature(&[
            ("subtype", PropValue::Str("country".into())),
            ("is_disputed", PropValue::Bool(true)),
        ]);
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 288);
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "disputed" && *v == PropValue::Bool(true))
        );
    }

    #[test]
    fn overture_undisputed_boolean_keeps_default_sort_rank() {
        let feat = make_feature(&[
            ("subtype", PropValue::Str("country".into())),
            ("is_disputed", PropValue::Bool(false)),
        ]);
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 289);
        assert!(!result.properties.iter().any(|(k, _)| k == "disputed"));
    }
    // ─── process_ne ────────────────────────────────────────────────────

    #[test]
    fn ne_non_boundary_layer_returns_none() {
        let feat = make_ne_feature("ne_10m_lakes", &[]);
        assert!(process(&feat).is_none());
    }

    /// Every Natural Earth `featurecla` value, with the kind, admin level and
    /// disputed flag the NE boundary attributes document for it, and the
    /// protomaps sort rank (288 disputed, 289 otherwise). Unknown
    /// values fall back on their "Disputed" or "Admin-1" keyword.
    #[test]
    fn ne_featurecla_values_map_to_kind_level_and_disputed() {
        let cases = [
            ("Disputed (please verify)", "country", 2, true, 288),
            ("Line of control (please verify)", "country", 2, true, 288),
            ("Indefinite (please verify)", "country", 2, true, 288),
            ("Lease limit", "country", 2, true, 288),
            ("Overlay limit", "country", 2, true, 288),
            ("Unrecognized", "country", 2, true, 288),
            ("Some weird disputed thing", "country", 2, true, 288),
            ("Something Disputed weird", "country", 2, true, 288),
            ("Admin-1 boundary", "region", 4, false, 289),
            ("Admin-1 statistical boundary", "region", 4, false, 289),
            ("Admin-1 region boundary", "region", 4, false, 289),
            ("Custom Admin-1 thing", "region", 4, false, 289),
        ];
        for (featurecla, kind, level, disputed, rank) in cases {
            let feat = make_ne_feature(
                "ne_10m_admin_0_boundary_lines_land",
                &[("featurecla", PropValue::Str(featurecla.into()))],
            );
            let result = process(&feat).expect(featurecla);
            let prop = |key: &str| {
                result
                    .properties
                    .iter()
                    .find(|(k, _)| k == key)
                    .map(|(_, v)| v.clone())
            };
            assert_eq!(
                prop("kind"),
                Some(PropValue::Str(kind.into())),
                "{featurecla}"
            );
            assert_eq!(
                prop("kind_detail"),
                Some(PropValue::I64(level)),
                "{featurecla}"
            );
            assert_eq!(
                prop("disputed"),
                disputed.then_some(PropValue::Bool(true)),
                "{featurecla}"
            );
            assert_eq!(result.sort_rank, rank, "{featurecla}");
        }
    }

    #[test]
    fn ne_admin_0_international_boundary() {
        let feat = make_ne_feature(
            "ne_10m_admin_0_boundary_lines_land",
            &[(
                "featurecla",
                PropValue::Str("International boundary (verify)".into()),
            )],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.layer, Layer::Boundaries);
        assert_eq!(result.max_zoom, 5);
        assert_eq!(result.sort_rank, 289);
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
        );
    }

    #[test]
    fn ne_unknown_default_country() {
        let feat = make_ne_feature(
            "ne_10m_admin_0_boundary_lines_land",
            &[("featurecla", PropValue::Str("Mystery line".into()))],
        );
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
        );
        assert_eq!(result.sort_rank, 289);
    }

    #[test]
    fn ne_missing_featurecla_default_country() {
        let feat = make_ne_feature("ne_10m_admin_0_boundary_lines_land", &[]);
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
        );
    }

    #[test]
    fn ne_min_zoom_from_f64_clamped() {
        let feat = make_ne_feature(
            "ne_10m_admin_0_boundary_lines_land",
            &[
                ("featurecla", PropValue::Str("Mystery".into())),
                ("min_zoom", PropValue::F64(8.0)),
            ],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.min_zoom, 5);
    }

    #[test]
    fn ne_min_zoom_from_f64_within_range() {
        let feat = make_ne_feature(
            "ne_10m_admin_0_boundary_lines_land",
            &[
                ("featurecla", PropValue::Str("Mystery".into())),
                ("min_zoom", PropValue::F64(3.0)),
            ],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.min_zoom, 3);
    }

    #[test]
    fn ne_min_zoom_from_i64() {
        let feat = make_ne_feature(
            "ne_10m_admin_0_boundary_lines_land",
            &[
                ("featurecla", PropValue::Str("Mystery".into())),
                ("min_zoom", PropValue::I64(2)),
            ],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.min_zoom, 2);
    }

    #[test]
    fn ne_min_zoom_default_zero() {
        let feat = make_ne_feature(
            "ne_10m_admin_0_boundary_lines_land",
            &[("featurecla", PropValue::Str("Mystery".into()))],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.min_zoom, 0);
    }

    // ─── process_osm ───────────────────────────────────────────────────

    #[test]
    fn osm_non_line_returns_none() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::Osm {
                element_type: OsmElementType::Way,
                relations: vec![],
            },
        };
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_no_relations_no_tag_returns_none() {
        let feat = make_osm_way(&[], vec![]);
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_no_relations_with_admin_tag() {
        let feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("administrative".into())),
                ("admin_level", PropValue::Str("4".into())),
            ],
            vec![],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.min_zoom, 6);
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
        );
    }

    /// A way with no relation and no usable `admin_level` is treated as a
    /// country border.
    #[test]
    fn osm_no_relations_missing_or_unparseable_admin_level_is_a_country() {
        let missing = vec![("boundary", PropValue::Str("administrative".into()))];
        let mut unparseable = missing.clone();
        unparseable.push(("admin_level", PropValue::Str("not-a-number".into())));
        for tags in [missing, unparseable] {
            let result = process(&make_osm_way(&tags, vec![])).expect("a boundary");
            assert_eq!(
                kind_of(&result),
                Some(&PropValue::Str("country".into())),
                "{tags:?}"
            );
        }
    }

    #[test]
    fn osm_no_relations_dropped_admin_level_returns_none() {
        let feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("administrative".into())),
                ("admin_level", PropValue::Str("9".into())),
            ],
            vec![],
        );
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_no_relations_boundary_disputed_tag() {
        let feat = make_osm_way(&[("boundary", PropValue::Str("disputed".into()))], vec![]);
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 288);
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "disputed" && *v == PropValue::Bool(true))
        );
    }

    #[test]
    fn osm_no_relations_disputed_yes_tag() {
        let feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("administrative".into())),
                ("admin_level", PropValue::Str("2".into())),
                ("disputed", PropValue::Str("yes".into())),
            ],
            vec![],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 288);
    }

    #[test]
    fn osm_no_relations_boundary_claim() {
        let feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("claim".into())),
                ("admin_level", PropValue::Str("2".into())),
            ],
            vec![],
        );
        // boundary=claim doesn't trigger has_tag("boundary","administrative") nor "disputed"
        // so it falls into the empty-relations + no-tag branch → None
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_no_relations_india_level_2_suppressed() {
        let mut feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("administrative".into())),
                ("admin_level", PropValue::Str("2".into())),
            ],
            vec![],
        );
        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]); // inside India
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_no_relations_india_level_2_disputed_kept() {
        let mut feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("disputed".into())),
                ("admin_level", PropValue::Str("2".into())),
            ],
            vec![],
        );
        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 288);
    }

    #[test]
    fn osm_no_relations_india_level_4_kept() {
        let mut feat = make_osm_way(
            &[
                ("boundary", PropValue::Str("administrative".into())),
                ("admin_level", PropValue::Str("4".into())),
            ],
            vec![],
        );
        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
        assert!(process(&feat).is_some());
    }

    #[test]
    fn osm_relations_picks_lowest_admin_level() {
        let feat = make_osm_way(
            &[],
            vec![
                rel_with(Some(6), false, &[("type", "boundary")]),
                rel_with(Some(2), false, &[("type", "boundary")]),
                rel_with(Some(4), false, &[("type", "boundary")]),
            ],
        );
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
        );
    }

    #[test]
    fn osm_relations_filter_boundary_administrative() {
        let feat = make_osm_way(
            &[],
            vec![rel_with(Some(4), false, &[("boundary", "administrative")])],
        );
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
        );
    }

    #[test]
    fn osm_relations_filter_boundary_disputed() {
        let feat = make_osm_way(
            &[],
            vec![rel_with(Some(2), false, &[("boundary", "disputed")])],
        );
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 288);
    }

    #[test]
    fn osm_relations_no_match_returns_none() {
        let feat = make_osm_way(
            &[],
            vec![rel_with(Some(2), false, &[("type", "multipolygon")])],
        );
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_relations_admin_level_default_when_missing() {
        let feat = make_osm_way(&[], vec![rel_with(None, false, &[("type", "boundary")])]);
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(2))
        );
    }

    #[test]
    fn osm_relations_dropped_admin_level_returns_none() {
        let feat = make_osm_way(&[], vec![rel_with(Some(9), false, &[("type", "boundary")])]);
        assert!(process(&feat).is_none());
    }

    /// Each of the three ways OSM marks a relation as disputed gives the
    /// disputed sort rank (288).
    #[test]
    fn osm_relations_disputed_by_flag_claim_or_disputed_tag() {
        let relations = [
            rel_with(Some(2), true, &[("type", "boundary")]),
            rel_with(
                Some(2),
                false,
                &[("type", "boundary"), ("boundary", "claim")],
            ),
            rel_with(Some(2), false, &[("type", "boundary"), ("disputed", "yes")]),
        ];
        for rel in relations {
            let tags = format!("{:?}", rel.tags);
            let result = process(&make_osm_way(&[], vec![rel])).expect("a boundary");
            assert_eq!(result.sort_rank, 288, "{tags}");
        }
    }

    #[test]
    fn osm_relations_india_level_2_suppressed() {
        let mut feat = make_osm_way(&[], vec![rel_with(Some(2), false, &[("type", "boundary")])]);
        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
        assert!(process(&feat).is_none());
    }

    #[test]
    fn osm_relations_india_level_2_disputed_kept() {
        let mut feat = make_osm_way(&[], vec![rel_with(Some(2), true, &[("type", "boundary")])]);
        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
        let result = process(&feat).unwrap();
        assert_eq!(result.sort_rank, 288);
    }

    #[test]
    fn osm_relations_disputed_by_property_added() {
        let feat = make_osm_way(
            &[("disputed_by", PropValue::Str("CountryX".into()))],
            vec![rel_with(Some(2), true, &[("type", "boundary")])],
        );
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "disputed_by" && *v == PropValue::Str("CountryX".into()))
        );
    }

    #[test]
    fn osm_relations_claimed_by_property_added() {
        let feat = make_osm_way(
            &[("claimed_by", PropValue::Str("CountryY".into()))],
            vec![rel_with(Some(2), true, &[("type", "boundary")])],
        );
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "claimed_by" && *v == PropValue::Str("CountryY".into()))
        );
    }

    // ─── process_india ─────────────────────────────────────────────────

    /// A 10° × 10° square of "India" (0..10, 0..10) as one closed ring,
    /// the shape `--india-boundary` uses.
    fn square_mask() -> IndiaMask {
        let ring = geo::LineString::from(vec![
            (0.0, 0.0),
            (10.0, 0.0),
            (10.0, 10.0),
            (0.0, 10.0),
            (0.0, 0.0),
        ]);
        let feat = InputFeature {
            geometry: Arc::new(geo::Geometry::MultiLineString(geo::MultiLineString::new(
                vec![ring],
            ))),
            ..make_india_feature(&[])
        };
        IndiaMask::from_features(&[feat]).unwrap()
    }

    fn country_line(coords: Vec<(f64, f64)>, disputed: bool) -> ProcessedFeature {
        let mut props = vec![("subtype", PropValue::Str("country".into()))];
        if disputed {
            props.push(("is_disputed", PropValue::Bool(true)));
        }
        let mut feat = make_feature(&props);
        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(coords)));
        process(&feat).unwrap()
    }

    fn total_length(feature: &ProcessedFeature) -> f64 {
        use geo::{Euclidean, Length};
        match feature.geometry.as_ref() {
            geo::Geometry::MultiLineString(m) => Euclidean.length(m),
            geo::Geometry::LineString(l) => Euclidean.length(l),
            other => panic!("unexpected geometry {other:?}"),
        }
    }

    /// A line from x=-5 to x=15 at y=5 crosses the square: only the parts
    /// outside the square plus the margin stay, 5 - margin on each side.
    #[test]
    fn india_mask_keeps_only_the_country_line_outside_india() {
        let line = country_line(vec![(-5.0, 5.0), (15.0, 5.0)], false);
        let clipped = square_mask().clip(line).unwrap();
        let expected = 2.0 * (5.0 - MASK_MARGIN_DEG);
        assert!((total_length(&clipped) - expected).abs() < 1e-6);
    }

    /// The Line of Control case: a country line (disputed or not) wholly
    /// inside India is dropped.
    #[test]
    fn india_mask_drops_country_lines_inside_india() {
        let mask = square_mask();
        for disputed in [false, true] {
            let line = country_line(vec![(2.0, 2.0), (8.0, 8.0)], disputed);
            assert!(mask.clip(line).is_none(), "disputed={disputed}");
        }
    }

    /// A source's own copy of India's border, 100 m off the Survey of India
    /// line, goes too.
    #[test]
    fn india_mask_drops_a_copy_of_the_border_inside_the_margin() {
        let line = country_line(vec![(-0.001, 2.0), (-0.001, 8.0)], false);
        assert!(square_mask().clip(line).is_none());
    }

    #[test]
    fn india_mask_leaves_regions_and_far_lines_alone() {
        let mask = square_mask();
        let mut region = make_feature(&[("subtype", PropValue::Str("region".into()))]);
        region.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
            (2.0, 2.0),
            (8.0, 8.0),
        ])));
        let region = process(&region).unwrap();
        let kept = mask.clip(region.clone()).unwrap();
        assert!(Arc::ptr_eq(&kept.geometry, &region.geometry));

        let far = country_line(vec![(40.0, 40.0), (50.0, 50.0)], false);
        let kept = mask.clip(far.clone()).unwrap();
        assert!(Arc::ptr_eq(&kept.geometry, &far.geometry));
    }

    #[test]
    fn india_mask_needs_a_closed_ring() {
        assert!(IndiaMask::from_features(&[make_india_feature(&[])]).is_none());
    }

    #[test]
    fn india_default_kind_and_detail() {
        let feat = make_india_feature(&[]);
        let result = process(&feat).unwrap();
        assert_eq!(result.layer, Layer::Boundaries);
        // From z0: the mask also removes Natural Earth lines at z0-z5.
        assert_eq!(result.min_zoom, 0);
        assert_eq!(result.max_zoom, 15);
        assert_eq!(result.sort_rank, 289);
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
        );
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(2))
        );
    }

    #[test]
    fn india_custom_kind_and_detail() {
        let feat = make_india_feature(&[
            ("kind", PropValue::Str("region".into())),
            ("kind_detail", PropValue::I64(4)),
        ]);
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
        );
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(4))
        );
    }

    #[test]
    fn india_with_name_property() {
        let feat = make_india_feature(&[("name", PropValue::Str("India".into()))]);
        let result = process(&feat).unwrap();
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "name" && *v == PropValue::Str("India".into()))
        );
    }

    // ─── admin_level_to_kind direct ────────────────────────────────────

    #[test]
    fn admin_level_to_kind_all_branches() {
        assert_eq!(admin_level_to_kind(2), Some(("country", 6)));
        assert_eq!(admin_level_to_kind(3), Some(("region", 6)));
        assert_eq!(admin_level_to_kind(4), Some(("region", 6)));
        assert_eq!(admin_level_to_kind(5), Some(("county", 8)));
        assert_eq!(admin_level_to_kind(6), Some(("county", 8)));
        assert_eq!(admin_level_to_kind(7), Some(("locality", 10)));
        assert_eq!(admin_level_to_kind(8), Some(("locality", 10)));
        assert_eq!(admin_level_to_kind(0), None);
        assert_eq!(admin_level_to_kind(1), None);
        assert_eq!(admin_level_to_kind(9), None);
        assert_eq!(admin_level_to_kind(100), None);
        assert_eq!(admin_level_to_kind(-1), None);
    }

    // ─── is_within_india_bbox ──────────────────────────────────────────

    #[test]
    fn india_bbox_centroid_inside() {
        let feat = InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: HashMap::new(),
            bbox: Some([77.0, 20.0, 79.0, 22.0]),
            source: DataSource::IndiaBoundary,
        };
        assert!(is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_centroid_outside() {
        let feat = InputFeature {
            id: 1,
            geometry: line_geom(),
            properties: HashMap::new(),
            bbox: Some([0.0, 0.0, 1.0, 1.0]),
            source: DataSource::IndiaBoundary,
        };
        assert!(!is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_fallback_linestring_inside() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
                (78.0, 20.0),
                (79.0, 22.0),
            ]))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        assert!(is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_fallback_linestring_outside() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
                (0.0, 0.0),
                (1.0, 1.0),
            ]))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        assert!(!is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_fallback_empty_linestring() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(Vec::<(
                f64,
                f64,
            )>::new(
            )))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        assert!(!is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_fallback_point_inside() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(78.0, 20.0))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        assert!(is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_fallback_point_outside() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        assert!(!is_within_india_bbox(&feat));
    }

    #[test]
    fn india_bbox_fallback_other_geom() {
        let feat = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
                geo::LineString::from(vec![(78.0, 20.0), (79.0, 20.0), (79.0, 21.0), (78.0, 20.0)]),
                vec![],
            ))),
            properties: HashMap::new(),
            bbox: None,
            source: DataSource::IndiaBoundary,
        };
        // Polygon falls into the `_ => {}` arm → false
        assert!(!is_within_india_bbox(&feat));
    }

    // ─── the Survey of India map for region and county lines, and labels ──

    /// An Overture boundary of `subtype` along `coords` with `extra` props.
    fn overture_line(
        subtype: &str,
        coords: Vec<(f64, f64)>,
        extra: &[(&str, PropValue)],
    ) -> ProcessedFeature {
        let mut props = vec![("subtype", PropValue::Str(subtype.into()))];
        props.extend(extra.iter().cloned());
        let mut feat = make_feature(&props);
        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(coords)));
        process(&feat).unwrap()
    }

    fn country(code: &str) -> (&'static str, PropValue) {
        ("country", PropValue::Str(code.into()))
    }

    fn has_key(feature: &ProcessedFeature, key: &str) -> bool {
        feature.properties.iter().any(|(k, _)| k == key)
    }

    /// A Pakistani region line across India's land goes; the same line
    /// 50 degrees away stays; neither leaks the private owner mark.
    #[test]
    fn a_foreign_region_line_inside_india_is_dropped() {
        let mask = square_mask();
        let inside = overture_line("region", vec![(2.0, 2.0), (8.0, 8.0)], &[country("PK")]);
        assert!(mask.clip(inside).is_none());
        let far = overture_line("region", vec![(40.0, 40.0), (50.0, 50.0)], &[country("PK")]);
        let kept = mask.clip(far).unwrap();
        assert!(!has_key(&kept, crate::layers::OWNER_KEY));
        assert!((total_length(&kept) - 10.0 * 2f64.sqrt()).abs() < 1e-9);
    }

    /// A line along the border stays: it is the neighbour's own border.
    #[test]
    fn a_foreign_line_along_the_border_stays() {
        let line = overture_line("region", vec![(10.0, 2.0), (10.0, 8.0)], &[country("PK")]);
        let kept = square_mask().clip(line).unwrap();
        assert!((total_length(&kept) - 6.0).abs() < 1e-6);
    }

    /// An Indian line that carries a claim is a claim line inside India.
    #[test]
    fn a_claim_carrying_line_inside_india_is_dropped() {
        let mask = square_mask();
        let claim = overture_line(
            "county",
            vec![(2.0, 2.0), (8.0, 8.0)],
            &[country("IN"), ("is_disputed", PropValue::Bool(true))],
        );
        assert!(mask.clip(claim).is_none());
        let plain = overture_line("county", vec![(2.0, 2.0), (8.0, 8.0)], &[country("IN")]);
        let kept = mask.clip(plain).unwrap();
        assert!(!has_key(&kept, "disputed"));
        assert!((total_length(&kept) - 6.0 * 2f64.sqrt()).abs() < 1e-9);
    }

    #[test]
    fn an_osm_line_of_an_admin_relation_of_another_country_is_foreign() {
        let mut tags = std::collections::HashMap::new();
        assert_eq!(relation_country(&tags), None);
        tags.insert("ISO3166-2".to_string(), "PK-GB".to_string());
        assert_eq!(relation_country(&tags).as_deref(), Some("PK"));
        tags.insert("ISO3166-1:alpha2".to_string(), "IN".to_string());
        assert_eq!(relation_country(&tags).as_deref(), Some("IN"));
    }

    fn label(subtype: &str, props: &[(&str, &str)], at: (f64, f64)) -> ProcessedFeature {
        let mut all: Vec<(&str, PropValue)> = vec![
            ("subtype", PropValue::Str(subtype.into())),
            ("names.primary", PropValue::Str("X".into())),
        ];
        all.extend(props.iter().map(|(k, v)| (*k, PropValue::Str((*v).into()))));
        let mut feat = make_feature(&all);
        feat.geometry = Arc::new(geo::Geometry::Point(geo::Point::new(at.0, at.1)));
        crate::layers::places::process(&feat).unwrap()
    }

    /// The labels of Overture's claim record, of a Pakistani division and
    /// of a Chinese prefecture are dropped on India's land; India's own
    /// state and county labels, and the same foreign labels outside it, stay.
    #[test]
    fn foreign_admin_labels_on_india_land_are_dropped() {
        let mask = square_mask();
        let at = (5.0, 5.0);
        let claim = label("region", &[("country", "IN")], at);
        let tibet = label("region", &[("country", "CN"), ("region", "CN-XZ")], at);
        let division = label("county", &[("country", "PK"), ("region", "PK-GB")], at);
        let pakistan = label("country", &[("country", "PK")], at);
        for (name, feature) in [
            ("claim region", claim),
            ("Chinese region", tibet),
            ("Pakistani division", division),
            ("Pakistan", pakistan),
        ] {
            assert!(mask.clip(feature).is_none(), "{name}");
        }
        let state = label("region", &[("country", "IN"), ("region", "IN-AR")], at);
        let county = label("county", &[("country", "IN"), ("region", "IN-AR")], at);
        let city = label("locality", &[("country", "PK")], at);
        for (name, feature) in [("state", state), ("county", county), ("city", city)] {
            let kept = mask.clip(feature).unwrap_or_else(|| panic!("{name} stays"));
            assert!(!has_key(&kept, crate::layers::OWNER_KEY), "{name}");
        }
        let outside = label(
            "region",
            &[("country", "PK"), ("region", "PK-GB")],
            (40.0, 40.0),
        );
        assert!(
            mask.clip(outside).is_some(),
            "outside India nothing changes"
        );
    }

    /// With no mask the private mark still never reaches a tile.
    #[test]
    fn the_owner_mark_is_stripped_without_a_mask() {
        let foreign = overture_line("region", vec![(2.0, 2.0), (8.0, 8.0)], &[country("PK")]);
        assert!(has_key(&foreign, crate::layers::OWNER_KEY));
        let (clean, was_foreign) = crate::layers::take_owner(foreign);
        assert!(was_foreign);
        assert!(!has_key(&clean, crate::layers::OWNER_KEY));
    }

    // ─── claim-marked lines inside India ───────────────────────────────

    /// A boundaries feature of `kind` along `coords`, with `extra` properties
    /// and the owner mark when `foreign`.
    fn admin_line(
        kind: &str,
        coords: Vec<(f64, f64)>,
        extra: &[(&str, PropValue)],
        foreign: bool,
    ) -> ProcessedFeature {
        let mut properties: Vec<(String, PropValue)> = vec![
            ("kind".into(), PropValue::Str(kind.into())),
            ("kind_detail".into(), PropValue::I64(4)),
        ];
        for (k, v) in extra {
            properties.push(((*k).into(), v.clone()));
        }
        if foreign {
            mark_foreign(&mut properties);
        }
        ProcessedFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(coords))),
            layer: Layer::Boundaries,
            min_zoom: 0,
            max_zoom: 15,
            sort_rank: 288,
            properties,
        }
    }

    /// A vertical line `x` degrees east of the west edge of the square mask.
    fn vertical(
        kind: &str,
        x: f64,
        extra: &[(&str, PropValue)],
        foreign: bool,
    ) -> ProcessedFeature {
        admin_line(kind, vec![(x, 2.0), (x, 8.0)], extra, foreign)
    }

    const CLAIM_MARKERS: [&str; 3] = ["disputed", "disputed_by", "claimed_by"];

    fn marker(name: &str) -> (&'static str, PropValue) {
        match name {
            "disputed" => ("disputed", PropValue::Bool(true)),
            "disputed_by" => ("disputed_by", PropValue::Str("PK".into())),
            _ => ("claimed_by", PropValue::Str("CN".into())),
        }
    }

    /// The owner's rule: no claim line inside India, whatever the kind and
    /// whatever the marker. A claim-marked line 0.01 deg inside the edge (the
    /// band the other rules keep) used to survive as a second border next to
    /// the Survey of India line.
    #[test]
    fn a_claim_marked_line_in_the_band_inside_india_is_dropped_for_every_kind_and_marker() {
        let mask = square_mask();
        for kind in ["country", "region", "county", "locality"] {
            for name in CLAIM_MARKERS {
                for foreign in [false, true] {
                    let (key, value) = marker(name);
                    let line = vertical(kind, 0.01, &[(key, value)], foreign);
                    assert!(
                        mask.clip(line).is_none(),
                        "{kind} with {name} (foreign={foreign}) at 0.01 deg inside survives"
                    );
                }
            }
        }
    }

    /// A claim-marked line that weaves along the edge from the outside must not
    /// leave dashes hugging the border: the outward band is 0.02 deg too.
    #[test]
    fn a_claim_marked_line_within_the_margin_outside_india_is_dropped_too() {
        let mask = square_mask();
        for kind in ["country", "region", "county", "locality"] {
            for x in [-0.001, -0.015, -0.019] {
                let line = vertical(kind, x, &[marker("disputed_by")], true);
                assert!(mask.clip(line).is_none(), "{kind} at {x}");
            }
            let line = vertical(kind, -0.03, &[marker("disputed_by")], true);
            let kept = mask
                .clip(line)
                .expect("a claim line 0.03 deg outside stays");
            assert!((total_length(&kept) - 6.0).abs() < 1e-9, "{kind}");
        }
    }

    /// Deep inside India the same rule holds, and a claim line that crosses the
    /// edge keeps only its part outside the outward band.
    #[test]
    fn a_claim_marked_line_crossing_the_edge_keeps_only_the_part_beyond_the_outward_band() {
        let mask = square_mask();
        let line = admin_line(
            "region",
            vec![(-5.0, 5.0), (15.0, 5.0)],
            &[marker("claimed_by")],
            true,
        );
        let kept = mask.clip(line).expect("the outside parts stay");
        let expected = 2.0 * (5.0 - CLAIM_MARGIN_DEG);
        assert!(
            (total_length(&kept) - expected).abs() < 1e-6,
            "{}",
            total_length(&kept)
        );
    }

    /// Unclaimed lines keep today's behaviour: an unmarked line stays whole, a
    /// foreign unclaimed line keeps its part in the 0.02 band (avoids confetti
    /// along a border both sources agree on) and loses what is deeper.
    #[test]
    fn unclaimed_lines_keep_the_band_rule() {
        let mask = square_mask();
        let unmarked = vertical("region", 0.01, &[], false);
        let kept = mask.clip(unmarked.clone()).expect("unmarked stays");
        assert!(Arc::ptr_eq(&kept.geometry, &unmarked.geometry));

        let foreign_band = vertical("region", 0.01, &[], true);
        let kept = mask
            .clip(foreign_band)
            .expect("a foreign line in the band stays");
        assert!((total_length(&kept) - 6.0).abs() < 1e-9);

        let foreign_deep = vertical("region", 0.03, &[], true);
        assert!(
            mask.clip(foreign_deep).is_none(),
            "a foreign line deeper than the band goes"
        );
    }

    /// The lines between Indian divisions carry no claim marker, from either
    /// source, so the claim rule never touches them.
    #[test]
    fn a_line_between_indian_divisions_carries_no_claim_marker_and_stays_whole() {
        let mask = square_mask();
        let inside = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
            (2.0, 2.0),
            (8.0, 8.0),
        ])));

        let mut overture = make_feature(&[
            ("subtype", PropValue::Str("region".into())),
            ("country", PropValue::Str("IN".into())),
        ]);
        overture.geometry = inside.clone();
        let overture = process(&overture).expect("an Indian region line");
        assert!(!carries_claim(&overture), "{:?}", overture.properties);
        let kept = mask.clip(overture.clone()).expect("stays");
        assert!(Arc::ptr_eq(&kept.geometry, &overture.geometry));

        let mut way = make_osm_way(
            &[],
            vec![
                rel_with(
                    Some(4),
                    false,
                    &[("type", "boundary"), ("ISO3166-2", "IN-MH")],
                ),
                rel_with(
                    Some(4),
                    false,
                    &[("type", "boundary"), ("ISO3166-2", "IN-GJ")],
                ),
            ],
        );
        way.geometry = inside;
        let way = process(&way).expect("a line between two Indian states");
        assert!(!carries_claim(&way), "{:?}", way.properties);
        let (unmarked, foreign) = take_owner(way.clone());
        assert!(!foreign, "a line of two Indian relations is not foreign");
        let kept = mask.clip(way).expect("stays");
        assert!(Arc::ptr_eq(&kept.geometry, &unmarked.geometry) || total_length(&kept) > 8.0);
    }

    /// An OSM way without a relation used to lose `disputed_by` and
    /// `claimed_by` (only the relation branch copied them), so the claim rule
    /// could not see it.
    #[test]
    fn a_way_without_a_relation_keeps_its_claim_tags() {
        let way = make_osm_way(
            &[
                ("boundary", PropValue::Str("administrative".into())),
                ("admin_level", PropValue::Str("4".into())),
                ("disputed_by", PropValue::Str("PK".into())),
                ("claimed_by", PropValue::Str("CN".into())),
            ],
            vec![],
        );
        let result = process(&way).expect("a region line");
        assert!(carries_claim(&result));
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "disputed_by" && *v == PropValue::Str("PK".into()))
        );
        assert!(
            result
                .properties
                .iter()
                .any(|(k, v)| k == "claimed_by" && *v == PropValue::Str("CN".into()))
        );
    }
}