geolith-dataset-builder 0.4.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
//! District areas cut from Overture divisions (`geolith dataset areas`).
//!
//! Reads `divisions/division_area` for the listed countries and subtype and
//! writes one area per Overture `division_id`. India is always cut with the
//! Survey of India (SOI) outline: Indian areas are intersected with it,
//! Pakistan's, China's and Overture's disputed (`X*`) areas lose the land
//! inside it, and regions go through [`IndiaView`] so Ladakh and Jammu and
//! Kashmir carry the Kashmir land. When India is in scope, every piece of the
//! SOI outline that no Indian area covers is split by Indian region, and each
//! part (at least [`GAP_MIN_PIECE_SQ_DEG`]) is listed as a gap; smaller parts
//! join a neighbouring part, so the gaps of a piece cover all of it.

use std::collections::{BTreeMap, BTreeSet, HashMap, hash_map};
use std::fs::File;
use std::io::{BufWriter, Write as _};
use std::path::Path;

use crate::error::{DatasetError, IoOp, IoResultExt as _, Result, WithinExt as _};
use geo::orient::{Direction, Orient as _};
use geo::{
    Area as _, BooleanOps, BoundingRect, Centroid, Coord, Intersects as _, LineString,
    MultiPolygon, Point, Polygon,
};
use serde_json::{Value, json};

use super::country::{BoundarySource, CountryConfig};
use super::exact_json::parse_feature_collection;
use crate::cli::AreasArgs;
use geolith::admin::india::{IndiaOutline, IndiaView};
use geolith::admin::{AdminDivision, AdminLevel, division_from_feature};
use geolith::source::bbox_filter::Bbox;
use geolith::source::overture_files;
use geolith::source::reader::{SOURCE_ID_PROP, read_parquet_file_with_source_id};
use geolith::source::schema::OvertureType;

/// Attribution of the area boundaries, carried by every file `areas` writes.
pub const BOUNDARIES_ATTRIBUTION: &str = "Boundaries: Overture Maps Foundation, \
     © OpenStreetMap contributors, ODbL. India boundaries by DataMeet India community (CC BY 4.0)";

/// Smallest SOI gap piece listed, in planar square degrees (the `MIN_PIECE`
/// of `geocoding::india`).
pub const GAP_MIN_PIECE_SQ_DEG: f64 = 0.005;

/// Label of a gap piece on the map.
pub const GAP_LABEL: &str = "District data not available";

/// One area (district or region), cut to India's SOI view.
///
/// No `Serialize`: `geo` is built without its serde feature; the area is
/// written and read as `GeoJSON` by [`write_areas_geojson`] and
/// [`read_areas_geojson`].
#[derive(Debug, Clone, PartialEq)]
pub struct Area {
    /// Overture `division_id`, or the id minted from an official code.
    pub id: String,
    /// The publisher's own code (`GEOID`), when the boundaries come from an
    /// official file.
    pub code: Option<String>,
    /// Primary name.
    pub name: String,
    /// ISO 3166-1 alpha-2 country code.
    pub country: String,
    /// Overture subtype of the area (`county`, `region`).
    pub level: String,
    /// `division_id` of the region holding the area.
    pub parent_id: Option<String>,
    /// Name of the region holding the area.
    pub parent_name: Option<String>,
    /// ISO 3166-2 code of the region (Overture's `region`).
    pub region_code: Option<String>,
    /// Land of the area, lon/lat.
    pub shape: MultiPolygon<f64>,
}

/// One piece of the SOI outline no Indian area covers.
#[derive(Debug, Clone, PartialEq)]
pub struct GapPiece {
    /// `gap-<n>`, numbered from 1 in centroid order.
    pub id: String,
    /// Planar area in square degrees.
    pub area_sq_deg: f64,
    /// Centroid `(lon, lat)`.
    pub centroid: (f64, f64),
    /// `division_id` of the Indian region holding the piece; `None` when no
    /// Indian region covers it.
    pub region_id: Option<String>,
    /// Name of that region.
    pub region_name: Option<String>,
    /// ISO 3166-2 code of that region.
    pub region_code: Option<String>,
    /// The piece, lon/lat: one polygon, unless a small part bordering no
    /// other part joined it.
    pub shape: MultiPolygon<f64>,
}

/// The content of `areas.geojson`.
#[derive(Debug, Clone, PartialEq)]
pub struct AreasFile {
    /// Areas sorted by id.
    pub areas: Vec<Area>,
    /// Overture release the areas come from.
    pub boundary_release: String,
    /// Attribution of the boundaries.
    pub attribution: String,
}

/// Pieces of `outline` that no district covers, each at least
/// [`GAP_MIN_PIECE_SQ_DEG`], sorted by centroid `(lon, lat)`.
#[must_use]
pub fn soi_gaps(
    outline: &MultiPolygon<f64>,
    districts: &[&MultiPolygon<f64>],
) -> Vec<Polygon<f64>> {
    let districts: Vec<MultiPolygon<f64>> = districts.iter().map(|d| oriented(d)).collect();
    let covered = geo::unary_union(&districts);
    let mut pieces: Vec<Polygon<f64>> = oriented(outline)
        .difference(&covered)
        .0
        .into_iter()
        .filter(|p| p.unsigned_area() >= GAP_MIN_PIECE_SQ_DEG)
        .collect();
    pieces.sort_by(|a, b| {
        let (a, b) = (centroid_of(a), centroid_of(b));
        a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
    });
    pieces
}

/// `shape` with counter-clockwise exteriors and clockwise holes: the
/// boolean operations fill by winding number, so a hole wound like its
/// exterior would count as land.
fn oriented(shape: &MultiPolygon<f64>) -> MultiPolygon<f64> {
    shape.orient(Direction::Default)
}

fn centroid_of<T: Centroid<Output = Option<Point<f64>>>>(shape: &T) -> (f64, f64) {
    shape.centroid().map_or((0.0, 0.0), |c| (c.x(), c.y()))
}

/// Read `areas.geojson` as written by [`write_areas_geojson`].
///
/// # Errors
///
/// Fails if the file cannot be read or parsed, a feature lacks `id`, `name`,
/// `country` or `level`, or a geometry is not a polygon.
pub fn read_areas_geojson(path: &Path) -> Result<AreasFile> {
    let bytes = std::fs::read(path).io_at(IoOp::Open, path)?;
    let collection =
        parse_feature_collection(&bytes).within(format!("failed to parse {}", path.display()))?;
    let member = |key: &str| {
        collection
            .foreign_members
            .as_ref()
            .and_then(|m| m.get(key))
            .and_then(Value::as_str)
            .map(str::to_string)
            .ok_or_else(|| DatasetError::data(format!("{} has no {key}", path.display())))
    };
    let boundary_release = member("boundary_release")?;
    let attribution = member("attribution")?;
    let mut areas = Vec::with_capacity(collection.features.len());
    for feature in &collection.features {
        let props = feature.properties.clone().unwrap_or_default();
        let text = |key: &str| props.get(key).and_then(Value::as_str).map(str::to_string);
        let required = |key: &str| {
            text(key).ok_or_else(|| {
                DatasetError::data(format!("a feature of {} has no {key}", path.display()))
            })
        };
        let id = required("id")?;
        let geometry = feature.geometry.clone().ok_or_else(|| {
            DatasetError::data(format!("area {id} in {} has no geometry", path.display()))
        })?;
        let shape = match geo::Geometry::<f64>::try_from(geometry).map_err(|source| {
            DatasetError::Geometry {
                what: format!("bad geometry of area {id} in {}", path.display()),
                source: Box::new(source),
            }
        })? {
            geo::Geometry::Polygon(p) => MultiPolygon(vec![p]),
            geo::Geometry::MultiPolygon(m) => m,
            _ => {
                return Err(DatasetError::data(format!(
                    "area {id} in {} is not a polygon",
                    path.display()
                )));
            }
        };
        areas.push(Area {
            name: required("name")?,
            country: required("country")?,
            level: required("level")?,
            parent_id: text("parent_id"),
            parent_name: text("parent_name"),
            region_code: text("region_code"),
            shape,
            id,
            code: text("code"),
        });
    }
    areas.sort_by(|a, b| a.id.cmp(&b.id));
    Ok(AreasFile {
        areas,
        boundary_release,
        attribution,
    })
}

/// Write `file` as a `GeoJSON` feature collection: properties `id`, `name`,
/// `country`, `level`, `parent_id`, `parent_name`, `region_code`; foreign
/// members `boundary_release` and `attribution`.
///
/// # Errors
///
/// Fails if the file cannot be written.
pub fn write_areas_geojson(path: &Path, file: &AreasFile) -> Result<()> {
    let features = file.areas.iter().map(|area| {
        let mut props = json!({
            "id": area.id,
            "name": area.name,
            "country": area.country,
            "level": area.level,
            "parent_id": area.parent_id,
            "parent_name": area.parent_name,
            "region_code": area.region_code,
        });
        // Only an official-source area carries a code: India's bytes must not
        // change.
        if let (Some(code), Value::Object(map)) = (&area.code, &mut props) {
            map.insert("code".into(), json!(code));
        }
        feature(geojson::GeometryValue::from(&area.shape), props)
    });
    write_collection(path, features, &file.boundary_release, &file.attribution)
}

pub(super) fn feature(geometry: geojson::GeometryValue, properties: Value) -> geojson::Feature {
    geojson::Feature {
        bbox: None,
        geometry: Some(geojson::Geometry::new(geometry)),
        id: None,
        properties: match properties {
            Value::Object(map) => Some(map),
            _ => None,
        },
        foreign_members: None,
    }
}

pub(super) fn write_collection(
    path: &Path,
    features: impl Iterator<Item = geojson::Feature>,
    boundary_release: &str,
    attribution: &str,
) -> Result<()> {
    let mut members = geojson::JsonObject::new();
    members.insert("boundary_release".into(), boundary_release.into());
    members.insert("attribution".into(), attribution.into());
    let collection = geojson::FeatureCollection {
        bbox: None,
        features: features.collect(),
        foreign_members: Some(members),
    };
    write_json(path, &collection)
}

pub(super) fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<()> {
    let file = File::create(path).io_at(IoOp::Create, path)?;
    let mut out = BufWriter::new(file);
    serde_json::to_writer(&mut out, value).io_at(IoOp::Write, path)?;
    out.flush().io_at(IoOp::Write, path)
}

/// A land division row of a listed country, with its `division_id`.
struct Row {
    division_id: String,
    division: AdminDivision,
}

/// Run `geolith dataset areas`.
///
/// # Errors
///
/// Fails when the countries hold land of India's SOI map (`IN`, `PK`, `CN`
/// or an `X*` code) without `--india-outline`, the
/// subtype is not a county or region subtype, a file cannot be read, a land
/// row has no `division_id`, or an output cannot be written.
pub fn run(args: &AreasArgs) -> Result<()> {
    let config = args
        .country_config
        .as_deref()
        .map(CountryConfig::load)
        .transpose()?;
    if let Some(config) = &config
        && config.boundaries.source == BoundarySource::Shapefile
    {
        let dir = args.boundaries_dir.as_deref().ok_or_else(|| {
            DatasetError::data(
                "the country config has a shapefile source: pass --boundaries-dir <dir>",
            )
        })?;
        return super::official_areas::run(config, dir, &args.out, args.max_zoom);
    }
    run_overture(args, config.as_ref())
}

/// The Overture path: the engine as India has always used it.
///
/// # Errors
///
/// As [`run`], plus `--overture` missing.
fn run_overture(args: &AreasArgs, config: Option<&CountryConfig>) -> Result<()> {
    let overture = args.overture.as_deref().ok_or_else(|| {
        DatasetError::data({
            "dataset areas reads Overture: pass --overture <release dir>, or a --country-config \
         whose boundaries.source is shapefile"
        })
    })?;
    let listed = args
        .countries
        .clone()
        .or_else(|| config.map(|c| c.code.to_uppercase()))
        .unwrap_or_default();
    let countries: BTreeSet<String> = listed
        .split(',')
        .map(|c| c.trim().to_uppercase())
        .filter(|c| !c.is_empty())
        .collect();
    if countries.is_empty() {
        return Err(DatasetError::usage("--countries lists no country"));
    }
    let india = countries.contains("IN");
    let needs_outline = match config {
        Some(config) => config.boundaries.holds_soi_land,
        None => india || countries.iter().any(|c| holds_soi_land(c)),
    };
    let allowed: Vec<String> = args
        .allow_districtless
        .as_deref()
        .unwrap_or_default()
        .split(',')
        .map(|c| c.trim().to_uppercase())
        .filter(|c| !c.is_empty())
        .collect();
    if args.india_outline.is_none() && needs_outline {
        if india {
            return Err(DatasetError::data(
                "dataset areas covers India: pass --india-outline <Survey of India GeoJSON>",
            ));
        }
        if let Some(code) = countries.iter().find(|c| holds_soi_land(c)) {
            return Err(DatasetError::data(format!(
                "dataset areas covers {code}, which holds land of India's Survey of India map: \
                 pass --india-outline <Survey of India GeoJSON>"
            )));
        }
        return Err(DatasetError::data(
            "the country config holds Survey of India land: pass --india-outline",
        ));
    }
    let level = match AdminLevel::from_overture_subtype(&args.subtype) {
        Some(level @ (AdminLevel::County | AdminLevel::Region)) => level,
        _ => {
            return Err(DatasetError::usage(format!(
                "--subtype {}: areas must be an Overture county or region subtype",
                args.subtype
            )));
        }
    };
    let outline = args
        .india_outline
        .as_deref()
        .map(IndiaOutline::load)
        .transpose()?;
    // Only an India-only build is limited to the outline (plus 1°): other
    // listed countries reach far beyond it.
    let india_only = countries.len() == 1 && needs_outline;
    let bbox = match (&outline, india_only) {
        (Some(o), true) => o.polygons().bounding_rect().map(|r| Bbox {
            min_lon: r.min().x - 1.0,
            min_lat: r.min().y - 1.0,
            max_lon: r.max().x + 1.0,
            max_lat: r.max().y + 1.0,
        }),
        _ => None,
    };
    let boundary_release = match &args.release {
        Some(release) => release.clone(),
        None => overture
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .ok_or_else(|| {
                DatasetError::data(format!(
                    "{} has no file name: pass --release",
                    overture.display()
                ))
            })?,
    };

    let Rows {
        regions: raw_regions,
        units,
        view_only,
    } = read_rows(
        overture,
        bbox.as_ref(),
        &countries,
        level,
        outline.is_some(),
    )?;
    let raw_regions: Vec<Row> = raw_regions
        .into_iter()
        .filter(|r| !is_uncoded_indian_region(&r.division))
        .collect();
    let regions = india_view_regions(raw_regions, view_only, outline.as_ref());
    let region_groups = union_by_id(&regions, None);
    let parents = region_parents(&region_groups);
    let unit_rows = if level == AdminLevel::Region {
        &regions
    } else {
        &units
    };
    let soi = outline.as_ref().map(|o| oriented(o.polygons()));
    let mut areas: Vec<Area> = Vec::new();
    let mut by_overlap: Vec<Value> = Vec::new();
    for (id, g) in union_by_id(unit_rows, soi.as_ref()) {
        let parent = if level == AdminLevel::Region {
            None
        } else {
            resolve_parent(&g, &parents)?
        };
        if let Some(p) = parent
            && p.region_code != g.region_code
        {
            let area = g.shape.unsigned_area();
            let share = if area > 0.0 {
                g.shape.intersection(&p.shape).unsigned_area() / area
            } else {
                0.0
            };
            tracing::info!(
                district = id.as_str(),
                name = g.name.as_str(),
                region_code = p.region_code.as_deref().unwrap_or_default(),
                share,
                "district without a coded region placed in the region it overlaps most"
            );
            by_overlap.push(json!({
                "id": id,
                "name": g.name,
                "region_code": p.region_code,
                "overlap_share": share,
            }));
        }
        let region_code = match parent {
            Some(p) if level != AdminLevel::Region => p.region_code.clone(),
            _ => g.region_code,
        };
        areas.push(Area {
            id,
            code: None,
            parent_id: parent.map(|p| p.id.clone()),
            parent_name: parent.map(|p| p.name.clone()),
            level: args.subtype.clone(),
            name: g.name,
            country: g.country,
            region_code,
            shape: g.shape,
        });
    }
    if areas.is_empty() {
        return Err(DatasetError::data(format!(
            "dataset areas read no {} row of {} from {}: is that the release directory?",
            args.subtype,
            countries.iter().cloned().collect::<Vec<_>>().join(","),
            overture.display()
        )));
    }
    let india_regions = if india && level != AdminLevel::Region {
        check_india_regions(&areas, &parents, &allowed)?
    } else {
        BTreeMap::new()
    };

    let gaps = match (&outline, india) {
        (Some(o), true) => gap_pieces(o, &areas, &region_groups),
        _ => Vec::new(),
    };

    std::fs::create_dir_all(&args.out).io_at(IoOp::Create, &args.out)?;
    let attribution = config.map_or_else(
        || BOUNDARIES_ATTRIBUTION.to_string(),
        |c| c.boundaries.attribution.clone(),
    );
    let file = AreasFile {
        areas,
        boundary_release,
        attribution,
    };
    write_areas_geojson(&args.out.join("areas.geojson"), &file)?;
    let gap_features = gaps.iter().map(|g| {
        // A one-polygon gap stays a GeoJSON Polygon, as P0 wrote it.
        let geometry = match g.shape.0.as_slice() {
            [polygon] => geojson::GeometryValue::from(polygon),
            _ => geojson::GeometryValue::from(&g.shape),
        };
        feature(
            geometry,
            json!({
                "id": g.id,
                "area_sq_deg": g.area_sq_deg,
                "region_id": g.region_id,
                "region_name": g.region_name,
                "region_code": g.region_code,
                "label": GAP_LABEL,
                "attribution": file.attribution,
            }),
        )
    });
    write_collection(
        &args.out.join("gaps.geojson"),
        gap_features,
        &file.boundary_release,
        &file.attribution,
    )?;
    let mut report = json!({
        "areas": file.areas.len(),
        "gaps": gaps
            .iter()
            .map(|g| json!({
                "id": g.id,
                "area_sq_deg": g.area_sq_deg,
                "centroid": [g.centroid.0, g.centroid.1],
                "region_name": g.region_name,
            }))
            .collect::<Vec<_>>(),
        "countries": countries,
        "india_regions": india_regions,
        "india_districtless_allowed": allowed,
        "india_assigned_by_overlap": by_overlap,
        "subtype": args.subtype,
        "boundary_release": file.boundary_release,
        "attribution": file.attribution,
    });
    if let (Some(config), Some(map)) = (config, report.as_object_mut()) {
        map.insert(
            "invariants".to_owned(),
            serde_json::to_value(&config.boundaries.invariants)?,
        );
    }
    write_json(&args.out.join("areas-report.json"), &report)?;
    crate::areas_tiles::write_areas_pmtiles(
        &args.out.join("areas.pmtiles"),
        &file.areas,
        &gaps,
        args.max_zoom,
        &file.attribution,
        None,
    )?;
    tracing::info!(
        areas = file.areas.len(),
        gaps = gaps.len(),
        out = %args.out.display(),
        "dataset areas written"
    );
    Ok(())
}

/// The rows `run` reads.
struct Rows {
    /// Regions of the listed countries.
    regions: Vec<Row>,
    /// Areas of the requested level of the listed countries (empty when
    /// that level is the region level).
    units: Vec<Row>,
    /// Divisions [`IndiaView`] needs that are not in `regions`: the India
    /// country (the Kashmir land is the SOI outline minus it) and Pakistan's
    /// "Azad Kashmir" region (`PK-JK`, which splits that land between Jammu
    /// and Kashmir and Ladakh). Never emitted.
    view_only: Vec<AdminDivision>,
}

/// Whether [`IndiaView`] needs `division` although it is not read as a
/// region of a listed country.
fn needed_by_india_view(division: &AdminDivision) -> bool {
    match division.level {
        AdminLevel::Country => division.country_code.as_deref() == Some("IN"),
        AdminLevel::Region => division.region_code.as_deref() == Some("PK-JK"),
        _ => false,
    }
}

/// Land rows of the listed countries, plus with `india_view` the divisions
/// only [`IndiaView`] needs.
fn read_rows(
    overture: &Path,
    bbox: Option<&Bbox>,
    countries: &BTreeSet<String>,
    level: AdminLevel,
    india_view: bool,
) -> Result<Rows> {
    let otype = OvertureType::new("divisions", "division_area");
    let files =
        overture_files(overture, otype).within(format!("failed to list {}", overture.display()))?;
    let mut rows = Rows {
        regions: Vec::new(),
        units: Vec::new(),
        view_only: Vec::new(),
    };
    for path in &files {
        let mut failed: Option<DatasetError> = None;
        read_parquet_file_with_source_id(path, otype, bbox, |feature| {
            if failed.is_some() {
                return;
            }
            let Some(division) = division_from_feature(&feature) else {
                return;
            };
            let listed = division
                .country_code
                .as_deref()
                .is_some_and(|c| countries.contains(c));
            let is_region = division.level == AdminLevel::Region;
            if !listed || !(is_region || division.level == level) {
                if india_view && needed_by_india_view(&division) {
                    rows.view_only.push(division);
                }
                return;
            }
            let Some(division_id) = feature.get_str("division_id").filter(|s| !s.is_empty()) else {
                failed = Some(DatasetError::data(format!(
                    "land row {} of {} has no division_id",
                    feature.get_str(SOURCE_ID_PROP).unwrap_or("(no id)"),
                    path.display()
                )));
                return;
            };
            let row = Row {
                division_id: division_id.to_string(),
                division,
            };
            if is_region {
                rows.regions.push(row);
            } else {
                rows.units.push(row);
            }
        })
        .io_at(IoOp::Read, path)?;
        if let Some(e) = failed {
            return Err(e);
        }
    }
    Ok(rows)
}

/// An Indian `region` without a region code. The states and union
/// territories all carry one; Overture 2026-10-21.0 also tags a claim polygon
/// over Arunachal Pradesh (named 藏南, region NULL) as IN. Such a row must
/// never become an area, a parent or a gap label.
fn is_uncoded_indian_region(division: &AdminDivision) -> bool {
    division.level == AdminLevel::Region
        && division
            .country_code
            .as_deref()
            .is_some_and(|c| c.eq_ignore_ascii_case("IN"))
        && division.region_code.as_deref().is_none_or(str::is_empty)
}

/// Regions in India's SOI view (see [`IndiaView`]); unchanged without an
/// outline. `view_only` divisions go through the view but are not returned.
fn india_view_regions(
    rows: Vec<Row>,
    view_only: Vec<AdminDivision>,
    outline: Option<&IndiaOutline>,
) -> Vec<Row> {
    let Some(outline) = outline else {
        return rows;
    };
    // Only the regions read are returned: the view-only divisions (and the
    // India country `finish` gives back) have no id here.
    let ids: HashMap<u64, String> = rows
        .iter()
        .map(|r| (r.division.id, r.division_id.clone()))
        .collect();
    let mut view = IndiaView::new(outline);
    let mut admitted: Vec<AdminDivision> = rows
        .into_iter()
        .map(|r| r.division)
        .chain(view_only)
        .filter_map(|d| view.admit(d))
        .collect();
    admitted.extend(view.finish());
    admitted
        .into_iter()
        .filter(|d| d.level == AdminLevel::Region)
        .filter_map(|division| {
            Some(Row {
                division_id: ids.get(&division.id)?.clone(),
                division,
            })
        })
        .collect()
}

/// The region of each `(country, region code)`. When two regions share a
/// code, the larger keeps it (the first by id on a tie) and a warning names
/// both.
fn region_parents(groups: &BTreeMap<String, Group>) -> HashMap<(&str, &str), &Group> {
    let mut parents: HashMap<(&str, &str), &Group> = HashMap::with_capacity(groups.len());
    for group in groups.values() {
        let Some(code) = group.region_code.as_deref() else {
            continue;
        };
        match parents.entry((group.country.as_str(), code)) {
            hash_map::Entry::Vacant(slot) => {
                slot.insert(group);
            }
            hash_map::Entry::Occupied(mut slot) => {
                let held = *slot.get();
                let (kept, dropped) = if group.shape.unsigned_area() > held.shape.unsigned_area() {
                    (group, held)
                } else {
                    (held, group)
                };
                tracing::warn!(
                    region_code = code,
                    kept = kept.id.as_str(),
                    dropped = dropped.id.as_str(),
                    "two regions share a region code; the larger keeps it"
                );
                slot.insert(kept);
            }
        }
    }
    parents
}

/// The region of district `g`: the coded region of its `region_code`; for an
/// Indian district without one (Overture parents some to an uncoded claim
/// region, which is never used) or with a code no coded region holds, the
/// coded Indian region that overlaps it most (ties: the lower code). Other
/// countries keep the code rule only.
///
/// # Errors
///
/// Fails, naming the district, when an Indian district overlaps no coded
/// Indian region.
fn resolve_parent<'a>(
    g: &Group,
    parents: &HashMap<(&str, &str), &'a Group>,
) -> Result<Option<&'a Group>> {
    if let Some(parent) = g
        .region_code
        .as_deref()
        .and_then(|code| parents.get(&(g.country.as_str(), code)))
    {
        return Ok(Some(*parent));
    }
    if g.country != "IN" {
        return Ok(None);
    }
    let rect = g.shape.bounding_rect();
    let mut best: Option<(f64, &str, &'a Group)> = None;
    for (&(country, code), &region) in parents {
        if country != "IN" {
            continue;
        }
        let meets = match (rect, region.shape.bounding_rect()) {
            (Some(a), Some(b)) => a.intersects(&b),
            _ => false,
        };
        if !meets {
            continue;
        }
        let overlap = g.shape.intersection(&region.shape).unsigned_area();
        if overlap <= 0.0 {
            continue;
        }
        let better =
            best.is_none_or(|(area, held, _)| overlap > area || (overlap == area && code < held));
        if better {
            best = Some((overlap, code, region));
        }
    }
    match best {
        Some((_, _, region)) => Ok(Some(region)),
        None => Err(DatasetError::data(format!(
            "Indian district {} ({}) has no coded region and overlaps no coded Indian region",
            g.id, g.name
        ))),
    }
}

/// Districts per coded Indian region, after checking that every Indian
/// district has a state (region code and parent name) and every coded Indian
/// region holds a district (or is in `allowed`, the `--allow-districtless`
/// list; empty in the operator script, since every coded state and union
/// territory of Overture 2026-10-21.0 holds a county).
///
/// # Errors
///
/// Fails naming the districts without a state, or the coded regions without
/// a district.
fn check_india_regions(
    areas: &[Area],
    parents: &HashMap<(&str, &str), &Group>,
    allowed: &[String],
) -> Result<BTreeMap<String, usize>> {
    let indian: Vec<&Area> = areas.iter().filter(|a| a.country == "IN").collect();
    let stateless: Vec<String> = indian
        .iter()
        .filter(|a| a.region_code.is_none() || a.parent_name.is_none())
        .map(|a| format!("{} ({})", a.id, a.name))
        .collect();
    if !stateless.is_empty() {
        return Err(DatasetError::data(format!(
            "{} Indian districts have no state: {}",
            stateless.len(),
            stateless.join(", ")
        )));
    }
    let mut counts: BTreeMap<String, usize> = parents
        .keys()
        .filter(|(country, _)| *country == "IN")
        .map(|(_, code)| ((*code).to_string(), 0))
        .collect();
    for area in &indian {
        if let Some(count) = area.region_code.as_ref().and_then(|c| counts.get_mut(c)) {
            *count += 1;
        }
    }
    let empty: Vec<&str> = counts
        .iter()
        .filter(|(code, n)| **n == 0 && !allowed.contains(code))
        .map(|(code, _)| code.as_str())
        .collect();
    if !indian.is_empty() && !empty.is_empty() {
        return Err(DatasetError::data(format!(
            "coded Indian regions without a district: {}",
            empty.join(", ")
        )));
    }
    Ok(counts)
}

/// The rows of one `division_id`, unioned.
struct Group {
    id: String,
    name: String,
    country: String,
    region_code: Option<String>,
    shape: MultiPolygon<f64>,
}

/// Union the rows of each `division_id`, keyed and so sorted by id. With the
/// (oriented) SOI outline, each row is first cut to India's SOI view; groups left without
/// land are dropped.
fn union_by_id(rows: &[Row], soi: Option<&MultiPolygon<f64>>) -> BTreeMap<String, Group> {
    let mut groups: BTreeMap<String, Group> = BTreeMap::new();
    for row in rows {
        let country = row.division.country_code.clone().unwrap_or_default();
        let mut shape = to_multi(&row.division.parts);
        if let Some(soi) = soi {
            shape = soi_recut(&country, shape, soi);
        }
        match groups.get_mut(&row.division_id) {
            Some(group) => group.shape = group.shape.union(&shape),
            None => {
                groups.insert(
                    row.division_id.clone(),
                    Group {
                        id: row.division_id.clone(),
                        name: row.division.name.clone(),
                        country,
                        region_code: row.division.region_code.clone(),
                        shape,
                    },
                );
            }
        }
    }
    groups.retain(|_, g| !g.shape.0.is_empty());
    groups
}

/// Whether areas of `country` hold land of India's SOI map that must be cut
/// out: Pakistan, China and Overture's disputed (`X*`) codes.
fn holds_soi_land(country: &str) -> bool {
    country == "PK" || country == "CN" || country.starts_with('X')
}

/// An area in India's SOI view: Indian land is cut to the outline;
/// Pakistan, China and disputed (`X*`) areas lose the land inside it.
fn soi_recut(
    country: &str,
    shape: MultiPolygon<f64>,
    soi: &MultiPolygon<f64>,
) -> MultiPolygon<f64> {
    if country == "IN" {
        shape.intersection(soi)
    } else if holds_soi_land(country) {
        shape.difference(soi)
    } else {
        shape
    }
}

/// The SOI gap pieces of the Indian areas, labelled with the Indian regions
/// (in India's view, so Jammu and Kashmir and Ladakh hold the Kashmir land).
///
/// A piece with parts of at least [`GAP_MIN_PIECE_SQ_DEG`] in two or more
/// regions is split: each such part becomes a gap labelled with its region,
/// and each such part of the rest no region covers a gap without a region.
/// Smaller parts join a kept part (see [`merge_slivers`]), so the gaps of a
/// piece cover all of it. Any other piece stays whole with the region it
/// overlaps most, so a piece just outside the region outlines (a coastal
/// flat, a border strip) keeps the region it borders. Gaps are numbered in
/// centroid order.
fn gap_pieces(
    outline: &IndiaOutline,
    areas: &[Area],
    regions: &BTreeMap<String, Group>,
) -> Vec<GapPiece> {
    let districts: Vec<&MultiPolygon<f64>> = areas
        .iter()
        .filter(|a| a.country == "IN")
        .map(|a| &a.shape)
        .collect();
    // Sorted by id (the map's order), so overlapping regions resolve the
    // same way on every run: the first region takes the shared land.
    let indian: Vec<&Group> = regions.values().filter(|g| g.country == "IN").collect();
    let mut parts: Vec<(MultiPolygon<f64>, Option<&Group>)> = Vec::new();
    for piece in soi_gaps(outline.polygons(), &districts) {
        parts.extend(split_gap_piece(piece, &indian));
    }
    let mut gaps: Vec<GapPiece> = parts
        .into_iter()
        .map(|(shape, region)| GapPiece {
            id: String::new(),
            area_sq_deg: shape.unsigned_area(),
            centroid: centroid_of(&shape),
            region_id: region.map(|g| g.id.clone()),
            region_name: region.map(|g| g.name.clone()),
            region_code: region.and_then(|g| g.region_code.clone()),
            shape,
        })
        .collect();
    gaps.sort_by(|a, b| {
        a.centroid
            .0
            .total_cmp(&b.centroid.0)
            .then(a.centroid.1.total_cmp(&b.centroid.1))
    });
    for (i, gap) in gaps.iter_mut().enumerate() {
        gap.id = format!("gap-{}", i + 1);
    }
    gaps
}

/// One gap piece as labelled parts (see [`gap_pieces`]).
fn split_gap_piece<'a>(
    piece: Polygon<f64>,
    indian: &[&'a Group],
) -> Vec<(MultiPolygon<f64>, Option<&'a Group>)> {
    let whole = MultiPolygon(vec![piece]);
    let mut rest = whole.clone();
    let mut inside: Vec<(Polygon<f64>, &Group)> = Vec::new();
    let mut most: Option<(f64, &Group)> = None;
    for &region in indian {
        let touches = match (whole.bounding_rect(), region.shape.bounding_rect()) {
            (Some(a), Some(b)) => a.intersects(&b),
            _ => false,
        };
        if !touches {
            continue;
        }
        let overlap = rest.intersection(&region.shape);
        let area = overlap.unsigned_area();
        if area <= 0.0 {
            continue;
        }
        if most.is_none_or(|(a, _)| area > a) {
            most = Some((area, region));
        }
        inside.extend(overlap.0.into_iter().map(|p| (p, region)));
        rest = rest.difference(&region.shape);
    }
    let regions: BTreeSet<&str> = inside
        .iter()
        .filter(|(p, _)| p.unsigned_area() >= GAP_MIN_PIECE_SQ_DEG)
        .map(|(_, g)| g.id.as_str())
        .collect();
    if regions.len() < 2 {
        return vec![(whole, most.map(|(_, g)| g))];
    }
    let mut kept: Vec<(MultiPolygon<f64>, Option<&Group>)> = Vec::with_capacity(inside.len());
    let mut slivers: Vec<Polygon<f64>> = Vec::new();
    let labelled = inside.into_iter().map(|(p, g)| (p, Some(g)));
    for (part, region) in labelled.chain(rest.0.into_iter().map(|p| (p, None))) {
        let area = part.unsigned_area();
        if area >= GAP_MIN_PIECE_SQ_DEG {
            kept.push((MultiPolygon(vec![part]), region));
        } else if area >= GAP_NOISE_SQ_DEG {
            slivers.push(part);
        }
    }
    merge_slivers(&mut kept, slivers);
    kept
}

/// Parts of a split piece below this area, in square degrees (about 12 m²),
/// are rounding noise of the boolean operations along region borders, not
/// land: the real Kashmir split leaves dozens of them of about 1e-13 sq°.
/// They are dropped, not joined.
const GAP_NOISE_SQ_DEG: f64 = 1e-9;

/// Join each sliver to the kept part it shares the longest edge with,
/// counting slivers joined before (so a chain of slivers follows its first
/// link); a sliver bordering no part joins the largest part. Each part is
/// unioned once with all its slivers.
fn merge_slivers<T>(kept: &mut [(MultiPolygon<f64>, T)], slivers: Vec<Polygon<f64>>) {
    let mut joined: Vec<Vec<Polygon<f64>>> = vec![Vec::new(); kept.len()];
    let mut pending = slivers;
    loop {
        let before = pending.len();
        let mut waiting = Vec::with_capacity(before);
        for sliver in pending {
            let best = kept
                .iter()
                .zip(&joined)
                .enumerate()
                .map(|(i, ((part, _), extra))| {
                    let length =
                        shared_edge_length(&sliver, &part.0) + shared_edge_length(&sliver, extra);
                    (i, length)
                })
                .filter(|&(_, length)| length > 0.0)
                .max_by(|a, b| a.1.total_cmp(&b.1))
                .map(|(i, _)| i);
            match best.and_then(|i| joined.get_mut(i)) {
                Some(extra) => extra.push(sliver),
                None => waiting.push(sliver),
            }
        }
        pending = waiting;
        if pending.is_empty() || pending.len() == before {
            break;
        }
    }
    let largest = kept
        .iter()
        .enumerate()
        .max_by(|a, b| a.1.0.unsigned_area().total_cmp(&b.1.0.unsigned_area()))
        .map(|(i, _)| i);
    if let Some(extra) = largest.and_then(|i| joined.get_mut(i)) {
        extra.extend(pending);
    }
    for ((part, _), extra) in kept.iter_mut().zip(joined) {
        if !extra.is_empty() {
            *part = part.union(&MultiPolygon(extra));
        }
    }
}

/// Largest distance, in degrees, of a point from an edge it lies on.
const EDGE_TOLERANCE: f64 = 1e-9;

/// Length, in degrees, of the boundary `sliver` shares with the polygons
/// `part`: the collinear overlap of their ring segments. A shared corner
/// counts 0.
fn shared_edge_length(sliver: &Polygon<f64>, part: &[Polygon<f64>]) -> f64 {
    let Some(bounds) = sliver.bounding_rect() else {
        return 0.0;
    };
    let near: Vec<&Polygon<f64>> = part
        .iter()
        .filter(|p| p.bounding_rect().is_some_and(|r| r.intersects(&bounds)))
        .collect();
    if near.is_empty() {
        return 0.0;
    }
    let segments = |p: &Polygon<f64>| -> Vec<(Coord<f64>, Coord<f64>)> {
        std::iter::once(p.exterior())
            .chain(p.interiors())
            .flat_map(|r| r.lines().map(|l| (l.start, l.end)))
            .collect()
    };
    let theirs: Vec<(Coord<f64>, Coord<f64>)> = near.into_iter().flat_map(segments).collect();
    segments(sliver)
        .into_iter()
        .map(|(p, q)| {
            theirs
                .iter()
                .map(|&(r, s)| collinear_overlap(p, q, r, s))
                .sum::<f64>()
        })
        .sum()
}

/// Length of segment `r s` lying on segment `p q` (0 unless both ends of
/// `r s` are within [`EDGE_TOLERANCE`] of the line through `p q`).
fn collinear_overlap(p: Coord<f64>, q: Coord<f64>, r: Coord<f64>, s: Coord<f64>) -> f64 {
    let d = q - p;
    let length = d.x.hypot(d.y);
    if length == 0.0 {
        return 0.0;
    }
    let off_line = |c: Coord<f64>| ((c.x - p.x) * d.y - (c.y - p.y) * d.x).abs() / length;
    if off_line(r) > EDGE_TOLERANCE || off_line(s) > EDGE_TOLERANCE {
        return 0.0;
    }
    let along = |c: Coord<f64>| ((c.x - p.x) * d.x + (c.y - p.y) * d.y) / length;
    let (a, b) = (along(r), along(s));
    (a.max(b).min(length) - a.min(b).max(0.0)).max(0.0)
}

fn to_multi(parts: &[Vec<Vec<[f64; 2]>>]) -> MultiPolygon<f64> {
    let ring =
        |r: &Vec<[f64; 2]>| LineString::from(r.iter().map(|&[x, y]| (x, y)).collect::<Vec<_>>());
    oriented(&MultiPolygon(
        parts
            .iter()
            .filter_map(|rings| {
                let (outer, holes) = rings.split_first()?;
                Some(Polygon::new(ring(outer), holes.iter().map(ring).collect()))
            })
            .collect(),
    ))
}

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

    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> LineString<f64> {
        LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)])
    }

    fn group(id: &str, code: &str, shape: Polygon<f64>) -> Group {
        Group {
            id: id.to_string(),
            name: format!("{id} name"),
            country: "IN".to_string(),
            region_code: Some(code.to_string()),
            shape: MultiPolygon(vec![shape]),
        }
    }

    /// Shortest text of an f64 (an Indian district vertex) that `serde_json`'s
    /// default parser reads one ULP off.
    const MISROUNDED: &str = "21.546982095478498";

    fn one_area_text(x: &str) -> String {
        format!(
            r#"{{"type":"FeatureCollection","boundary_release":"r","attribution":"a","features":[
            {{"type":"Feature","properties":{{"id":"d","name":"D","country":"IN","level":"county"}},
             "geometry":{{"type":"Polygon","coordinates":[[[{x},1.0],[22,1.0],[22,2.5e0],[{x},2.5E0],[{x},1.0]]]}}}}]}}"#
        )
    }

    #[test]
    fn areas_geojson_coordinates_are_correctly_rounded() {
        let exact: f64 = MISROUNDED.parse().unwrap();
        let naive: f64 = serde_json::from_str(MISROUNDED).unwrap();
        assert_ne!(
            exact.to_bits(),
            naive.to_bits(),
            "fixture must be misrounded by default"
        );
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("areas.geojson");
        std::fs::write(&path, one_area_text(MISROUNDED)).unwrap();
        let file = read_areas_geojson(&path).unwrap();
        let ring = &file.areas[0].shape.0[0].exterior().0;
        assert_eq!(ring[0].x.to_bits(), exact.to_bits());
        assert_eq!(ring[3].x.to_bits(), exact.to_bits());
        assert_eq!(ring[2], Coord { x: 22.0, y: 2.5 });
    }

    #[test]
    fn areas_geojson_write_read_write_is_byte_stable() {
        let exact: f64 = MISROUNDED.parse().unwrap();
        let file = AreasFile {
            areas: vec![Area {
                code: None,
                id: "d".into(),
                name: "D".into(),
                country: "IN".into(),
                level: "county".into(),
                parent_id: None,
                parent_name: None,
                region_code: None,
                shape: MultiPolygon(vec![Polygon::new(rect(exact, 1.0, 22.0, 2.5), vec![])]),
            }],
            boundary_release: "r".into(),
            attribution: "a".into(),
        };
        let dir = tempfile::tempdir().unwrap();
        let first = dir.path().join("first.geojson");
        let second = dir.path().join("second.geojson");
        write_areas_geojson(&first, &file).unwrap();
        let read = read_areas_geojson(&first).unwrap();
        assert_eq!(read, file);
        write_areas_geojson(&second, &read).unwrap();
        let bytes = std::fs::read(&first).unwrap();
        assert_eq!(bytes, std::fs::read(&second).unwrap());
        assert!(String::from_utf8(bytes).unwrap().contains(MISROUNDED));
    }

    #[test]
    fn shared_edge_length_counts_collinear_overlap_only() {
        let a = Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![]);
        // Shares 0.5 of a's right edge (x = 1, y 0.25..0.75).
        let b = MultiPolygon(vec![Polygon::new(rect(1.0, 0.25, 2.0, 0.75), vec![])]);
        assert!((shared_edge_length(&a, &b.0) - 0.5).abs() <= 1e-12);
        // Meets a only at the corner (1, 1).
        let c = MultiPolygon(vec![Polygon::new(rect(1.0, 1.0, 2.0, 2.0), vec![])]);
        assert_eq!(shared_edge_length(&a, &c.0), 0.0);
    }

    #[test]
    fn a_sliver_joins_the_part_it_shares_the_longest_edge_with() {
        // Piece 0..3 × 0..1. Region P covers 0..1, Q covers 1..3 except the
        // corner 2.95..3 × 0.94..1 (0.003), which borders Q only.
        let p = group(
            "div-p",
            "IN-PP",
            Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![]),
        );
        let q_ring = LineString::from(vec![
            (1.0, 0.0),
            (3.0, 0.0),
            (3.0, 0.94),
            (2.95, 0.94),
            (2.95, 1.0),
            (1.0, 1.0),
            (1.0, 0.0),
        ]);
        let q = group("div-q", "IN-QQ", Polygon::new(q_ring, vec![]));
        let piece = Polygon::new(rect(0.0, 0.0, 3.0, 1.0), vec![]);
        let parts = split_gap_piece(piece, &[&p, &q]);
        assert_eq!(parts.len(), 2, "one part per region");
        let total: f64 = parts.iter().map(|(s, _)| s.unsigned_area()).sum();
        assert!((total - 3.0).abs() <= 1e-9, "parts add up to {total}");
        let (q_part, _) = parts
            .iter()
            .find(|(_, g)| g.is_some_and(|g| g.id == "div-q"))
            .expect("Q's part");
        assert!((q_part.unsigned_area() - 2.0).abs() <= 1e-9);
    }

    #[test]
    fn a_sliver_bordering_no_part_joins_the_largest() {
        let mut kept = vec![
            (
                MultiPolygon(vec![Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![])]),
                "small",
            ),
            (
                MultiPolygon(vec![Polygon::new(rect(2.0, 0.0, 4.0, 1.0), vec![])]),
                "large",
            ),
        ];
        let sliver = Polygon::new(rect(10.0, 10.0, 10.05, 10.06), vec![]);
        merge_slivers(&mut kept, vec![sliver]);
        let (large, _) = kept
            .iter()
            .find(|(_, tag)| *tag == "large")
            .expect("the large part");
        assert!((large.unsigned_area() - 2.003).abs() <= 1e-9);
        let (small, _) = kept
            .iter()
            .find(|(_, tag)| *tag == "small")
            .expect("the small part");
        assert!((small.unsigned_area() - 1.0).abs() <= 1e-9);
    }

    fn district(id: &str, code: Option<&str>, shape: Polygon<f64>) -> Group {
        Group {
            id: id.to_string(),
            name: format!("{id} name"),
            country: "IN".to_string(),
            region_code: code.map(str::to_string),
            shape: MultiPolygon(vec![shape]),
        }
    }

    fn two_states() -> BTreeMap<String, Group> {
        let mut groups = BTreeMap::new();
        for g in [
            group(
                "div-ar",
                "IN-AR",
                Polygon::new(rect(0.0, 0.0, 2.0, 1.0), vec![]),
            ),
            group(
                "div-as",
                "IN-AS",
                Polygon::new(rect(2.0, 0.0, 4.0, 1.0), vec![]),
            ),
        ] {
            groups.insert(g.id.clone(), g);
        }
        groups
    }

    #[test]
    fn a_district_without_a_coded_parent_gets_the_state_it_overlaps_most() {
        let groups = two_states();
        let parents = region_parents(&groups);
        // Parent was an uncoded (claim) region: no region code. 0.9 of it
        // lies in IN-AR, 0.1 in IN-AS.
        let tawang = district("d1", None, Polygon::new(rect(1.0, 0.0, 2.1, 1.0), vec![]));
        let parent = resolve_parent(&tawang, &parents)
            .expect("resolves")
            .expect("a parent");
        assert_eq!(parent.region_code.as_deref(), Some("IN-AR"));
        // A coded district keeps its own region.
        let coded = district(
            "d2",
            Some("IN-AS"),
            Polygon::new(rect(1.0, 0.0, 2.1, 1.0), vec![]),
        );
        let parent = resolve_parent(&coded, &parents)
            .expect("resolves")
            .expect("a parent");
        assert_eq!(parent.region_code.as_deref(), Some("IN-AS"));
        // A code no coded region holds falls back to geometry too.
        let unknown = district(
            "d3",
            Some("IN-ZZ"),
            Polygon::new(rect(3.0, 0.0, 3.5, 1.0), vec![]),
        );
        let parent = resolve_parent(&unknown, &parents)
            .expect("resolves")
            .expect("a parent");
        assert_eq!(parent.region_code.as_deref(), Some("IN-AS"));
    }

    #[test]
    fn an_indian_district_overlapping_no_coded_state_fails() {
        let groups = two_states();
        let parents = region_parents(&groups);
        let lost = district(
            "d9",
            None,
            Polygon::new(rect(10.0, 10.0, 11.0, 11.0), vec![]),
        );
        let Err(err) = resolve_parent(&lost, &parents) else {
            panic!("a district overlapping no coded region must fail");
        };
        assert!(geolith::error::report(&err).contains("d9"), "{err:#}");
        // Outside India the old rule stays: no code, no parent, no error.
        let mut abroad = lost;
        abroad.country = "NP".to_string();
        assert!(
            resolve_parent(&abroad, &parents)
                .expect("no error")
                .is_none()
        );
    }

    fn area_in(id: &str, code: Option<&str>, parent: Option<&str>) -> Area {
        Area {
            code: None,
            id: id.to_string(),
            name: id.to_string(),
            country: "IN".to_string(),
            level: "county".to_string(),
            parent_id: parent.map(|p| format!("{p}-id")),
            parent_name: parent.map(str::to_string),
            region_code: code.map(str::to_string),
            shape: MultiPolygon(vec![]),
        }
    }

    #[test]
    fn every_indian_district_has_a_state_and_every_state_a_district() {
        let groups = two_states();
        let parents = region_parents(&groups);
        let ok = [
            area_in("a", Some("IN-AR"), Some("Arunachal Pradesh")),
            area_in("b", Some("IN-AS"), Some("Assam")),
            area_in("c", Some("IN-AS"), Some("Assam")),
        ];
        let counts = check_india_regions(&ok, &parents, &[]).expect("complete");
        assert_eq!(counts.get("IN-AR"), Some(&1));
        assert_eq!(counts.get("IN-AS"), Some(&2));
        let orphan = [
            area_in("a", Some("IN-AR"), Some("Arunachal Pradesh")),
            area_in("b", None, None),
        ];
        let err = check_india_regions(&orphan, &parents, &[]).expect_err("null state");
        assert!(
            geolith::error::report(&err).contains("1 Indian districts have no state"),
            "{err:#}"
        );
        let empty_state = [area_in("a", Some("IN-AR"), Some("Arunachal Pradesh"))];
        let err = check_india_regions(&empty_state, &parents, &[]).expect_err("IN-AS empty");
        assert!(geolith::error::report(&err).contains("IN-AS"), "{err:#}");
        let counts = check_india_regions(&empty_state, &parents, &["IN-AS".to_string()])
            .expect("IN-AS allowlisted");
        assert_eq!(counts.get("IN-AS"), Some(&0));
    }

    #[test]
    fn duplicate_region_codes_keep_the_larger_group() {
        let mut groups = BTreeMap::new();
        for g in [
            group(
                "div-a",
                "IN-XX",
                Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![]),
            ),
            group(
                "div-b",
                "IN-XX",
                Polygon::new(rect(0.0, 0.0, 3.0, 1.0), vec![]),
            ),
            group(
                "div-c",
                "IN-XX",
                Polygon::new(rect(0.0, 0.0, 2.0, 1.0), vec![]),
            ),
        ] {
            groups.insert(g.id.clone(), g);
        }
        let parents = region_parents(&groups);
        assert_eq!(parents.len(), 1);
        let kept = parents.get(&("IN", "IN-XX")).expect("IN-XX");
        assert_eq!(kept.id, "div-b");
    }

    #[test]
    fn soi_gaps_drops_pieces_below_the_threshold() {
        let outline = MultiPolygon(vec![Polygon::new(rect(0.0, 0.0, 10.0, 10.0), vec![])]);
        let east = MultiPolygon(vec![Polygon::new(
            rect(0.05, 0.0, 10.0, 10.0),
            vec![rect(8.0, 8.0, 9.0, 9.0)],
        )]);
        let west = MultiPolygon(vec![Polygon::new(rect(0.0, 0.05, 0.05, 10.0), vec![])]);
        let gaps = soi_gaps(&outline, &[&east, &west]);
        assert_eq!(gaps.len(), 1);
        let area: f64 = gaps.iter().map(Polygon::unsigned_area).sum();
        assert!((area - 1.0).abs() <= 1e-9, "gap area {area}");
    }
}