geolith 0.1.2

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
//! Admin hierarchy resolution by point-in-polygon lookup.
//!
//! Overture `divisions/division_area` polygons are loaded into an rstar
//! R-tree, one entry per polygon part. Each part keeps its exterior and hole
//! rings exactly (no simplification) and carries a banded edge index, so a
//! containment test scans only the edges that cross the point's latitude
//! band rather than every vertex of a country outline.

pub mod india;

use std::collections::HashMap;
use std::path::Path;

use rstar::{AABB, RTree, RTreeObject};
use serde::{Deserialize, Serialize};

use crate::admin::india::{IndiaOutline, IndiaView};
use crate::error::GeolithError;
use crate::source::bbox_filter::Bbox;
use crate::source::input::InputFeature;
use crate::source::overture_files;
use crate::source::reader::read_parquet_file_with_source_id;
use crate::source::schema::OvertureType;

/// Admin level classification.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AdminLevel {
    /// Country (ISO 3166-1 alpha-2 code).
    Country,
    /// Dependency (e.g. Puerto Rico). Fills the country fields only when no
    /// country contains the point.
    Dependency,
    /// Region / state / province.
    Region,
    /// County / district.
    County,
    /// Locality / city / town / village.
    Locality,
    /// Neighbourhood / suburb.
    Neighbourhood,
}

impl AdminLevel {
    /// Map an Overture `division_area.subtype` to a level.
    ///
    /// Only the levels the geocoding records carry are mapped; `localadmin`,
    /// `macrohood` and `microhood` return `None`.
    #[must_use]
    pub fn from_overture_subtype(subtype: &str) -> Option<Self> {
        match subtype {
            "country" => Some(Self::Country),
            "dependency" => Some(Self::Dependency),
            "region" => Some(Self::Region),
            "county" => Some(Self::County),
            "locality" => Some(Self::Locality),
            "neighborhood" => Some(Self::Neighbourhood),
            _ => None,
        }
    }
}

/// Resolved admin hierarchy for a geographic point.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AdminHierarchy {
    /// ISO 3166-1 alpha-2 country code (e.g., "IN", "US").
    pub country_code: Option<String>,
    /// Country name.
    pub country: Option<String>,
    /// Region / state name.
    pub region: Option<String>,
    /// County / district name.
    pub county: Option<String>,
    /// Locality / city name.
    pub locality: Option<String>,
    /// Neighbourhood name.
    pub neighbourhood: Option<String>,
    /// Borough, city district or suburb around the neighbourhood.
    #[serde(default)]
    pub borough: Option<String>,
    /// Postcode of the nearest postcode centroid, for a place that has
    /// none of its own; shown, not searched.
    #[serde(default)]
    pub postcode: Option<String>,
    /// The largest locality holding the place, when it is not the locality:
    /// the city around a ward or village ("Bengaluru" around "Chikka
    /// Devasandra"). Photon keeps the city and the district apart; the
    /// smallest locality alone loses the city a search names.
    #[serde(default)]
    pub city: Option<String>,
}

/// An admin division to add to the index.
#[derive(Debug, Clone)]
pub struct AdminDivision {
    /// Division ID.
    pub id: u64,
    /// Admin level.
    pub level: AdminLevel,
    /// Display name.
    pub name: String,
    /// ISO 3166-1 alpha-2 country code of the division.
    pub country_code: Option<String>,
    /// ISO 3166-2 code of the region the division is or lies in
    /// (Overture's `region`, e.g. `IN-LA`).
    pub region_code: Option<String>,
    /// Polygon parts as lon/lat rings: `parts[i][0]` is the exterior of part
    /// `i` and any further rings are its holes.
    pub parts: Vec<Vec<Vec<[f64; 2]>>>,
}

/// Name and level shared by every part of one division.
#[derive(Debug)]
struct DivisionMeta {
    id: u64,
    level: AdminLevel,
    name: String,
    country_code: Option<String>,
}

/// One polygon part (exterior plus holes), prepared in memory for fast
/// containment and then written to the index's scratch file.
///
/// All rings are stored in `pts`, separated by a NaN point, so edge `i` runs
/// from `pts[i]` to `pts[i + 1]` unless either end is the separator. Edges are
/// bucketed into horizontal bands (CSR layout) so a ray-cast only visits edges
/// whose latitude range covers the query point.
struct Prepared {
    bbox: [f64; 4],
    area: f64,
    pts: Vec<[f64; 2]>,
    band_height: f64,
    band_offsets: Vec<u32>,
    band_edges: Vec<u32>,
}

/// Average number of edges per band. Small enough that a lookup touches a
/// handful of edges, large enough that the index stays a fraction of the
/// vertex storage.
const EDGES_PER_BAND: usize = 8;

impl Prepared {
    /// Prepare one part, or `None` if it has no ring with at least 3 points.
    fn new(rings: &[Vec<[f64; 2]>]) -> Option<Self> {
        let total: usize = rings.iter().map(|r| r.len() + 2).sum();
        let mut pts: Vec<[f64; 2]> = Vec::with_capacity(total);
        let mut area = 0.0;
        for (i, ring) in rings.iter().enumerate() {
            if ring.len() < 3 {
                continue;
            }
            if !pts.is_empty() {
                pts.push([f64::NAN, f64::NAN]);
            }
            pts.extend_from_slice(ring);
            if ring.first() != ring.last() {
                pts.push(ring[0]);
            }
            let ring_area = shoelace(ring).abs();
            area += if i == 0 { ring_area } else { -ring_area };
        }
        if pts.len() < 4 {
            return None;
        }

        let mut bbox = [
            f64::INFINITY,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NEG_INFINITY,
        ];
        for p in pts.iter().filter(|p| !p[0].is_nan()) {
            bbox[0] = bbox[0].min(p[0]);
            bbox[1] = bbox[1].min(p[1]);
            bbox[2] = bbox[2].max(p[0]);
            bbox[3] = bbox[3].max(p[1]);
        }

        let edges = pts.len() - 1;
        let bands = (edges / EDGES_PER_BAND).max(1);
        let height = (bbox[3] - bbox[1]) / bands as f64;
        let band_height = if height > 0.0 { height } else { 1.0 };
        let band_of = |y: f64| -> usize { (((y - bbox[1]) / band_height) as usize).min(bands - 1) };
        let edge_bands = |i: usize| -> Option<(usize, usize)> {
            let (a, b) = (pts[i], pts[i + 1]);
            if a[0].is_nan() || b[0].is_nan() {
                return None;
            }
            Some((band_of(a[1].min(b[1])), band_of(a[1].max(b[1]))))
        };

        let mut counts = vec![0u32; bands + 1];
        for i in 0..edges {
            if let Some((lo, hi)) = edge_bands(i) {
                for c in &mut counts[lo + 1..=hi + 1] {
                    *c += 1;
                }
            }
        }
        for b in 0..bands {
            counts[b + 1] += counts[b];
        }
        let band_offsets = counts;
        let mut cursor: Vec<u32> = band_offsets[..bands].to_vec();
        let mut band_edges = vec![0u32; band_offsets[bands] as usize];
        for i in 0..edges {
            if let Some((lo, hi)) = edge_bands(i) {
                for c in &mut cursor[lo..=hi] {
                    band_edges[*c as usize] = i as u32;
                    *c += 1;
                }
            }
        }

        Some(Self {
            bbox,
            area,
            pts,
            band_height,
            band_offsets,
            band_edges,
        })
    }

    /// Write the part to `out` (vertices, band offsets, band edges, all
    /// little-endian) and return what the index keeps in memory. `at` is the
    /// file position of `out` and moves past the part.
    fn store(
        &self,
        meta: std::sync::Arc<DivisionMeta>,
        out: &mut impl std::io::Write,
        at: &mut u64,
    ) -> std::io::Result<PartRef> {
        let pts_at = *at;
        for p in &self.pts {
            out.write_all(&p[0].to_le_bytes())?;
            out.write_all(&p[1].to_le_bytes())?;
        }
        let offsets_at = pts_at + 16 * self.pts.len() as u64;
        for o in &self.band_offsets {
            out.write_all(&o.to_le_bytes())?;
        }
        let edges_at = offsets_at + 4 * self.band_offsets.len() as u64;
        for e in &self.band_edges {
            out.write_all(&e.to_le_bytes())?;
        }
        *at = edges_at + 4 * self.band_edges.len() as u64;
        Ok(PartRef {
            meta,
            bbox: self.bbox,
            area: self.area,
            band_height: self.band_height,
            bands: u32::try_from(self.band_offsets.len() - 1).unwrap_or(u32::MAX),
            pts_at,
            offsets_at,
            edges_at,
        })
    }
}

/// One polygon part as the index keeps it: the bounding box and where its
/// vertices and band index sit in the scratch file the index maps.
#[derive(Debug)]
struct PartRef {
    meta: std::sync::Arc<DivisionMeta>,
    bbox: [f64; 4],
    area: f64,
    band_height: f64,
    bands: u32,
    pts_at: u64,
    offsets_at: u64,
    edges_at: u64,
}

/// The little-endian `u32` at byte `at` of `data`.
fn u32_at(data: &[u8], at: u64) -> u32 {
    let at = at as usize;
    let mut raw = [0_u8; 4];
    raw.copy_from_slice(&data[at..at + 4]);
    u32::from_le_bytes(raw)
}

/// The little-endian `f64` at byte `at` of `data`.
fn f64_at(data: &[u8], at: u64) -> f64 {
    let at = at as usize;
    let mut raw = [0_u8; 8];
    raw.copy_from_slice(&data[at..at + 8]);
    f64::from_le_bytes(raw)
}

impl PartRef {
    /// Even-odd ray-cast over the edges in the point's band, read from the
    /// mapped scratch file `data`. Holes are rings like any other, so a point
    /// inside a hole crosses an even number of edges and is outside.
    fn contains(&self, data: &[u8], lon: f64, lat: f64) -> bool {
        let bands = self.bands as usize;
        let band = (((lat - self.bbox[1]) / self.band_height) as usize).min(bands - 1);
        let first = u64::from(u32_at(data, self.offsets_at + 4 * band as u64));
        let last = u64::from(u32_at(data, self.offsets_at + 4 * (band as u64 + 1)));
        let vertex = |i: u64| {
            let at = self.pts_at + 16 * i;
            (f64_at(data, at), f64_at(data, at + 8))
        };
        let mut inside = false;
        for k in first..last {
            let i = u64::from(u32_at(data, self.edges_at + 4 * k));
            let (a, b) = (vertex(i), vertex(i + 1));
            if (a.1 > lat) != (b.1 > lat) && lon < (b.0 - a.0) * (lat - a.1) / (b.1 - a.1) + a.0 {
                inside = !inside;
            }
        }
        inside
    }
}

impl RTreeObject for PartRef {
    type Envelope = AABB<[f64; 2]>;

    fn envelope(&self) -> Self::Envelope {
        AABB::from_corners([self.bbox[0], self.bbox[1]], [self.bbox[2], self.bbox[3]])
    }
}

/// Twice the signed area of a ring (shoelace formula).
fn shoelace(ring: &[[f64; 2]]) -> f64 {
    let mut sum = 0.0;
    for (i, a) in ring.iter().enumerate() {
        let b = ring[(i + 1) % ring.len()];
        sum += a[0] * b[1] - b[0] * a[1];
    }
    sum / 2.0
}

/// Builder for the admin hierarchy R-tree index.
///
/// The vertices of every polygon go to an anonymous scratch file as they are
/// added, so the planet's ~500 million division vertices (about 9 GB as
/// vectors) never sit in memory; [`Self::build`] maps the file.
#[derive(Default)]
pub struct AdminHierarchyBuilder {
    parts: Vec<PartRef>,
    /// Each division's parts in the scratch file: where its points start
    /// and how many there are.
    outlines: HashMap<u64, Vec<(u64, u64)>>,
    /// Per ISO code, the country (or dependency) with that code: its
    /// `(level slot, id)`, lowest first, and its name.
    countries: HashMap<String, ((usize, u64), String)>,
    /// Directory of the scratch file; the system temporary directory if unset.
    scratch_dir: Option<std::path::PathBuf>,
    scratch: Option<std::io::BufWriter<std::fs::File>>,
    written: u64,
}

impl AdminHierarchyBuilder {
    /// Create a new empty builder with its scratch file in the system
    /// temporary directory.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new empty builder with its scratch file in `dir`.
    #[must_use]
    pub fn in_dir(dir: &Path) -> Self {
        Self {
            scratch_dir: Some(dir.to_path_buf()),
            ..Self::default()
        }
    }

    /// Add a division; each of its polygon parts becomes one index entry.
    ///
    /// # Errors
    ///
    /// Returns an error if the scratch file cannot be created or written.
    pub fn add(&mut self, division: AdminDivision) -> std::io::Result<()> {
        if let (AdminLevel::Country | AdminLevel::Dependency, Some(code)) =
            (division.level, &division.country_code)
        {
            // A country wins over a dependency with the same code, then the
            // lowest id, so the name does not depend on the load order.
            let key = (level_slot(division.level), division.id);
            let entry = self
                .countries
                .entry(code.clone())
                .or_insert_with(|| (key, division.name.clone()));
            if key < entry.0 {
                *entry = (key, division.name.clone());
            }
        }
        let meta = std::sync::Arc::new(DivisionMeta {
            id: division.id,
            level: division.level,
            name: division.name,
            country_code: division.country_code,
        });
        for rings in &division.parts {
            let Some(part) = Prepared::new(rings) else {
                continue;
            };
            let out = match &mut self.scratch {
                Some(out) => out,
                none => {
                    let file = match &self.scratch_dir {
                        Some(dir) => tempfile::tempfile_in(dir)?,
                        None => tempfile::tempfile()?,
                    };
                    none.insert(std::io::BufWriter::with_capacity(1 << 20, file))
                }
            };
            let stored = part.store(meta.clone(), out, &mut self.written)?;
            self.outlines
                .entry(meta.id)
                .or_default()
                .push((stored.pts_at, part.pts.len() as u64));
            self.parts.push(stored);
        }
        Ok(())
    }

    /// Build the R-tree index from all added divisions and map the scratch
    /// file that holds their vertices.
    ///
    /// # Errors
    ///
    /// Returns an error if the scratch file cannot be flushed or mapped.
    #[allow(
        unsafe_code,
        reason = "memmap2::Mmap::map of the private scratch file; the SAFETY comment below states why it is sound"
    )]
    pub fn build(self) -> std::io::Result<AdminHierarchyIndex> {
        let data = match self.scratch {
            Some(out) => {
                let file = out
                    .into_inner()
                    .map_err(std::io::IntoInnerError::into_error)?;
                // SAFETY: the file is anonymous scratch made by this
                // process: it has no path, nothing else opens it, and it is
                // not written or truncated after this point, so the mapped
                // bytes never change while the map lives.
                Some(unsafe { memmap2::Mmap::map(&file)? })
            }
            None => None,
        };
        Ok(AdminHierarchyIndex {
            tree: RTree::bulk_load(self.parts),
            countries: self
                .countries
                .into_iter()
                .map(|(code, (_, name))| (code, name))
                .collect(),
            outlines: self.outlines,
            data,
        })
    }
}

/// Spatial index for resolving admin hierarchy via point-in-polygon.
pub struct AdminHierarchyIndex {
    tree: RTree<PartRef>,
    /// Name of the country (or dependency) with each ISO code.
    countries: HashMap<String, String>,
    /// Each division's parts in the scratch file.
    outlines: HashMap<u64, Vec<(u64, u64)>>,
    /// The scratch file with every part's vertices and band index.
    data: Option<memmap2::Mmap>,
}

impl AdminHierarchyIndex {
    /// Resolve the admin hierarchy for a WGS84 lon/lat point.
    ///
    /// When several divisions of one level contain the point, the one with
    /// the smallest area wins (ties: lowest id). A dependency fills the
    /// country fields only when no country contains the point. When neither
    /// does, the country code comes from the region (else county, locality,
    /// neighbourhood) that contains the point, and the country name from
    /// the country with that code.
    #[must_use]
    pub fn resolve(&self, lon: f64, lat: f64) -> AdminHierarchy {
        let point = [lon, lat];
        let data: &[u8] = self.data.as_deref().unwrap_or(&[]);
        let mut best: [Option<&PartRef>; 6] = [None; 6];
        let mut largest: Option<&PartRef> = None;
        for part in self
            .tree
            .locate_in_envelope_intersecting(AABB::from_point(point))
        {
            if !part.contains(data, lon, lat) {
                continue;
            }
            if part.meta.level == AdminLevel::Locality
                && largest.is_none_or(|cur| (part.area, cur.meta.id) > (cur.area, part.meta.id))
            {
                largest = Some(part);
            }
            let slot = &mut best[level_slot(part.meta.level)];
            let better = match slot {
                None => true,
                Some(cur) => (part.area, part.meta.id) < (cur.area, cur.meta.id),
            };
            if better {
                *slot = Some(part);
            }
        }

        let name = |slot: usize| best[slot].map(|p| p.meta.name.clone());
        let (country_code, country) = match best[0].or(best[1]) {
            Some(part) => (part.meta.country_code.clone(), Some(part.meta.name.clone())),
            // A coastal place can lie outside its country's land polygon and
            // inside its region's (Gateway of India: in Maharashtra, not in
            // India). Every division carries its country's code.
            None => {
                let code = best[2..]
                    .iter()
                    .flatten()
                    .find_map(|part| part.meta.country_code.clone());
                let country = code
                    .as_ref()
                    .and_then(|code| self.countries.get(code).cloned());
                (code, country)
            }
        };
        let locality = name(4);
        let city = largest.map(|p| p.meta.name.clone()).filter(|city| {
            locality
                .as_ref()
                .is_some_and(|l| !l.eq_ignore_ascii_case(city))
        });
        AdminHierarchy {
            country_code,
            country,
            region: name(2),
            county: name(3),
            locality,
            neighbourhood: name(5),
            borough: None,
            postcode: None,
            city,
        }
    }

    /// The outline of the division that holds the point at one of `levels`
    /// and is named one of `names` (compared case-blind): its polygons,
    /// each an outer ring then its holes. When several do, the smallest
    /// wins (ties: lowest id); `None` when none does.
    #[must_use]
    pub fn outline(
        &self,
        lon: f64,
        lat: f64,
        levels: &[AdminLevel],
        names: &[&str],
    ) -> Option<Vec<Vec<Vec<[f64; 2]>>>> {
        let data: &[u8] = self.data.as_deref()?;
        let names: Vec<String> = names
            .iter()
            .map(|name| name.trim().to_lowercase())
            .collect();
        let best = self
            .tree
            .locate_in_envelope_intersecting(AABB::from_point([lon, lat]))
            .filter(|part| levels.contains(&part.meta.level))
            .filter(|part| names.contains(&part.meta.name.trim().to_lowercase()))
            .filter(|part| part.contains(data, lon, lat))
            .min_by(|a, b| a.area.total_cmp(&b.area).then(a.meta.id.cmp(&b.meta.id)))?;
        let parts = self.outlines.get(&best.meta.id)?;
        let mut polygons = Vec::with_capacity(parts.len());
        for &(at, count) in parts {
            let mut rings: Vec<Vec<[f64; 2]>> = vec![Vec::new()];
            for i in 0..count {
                let x = f64_at(data, at + 16 * i);
                let y = f64_at(data, at + 16 * i + 8);
                if x.is_nan() {
                    rings.push(Vec::new());
                } else if let Some(ring) = rings.last_mut() {
                    ring.push([x, y]);
                }
            }
            polygons.push(rings);
        }
        Some(polygons)
    }

    /// Whether a country or dependency with this ISO code is indexed.
    #[must_use]
    pub fn has_country(&self, code: &str) -> bool {
        self.countries.contains_key(code)
    }

    /// Bytes of polygon data kept in the mapped scratch file, not in memory.
    #[must_use]
    pub fn backing_bytes(&self) -> u64 {
        self.data.as_ref().map_or(0, |data| data.len() as u64)
    }

    /// Return the number of polygon parts in the index.
    #[must_use]
    pub fn len(&self) -> usize {
        self.tree.size()
    }

    /// Return true if the index is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.tree.size() == 0
    }
}

/// Index of a level in [`AdminHierarchyIndex::resolve`]'s slot array.
const fn level_slot(level: AdminLevel) -> usize {
    match level {
        AdminLevel::Country => 0,
        AdminLevel::Dependency => 1,
        AdminLevel::Region => 2,
        AdminLevel::County => 3,
        AdminLevel::Locality => 4,
        AdminLevel::Neighbourhood => 5,
    }
}

/// Convert a decoded Overture `division_area` feature into an [`AdminDivision`].
///
/// Returns `None` for maritime areas (their territorial-water extent would
/// place coastal points in the sea area), for subtypes the records do not
/// carry, and for features without a primary name or polygon geometry.
#[must_use]
pub fn division_from_feature(feature: &InputFeature) -> Option<AdminDivision> {
    let text = |key: &str| {
        feature
            .get_str(key)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
    };
    if text("class")? != "land" {
        return None;
    }
    let level = AdminLevel::from_overture_subtype(&text("subtype")?)?;
    let name = text("names.primary")?;

    let ring = |r: &geo::LineString<f64>| r.coords().map(|c| [c.x, c.y]).collect::<Vec<_>>();
    let part = |p: &geo::Polygon<f64>| {
        std::iter::once(ring(p.exterior()))
            .chain(p.interiors().iter().map(ring))
            .collect::<Vec<_>>()
    };
    let parts = match feature.geometry.as_ref() {
        geo::Geometry::Polygon(p) => vec![part(p)],
        geo::Geometry::MultiPolygon(mp) => mp.iter().map(part).collect(),
        _ => return None,
    };

    Some(AdminDivision {
        id: feature.id,
        level,
        name,
        country_code: text("country").map(|c| c.to_uppercase()),
        region_code: text("region").map(|c| c.to_uppercase()),
        parts,
    })
}

/// Load `divisions/division_area` from an Overture release directory.
///
/// Files are read in sorted path order so the index, and therefore every
/// tie-break, is identical on every platform. A missing `division_area`
/// directory yields an empty index; the geocoding records then carry no admin
/// hierarchy, as before.
///
/// The polygon vertices go to a scratch file in `scratch_dir` (the system
/// temporary directory if `None`) that the index maps, so the planet's
/// division polygons do not take memory.
///
/// With `india`, India and its neighbours are drawn on the Survey of India
/// map (see [`crate::admin::india`]).
///
/// # Errors
///
/// `GeolithError::Io` when a divisions file or the scratch polygon file
/// cannot be read or written, and `GeolithError::Parquet` or
/// `GeolithError::Arrow` when a divisions row cannot be decoded.
pub fn load_admin_index(
    data_dir: &Path,
    bbox: Option<&Bbox>,
    scratch_dir: Option<&Path>,
    india: Option<&IndiaOutline>,
) -> crate::error::Result<AdminHierarchyIndex> {
    let mut view = india.map(IndiaView::new);
    let otype = OvertureType::new("divisions", "division_area");
    let files = overture_files(data_dir, otype)?;
    let mut builder = match scratch_dir {
        Some(dir) => AdminHierarchyBuilder::in_dir(dir),
        None => AdminHierarchyBuilder::new(),
    };
    let mut failed: Option<std::io::Error> = None;
    for path in &files {
        read_parquet_file_with_source_id(path, otype, bbox, |feature| {
            if failed.is_some() {
                return;
            }
            let division = match (division_from_feature(&feature), view.as_mut()) {
                (Some(d), Some(view)) => view.admit(d),
                (d, None) => d,
                (None, Some(_)) => None,
            };
            if let Some(division) = division
                && let Err(e) = builder.add(division)
            {
                failed = Some(e);
            }
        })
        .map_err(|e| e.context(format!("failed to read {}", path.display())))?;
        if let Some(e) = failed.take() {
            return Err(GeolithError::from(e).context(SCRATCH_WRITE));
        }
    }
    for division in view.map(IndiaView::finish).unwrap_or_default() {
        builder
            .add(division)
            .map_err(|e| GeolithError::from(e).context(SCRATCH_WRITE))?;
    }
    let (file_count, part_count) = (files.len(), builder.parts.len());
    tracing::info!(
        files = file_count,
        parts = part_count,
        "division_area loaded"
    );
    builder
        .build()
        .map_err(|e| GeolithError::from(e).context("failed to map the admin polygon scratch file"))
}

const SCRATCH_WRITE: &str = "failed to write the admin polygon scratch file";

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

    fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<[f64; 2]> {
        vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
    }

    fn division(
        id: u64,
        level: AdminLevel,
        name: &str,
        parts: Vec<Vec<Vec<[f64; 2]>>>,
    ) -> AdminDivision {
        AdminDivision {
            id,
            level,
            name: name.to_string(),
            country_code: None,
            region_code: None,
            parts,
        }
    }

    fn index(divisions: Vec<AdminDivision>) -> AdminHierarchyIndex {
        let mut b = AdminHierarchyBuilder::new();
        for d in divisions {
            b.add(d).unwrap();
        }
        b.build().unwrap()
    }

    fn index_in(dir: &Path, divisions: Vec<AdminDivision>) -> AdminHierarchyIndex {
        let mut b = AdminHierarchyBuilder::in_dir(dir);
        for d in divisions {
            b.add(d).unwrap();
        }
        b.build().unwrap()
    }

    /// The planet has ~1.27M division polygons with ~500M vertices, about 9 GB
    /// as `Vec<[f64; 2]>`. They must live in a scratch file the index maps, so
    /// a build fits in a small machine's memory.
    #[test]
    fn polygon_vertices_live_in_a_scratch_file() {
        let vertices = 20_000_usize;
        let ring: Vec<[f64; 2]> = (0..vertices)
            .map(|i| {
                let angle = std::f64::consts::TAU * i as f64 / vertices as f64;
                [10.0 + angle.cos(), 10.0 + angle.sin()]
            })
            .collect();
        let tmp = tempfile::tempdir().unwrap();
        let idx = index_in(
            tmp.path(),
            vec![division(1, AdminLevel::Locality, "Round", vec![vec![ring]])],
        );
        // 16 bytes per vertex, worked out from the two f64 coordinates.
        assert!(
            idx.backing_bytes() >= vertices as u64 * 16,
            "{} bytes",
            idx.backing_bytes()
        );
        assert_eq!(idx.resolve(10.0, 10.0).locality.as_deref(), Some("Round"));
        assert_eq!(idx.resolve(10.9, 10.0).locality.as_deref(), Some("Round"));
        assert!(idx.resolve(11.1, 10.0).locality.is_none());
    }

    #[test]
    fn empty_index_resolves_nothing() {
        let idx = index(vec![]);
        assert!(idx.is_empty());
        assert!(idx.resolve(77.0, 28.0).country.is_none());
    }

    #[test]
    fn country_fields_come_from_the_containing_country() {
        let mut india = division(
            1,
            AdminLevel::Country,
            "India",
            vec![vec![square(68.0, 6.5, 97.5, 37.2)]],
        );
        india.country_code = Some("IN".into());
        let idx = index(vec![india]);
        let h = idx.resolve(77.0, 28.0);
        assert_eq!(h.country.as_deref(), Some("India"));
        assert_eq!(h.country_code.as_deref(), Some("IN"));
        assert!(idx.resolve(0.0, 0.0).country.is_none());
    }

    /// A country with a hole (an enclave, like Lesotho inside South Africa):
    /// a point in the hole belongs to the enclave, not the surrounding country.
    #[test]
    fn a_point_in_a_hole_is_outside_the_surrounding_country() {
        let south_africa = division(
            1,
            AdminLevel::Country,
            "South Africa",
            vec![vec![
                square(16.0, -35.0, 33.0, -22.0),
                square(27.0, -30.7, 29.5, -28.5),
            ]],
        );
        let lesotho = division(
            2,
            AdminLevel::Country,
            "Lesotho",
            vec![vec![square(27.0, -30.7, 29.5, -28.5)]],
        );
        let idx = index(vec![south_africa, lesotho]);
        assert_eq!(idx.resolve(28.2, -29.6).country.as_deref(), Some("Lesotho"));
        assert_eq!(
            idx.resolve(18.4, -33.9).country.as_deref(),
            Some("South Africa")
        );
    }

    /// A multipolygon: every part (an island) resolves to the division.
    #[test]
    fn every_part_of_a_multipolygon_resolves() {
        let islands = division(
            1,
            AdminLevel::Region,
            "Islands",
            vec![
                vec![square(0.0, 0.0, 1.0, 1.0)],
                vec![square(10.0, 10.0, 11.0, 11.0)],
            ],
        );
        let idx = index(vec![islands]);
        assert_eq!(idx.len(), 2);
        assert_eq!(idx.resolve(0.5, 0.5).region.as_deref(), Some("Islands"));
        assert_eq!(idx.resolve(10.5, 10.5).region.as_deref(), Some("Islands"));
        assert!(idx.resolve(5.0, 5.0).region.is_none());
    }

    /// A concave C-shape with 400 vertices, so the banded index spans many
    /// bands. The notch is outside even though it is inside the bounding box.
    #[test]
    fn a_detailed_concave_ring_is_tested_exactly() {
        // Outer square 0..10 with a notch cut from x=3..10, y=4..6, drawn with
        // many collinear points along each side.
        let mut ring = Vec::new();
        let steps = 50;
        let side = |ring: &mut Vec<[f64; 2]>, a: [f64; 2], b: [f64; 2]| {
            for k in 0..steps {
                let t = k as f64 / steps as f64;
                ring.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
            }
        };
        for w in [
            [[0.0, 0.0], [10.0, 0.0]],
            [[10.0, 0.0], [10.0, 4.0]],
            [[10.0, 4.0], [3.0, 4.0]],
            [[3.0, 4.0], [3.0, 6.0]],
            [[3.0, 6.0], [10.0, 6.0]],
            [[10.0, 6.0], [10.0, 10.0]],
            [[10.0, 10.0], [0.0, 10.0]],
            [[0.0, 10.0], [0.0, 0.0]],
        ] {
            side(&mut ring, w[0], w[1]);
        }
        let idx = index(vec![division(
            1,
            AdminLevel::Locality,
            "C",
            vec![vec![ring]],
        )]);
        for (x, y, inside) in [
            (1.0, 1.0, true),
            (9.0, 9.0, true),
            (2.0, 5.0, true),
            (5.0, 5.0, false),
            (9.9, 5.0, false),
            (11.0, 5.0, false),
            (5.0, 3.9, true),
            (5.0, 6.1, true),
        ] {
            assert_eq!(idx.resolve(x, y).locality.is_some(), inside, "({x}, {y})");
        }
    }

    #[test]
    fn the_smallest_containing_division_of_a_level_wins() {
        let big = division(
            1,
            AdminLevel::Locality,
            "Big",
            vec![vec![square(0.0, 0.0, 10.0, 10.0)]],
        );
        let small = division(
            9,
            AdminLevel::Locality,
            "Small",
            vec![vec![square(4.0, 4.0, 6.0, 6.0)]],
        );
        let idx = index(vec![small, big]);
        assert_eq!(idx.resolve(5.0, 5.0).locality.as_deref(), Some("Small"));
        assert_eq!(idx.resolve(1.0, 1.0).locality.as_deref(), Some("Big"));
    }

    /// A place in a ward keeps the city around it as its city, as Photon
    /// keeps the city apart from the district: "Swensen's, Bengaluru" must
    /// find the shop in the ward Chikka Devasandra. The largest locality
    /// holding the point is the city; it is left out when it is the
    /// locality itself.
    #[test]
    fn the_largest_containing_locality_is_the_city() {
        let city = division(
            1,
            AdminLevel::Locality,
            "Bengaluru",
            vec![vec![square(0.0, 0.0, 10.0, 10.0)]],
        );
        let ward = division(
            9,
            AdminLevel::Locality,
            "Chikka Devasandra",
            vec![vec![square(4.0, 4.0, 6.0, 6.0)]],
        );
        let mid = division(
            5,
            AdminLevel::Locality,
            "Bangalore East",
            vec![vec![square(3.0, 3.0, 7.0, 7.0)]],
        );
        let idx = index(vec![ward, city, mid]);
        let inner = idx.resolve(5.0, 5.0);
        assert_eq!(inner.locality.as_deref(), Some("Chikka Devasandra"));
        assert_eq!(inner.city.as_deref(), Some("Bengaluru"));
        assert_eq!(idx.resolve(1.0, 1.0).city, None);
    }

    #[test]
    fn equal_areas_tie_break_on_the_lower_id() {
        let a = division(
            7,
            AdminLevel::County,
            "Seven",
            vec![vec![square(0.0, 0.0, 1.0, 1.0)]],
        );
        let b = division(
            3,
            AdminLevel::County,
            "Three",
            vec![vec![square(0.0, 0.0, 1.0, 1.0)]],
        );
        assert_eq!(
            index(vec![a, b]).resolve(0.5, 0.5).county.as_deref(),
            Some("Three")
        );
    }

    #[test]
    fn a_dependency_fills_country_only_when_no_country_contains_the_point() {
        let mut us = division(
            1,
            AdminLevel::Country,
            "United States",
            vec![vec![square(-125.0, 24.0, -66.0, 49.0)]],
        );
        us.country_code = Some("US".into());
        let mut pr = division(
            2,
            AdminLevel::Dependency,
            "Puerto Rico",
            vec![vec![square(-67.3, 17.9, -65.6, 18.6)]],
        );
        pr.country_code = Some("PR".into());
        let mut inside_us = division(
            3,
            AdminLevel::Dependency,
            "Overlap",
            vec![vec![square(-100.0, 30.0, -99.0, 31.0)]],
        );
        inside_us.country_code = Some("XX".into());
        let idx = index(vec![us, pr, inside_us]);

        let h = idx.resolve(-66.1, 18.4);
        assert_eq!(
            (h.country.as_deref(), h.country_code.as_deref()),
            (Some("Puerto Rico"), Some("PR"))
        );
        let h = idx.resolve(-99.5, 30.5);
        assert_eq!(
            (h.country.as_deref(), h.country_code.as_deref()),
            (Some("United States"), Some("US"))
        );
    }

    #[test]
    fn a_point_outside_every_country_takes_the_country_of_its_region() {
        // Gateway of India, at 72.8346 E 18.9220 N: the Maharashtra polygon
        // holds the point, the land polygon of India ends just east of it.
        let mut india = division(
            1,
            AdminLevel::Country,
            "India",
            vec![vec![square(72.9, 8.0, 97.5, 37.2)]],
        );
        india.country_code = Some("IN".into());
        let mut maharashtra = division(
            2,
            AdminLevel::Region,
            "Maharashtra",
            vec![vec![square(72.6, 15.6, 80.9, 22.1)]],
        );
        maharashtra.country_code = Some("IN".into());
        let h = index(vec![india, maharashtra]).resolve(72.8346, 18.9220);
        assert_eq!(
            (
                h.country.as_deref(),
                h.country_code.as_deref(),
                h.region.as_deref()
            ),
            (Some("India"), Some("IN"), Some("Maharashtra"))
        );
    }

    #[test]
    fn a_region_whose_country_is_not_loaded_gives_the_code_alone() {
        let mut maharashtra = division(
            2,
            AdminLevel::Region,
            "Maharashtra",
            vec![vec![square(72.6, 15.6, 80.9, 22.1)]],
        );
        maharashtra.country_code = Some("IN".into());
        let h = index(vec![maharashtra]).resolve(72.8346, 18.9220);
        assert_eq!(
            (h.country.as_deref(), h.country_code.as_deref()),
            (None, Some("IN"))
        );
    }

    #[test]
    fn the_country_name_for_a_region_code_prefers_the_country_to_a_dependency() {
        // A dependency that shares the code is loaded first; the country's
        // name still wins, whatever the load order.
        let mut dependency = division(
            1,
            AdminLevel::Dependency,
            "Island Territory",
            vec![vec![square(92.0, 6.0, 94.0, 14.0)]],
        );
        dependency.country_code = Some("IN".into());
        let mut india = division(
            2,
            AdminLevel::Country,
            "India",
            vec![vec![square(72.9, 8.0, 91.0, 37.2)]],
        );
        india.country_code = Some("IN".into());
        let mut maharashtra = division(
            3,
            AdminLevel::Region,
            "Maharashtra",
            vec![vec![square(72.6, 15.6, 80.9, 22.1)]],
        );
        maharashtra.country_code = Some("IN".into());
        let h = index(vec![dependency, india, maharashtra]).resolve(72.8346, 18.9220);
        assert_eq!(h.country.as_deref(), Some("India"));
    }

    #[test]
    fn all_levels_resolve_together() {
        let idx = index(vec![
            division(
                1,
                AdminLevel::Country,
                "France",
                vec![vec![square(-5.0, 42.0, 8.0, 51.0)]],
            ),
            division(
                2,
                AdminLevel::Region,
                "ÃŽle-de-France",
                vec![vec![square(1.4, 48.1, 3.6, 49.3)]],
            ),
            division(
                3,
                AdminLevel::County,
                "Paris",
                vec![vec![square(2.2, 48.8, 2.5, 48.9)]],
            ),
            division(
                4,
                AdminLevel::Locality,
                "Paris",
                vec![vec![square(2.2, 48.8, 2.5, 48.9)]],
            ),
            division(
                5,
                AdminLevel::Neighbourhood,
                "Le Marais",
                vec![vec![square(2.35, 48.85, 2.37, 48.87)]],
            ),
        ]);
        let h = idx.resolve(2.36, 48.86);
        assert_eq!(h.country.as_deref(), Some("France"));
        assert_eq!(h.region.as_deref(), Some("ÃŽle-de-France"));
        assert_eq!(h.county.as_deref(), Some("Paris"));
        assert_eq!(h.locality.as_deref(), Some("Paris"));
        assert_eq!(h.neighbourhood.as_deref(), Some("Le Marais"));
    }

    #[test]
    fn degenerate_rings_are_skipped() {
        let idx = index(vec![division(
            1,
            AdminLevel::Region,
            "Line",
            vec![vec![vec![[0.0, 0.0], [1.0, 1.0]]]],
        )]);
        assert!(idx.is_empty());
    }

    fn division_feature(props: &[(&str, &str)], geometry: geo::Geometry<f64>) -> InputFeature {
        InputFeature {
            id: 11,
            geometry: std::sync::Arc::new(geometry),
            properties: props
                .iter()
                .map(|(k, v)| {
                    (
                        k.to_string(),
                        crate::tile::feature::PropValue::Str(v.to_string()),
                    )
                })
                .collect(),
            bbox: None,
            source: crate::source::input::DataSource::Overture {
                theme: "divisions".into(),
                otype: "division_area".into(),
            },
        }
    }

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

    const LAND_REGION: [(&str, &str); 4] = [
        ("class", "land"),
        ("subtype", "region"),
        ("names.primary", "Bavaria"),
        ("country", "de"),
    ];

    #[test]
    fn a_land_polygon_becomes_a_division() {
        let f = division_feature(&LAND_REGION, geo::Geometry::Polygon(unit_polygon()));
        let d = division_from_feature(&f).expect("division");
        assert_eq!(
            (d.id, d.level, d.name.as_str()),
            (11, AdminLevel::Region, "Bavaria")
        );
        assert_eq!(d.country_code.as_deref(), Some("DE"));
        assert_eq!(d.parts.len(), 1);
        assert_eq!(d.parts[0][0].len(), 5);
    }

    #[test]
    fn a_multipolygon_keeps_every_part() {
        let mut far = unit_polygon();
        far.exterior_mut(|r| r.0.iter_mut().for_each(|c| c.x += 10.0));
        let mp = geo::MultiPolygon::new(vec![unit_polygon(), far]);
        let d = division_from_feature(&division_feature(
            &LAND_REGION,
            geo::Geometry::MultiPolygon(mp),
        ))
        .expect("division");
        assert_eq!(d.parts.len(), 2);
        assert_eq!(d.parts[1][0][0], [10.0, 0.0]);
    }

    /// Each rejection has its own reason; changing one field of a valid land
    /// region at a time isolates it.
    #[test]
    fn unusable_features_are_rejected() {
        let polygon = || geo::Geometry::Polygon(unit_polygon());
        fn with(
            key: &'static str,
            value: Option<&'static str>,
        ) -> Vec<(&'static str, &'static str)> {
            let mut props: Vec<_> = LAND_REGION
                .iter()
                .copied()
                .filter(|(k, _)| *k != key)
                .collect();
            props.extend(value.map(|v| (key, v)));
            props
        }
        for (reason, props, geometry) in [
            ("maritime", with("class", Some("maritime")), polygon()),
            ("no class", with("class", None), polygon()),
            ("empty class", with("class", Some("")), polygon()),
            (
                "unmapped subtype",
                with("subtype", Some("macrohood")),
                polygon(),
            ),
            ("no subtype", with("subtype", None), polygon()),
            ("no name", with("names.primary", None), polygon()),
            (
                "point geometry",
                with("class", Some("land")),
                geo::Geometry::Point(geo::Point::new(0.5, 0.5)),
            ),
        ] {
            assert!(
                division_from_feature(&division_feature(&props, geometry)).is_none(),
                "{reason}"
            );
        }
    }

    /// A ring with zero height (all points on one latitude) encloses nothing.
    #[test]
    fn a_zero_height_ring_contains_nothing() {
        let flat = division(
            1,
            AdminLevel::Locality,
            "Flat",
            vec![vec![vec![[0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]]],
        );
        let idx = index(vec![flat]);
        assert_eq!(idx.len(), 1);
        assert!(idx.resolve(1.0, 1.0).locality.is_none());
    }

    #[test]
    fn a_missing_division_area_directory_loads_an_empty_index() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(
            load_admin_index(tmp.path(), None, None, None)
                .unwrap()
                .is_empty()
        );
    }

    /// A corrupt file must fail the run with its path, not silently leave
    /// every record without admin names.
    #[test]
    fn a_corrupt_division_file_is_an_error_naming_the_file() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("theme=divisions/type=division_area");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("part-0.parquet"), b"not parquet").unwrap();
        let err = load_admin_index(tmp.path(), None, None, None)
            .err()
            .expect("error");
        assert!(format!("{err:#}").contains("part-0.parquet"), "{err:#}");
    }

    #[cfg(unix)]
    #[test]
    fn an_unreadable_division_area_directory_is_an_error() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("theme=divisions/type=division_area");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o000)).unwrap();
        let result = load_admin_index(tmp.path(), None, None, None);
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
        assert!(result.is_err());
    }

    #[test]
    fn subtypes_map_to_levels() {
        for (subtype, level) in [
            ("country", Some(AdminLevel::Country)),
            ("dependency", Some(AdminLevel::Dependency)),
            ("region", Some(AdminLevel::Region)),
            ("county", Some(AdminLevel::County)),
            ("locality", Some(AdminLevel::Locality)),
            ("neighborhood", Some(AdminLevel::Neighbourhood)),
            ("localadmin", None),
            ("macrohood", None),
            ("microhood", None),
        ] {
            assert_eq!(
                AdminLevel::from_overture_subtype(subtype),
                level,
                "{subtype}"
            );
        }
    }
}