geolith-cli 0.4.2

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
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
#![allow(clippy::unwrap_used)] // tests and benches may unwrap (AGENTS.md).

//! End-to-end run of the tile pipeline on a tiny fixture source set.
//!
//! Writes one Overture `transportation/segment` Parquet file, an empty
//! Natural Earth database, and one land and one water shapefile, runs
//! [`geolith_cli::run_with_config`], then reads the `PMTiles` archive back with an
//! independent reader written from the `PMTiles` v3 spec and decodes the MVT
//! tiles. Nothing here uses geolith's own archive or directory code, so the
//! assertions check what a map client would actually receive.

use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;

use arrow::array::{
    Array, ArrayRef, BinaryArray, Float32Array, Float64Builder, ListArray, ListBuilder,
    StringArray, StringBuilder, StructArray,
};
use arrow::buffer::OffsetBuffer;
use arrow::datatypes::{DataType, Field, Fields, Schema};
use arrow::record_batch::RecordBatch;
use clap::Parser;
use geolith_cli::tile::mvt::proto;
use parquet::arrow::ArrowWriter;
use prost::Message;

/// One Overture segment row for the fixture.
struct Segment {
    id: &'static str,
    subtype: &'static str,
    class: &'static str,
    line: [(f64, f64); 2],
    /// `(flag, Some((start, end)))` for a partial rule, `None` for whole.
    flags: Vec<(&'static str, Option<(f64, f64)>)>,
}

fn wkb_line(line: &[(f64, f64)]) -> Vec<u8> {
    let mut b = vec![1u8];
    b.extend_from_slice(&2u32.to_le_bytes());
    b.extend_from_slice(&(line.len() as u32).to_le_bytes());
    for (x, y) in line {
        b.extend_from_slice(&x.to_le_bytes());
        b.extend_from_slice(&y.to_le_bytes());
    }
    b
}

/// `road_flags` shaped exactly as in Overture v1.18:
/// `list<struct<values: list<string>, between: list<double>>>`, one rule per flag.
fn road_flags(rows: &[Segment]) -> ListArray {
    let mut values = ListBuilder::new(StringBuilder::new());
    let mut between = ListBuilder::new(Float64Builder::new());
    let mut lengths = Vec::with_capacity(rows.len());
    for row in rows {
        lengths.push(row.flags.len());
        for (flag, range) in &row.flags {
            values.values().append_value(flag);
            values.append(true);
            match range {
                Some((a, b)) => {
                    between.values().append_value(*a);
                    between.values().append_value(*b);
                    between.append(true);
                }
                None => between.append(false),
            }
        }
    }
    let values = values.finish();
    let between = between.finish();
    let fields = Fields::from(vec![
        Field::new("values", values.data_type().clone(), true),
        Field::new("between", between.data_type().clone(), true),
    ]);
    let rules = StructArray::new(
        fields.clone(),
        vec![Arc::new(values) as ArrayRef, Arc::new(between)],
        None,
    );
    ListArray::new(
        Arc::new(Field::new("item", DataType::Struct(fields), true)),
        OffsetBuffer::from_lengths(lengths),
        Arc::new(rules),
        None,
    )
}

fn write_segments(dir: &Path, rows: &[Segment]) {
    write_segment_file(dir, "part-00000.parquet", rows);
}

fn write_segment_file(dir: &Path, file: &str, rows: &[Segment]) {
    let part = dir.join("theme=transportation/type=segment");
    std::fs::create_dir_all(&part).expect("partition dir");

    let bbox_fields = Fields::from(vec![
        Field::new("xmin", DataType::Float32, false),
        Field::new("ymin", DataType::Float32, false),
        Field::new("xmax", DataType::Float32, false),
        Field::new("ymax", DataType::Float32, false),
    ]);
    let coord = |f: fn(f64, f64) -> f64, i: usize| -> Float32Array {
        rows.iter()
            .map(|r| {
                let [(x0, y0), (x1, y1)] = r.line;
                let pair = if i == 0 { (x0, x1) } else { (y0, y1) };
                f(pair.0, pair.1) as f32
            })
            .collect()
    };
    let bbox = StructArray::new(
        bbox_fields.clone(),
        vec![
            Arc::new(coord(f64::min, 0)) as ArrayRef,
            Arc::new(coord(f64::min, 1)),
            Arc::new(coord(f64::max, 0)),
            Arc::new(coord(f64::max, 1)),
        ],
        None,
    );
    let flags = road_flags(rows);
    let wkb: Vec<Vec<u8>> = rows.iter().map(|r| wkb_line(&r.line)).collect();

    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("geometry", DataType::Binary, false),
        Field::new("bbox", DataType::Struct(bbox_fields), false),
        Field::new("subtype", DataType::Utf8, true),
        Field::new("class", DataType::Utf8, true),
        Field::new("road_flags", flags.data_type().clone(), true),
    ]));
    let batch = RecordBatch::try_new(
        schema.clone(),
        vec![
            Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.id))) as ArrayRef,
            Arc::new(BinaryArray::from_iter_values(wkb.iter())),
            Arc::new(bbox),
            Arc::new(StringArray::from_iter_values(
                rows.iter().map(|r| r.subtype),
            )),
            Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.class))),
            Arc::new(flags),
        ],
    )
    .expect("record batch");
    let file = std::fs::File::create(part.join(file)).expect("parquet file");
    let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
    writer.write(&batch).expect("write");
    writer.close().expect("close");
}

/// One square polygon in EPSG:3857 metres, as the OSM land/water shapefiles are.
fn write_square_shapefile(dir: &Path, name: &str, min: f64, max: f64) {
    use shapefile::dbase::{Record, TableWriterBuilder};
    use shapefile::record::polygon::{Polygon, PolygonRing};
    use shapefile::{Point, Writer};

    std::fs::create_dir_all(dir).expect("shapefile dir");
    let mut writer = Writer::from_path(dir.join(format!("{name}.shp")), TableWriterBuilder::new())
        .expect("shapefile writer");
    let ring = vec![
        Point::new(min, min),
        Point::new(min, max),
        Point::new(max, max),
        Point::new(max, min),
        Point::new(min, min),
    ];
    writer
        .write_shape_and_record(
            &Polygon::with_rings(vec![PolygonRing::Outer(ring)]),
            &Record::default(),
        )
        .expect("write polygon");
}

// ─── Independent PMTiles v3 reader (spec: github.com/protomaps/PMTiles/spec/v3) ───

fn read_varint(buf: &[u8], pos: &mut usize) -> u64 {
    let mut value = 0u64;
    let mut shift = 0;
    loop {
        let byte = buf[*pos];
        *pos += 1;
        value |= u64::from(byte & 0x7f) << shift;
        if byte & 0x80 == 0 {
            return value;
        }
        shift += 7;
    }
}

fn decompress(bytes: &[u8], compression: u8) -> Vec<u8> {
    match compression {
        1 => bytes.to_vec(),
        2 => {
            let mut out = Vec::new();
            flate2::read::GzDecoder::new(bytes)
                .read_to_end(&mut out)
                .expect("gzip");
            out
        }
        other => panic!("unexpected PMTiles compression {other}"),
    }
}

fn u64_at(buf: &[u8], at: usize) -> u64 {
    u64::from_le_bytes(buf[at..at + 8].try_into().expect("8 bytes"))
}

/// Every tile payload in the archive, keyed by tile id.
fn read_all_tiles(archive: &[u8]) -> HashMap<u64, Vec<u8>> {
    assert_eq!(&archive[..7], b"PMTiles");
    assert_eq!(archive[7], 3);
    let (root_off, root_len) = (u64_at(archive, 8), u64_at(archive, 16));
    let leaf_off = u64_at(archive, 40);
    let data_off = u64_at(archive, 56);
    let (internal, tile_comp) = (archive[97], archive[98]);

    let mut tiles = HashMap::new();
    let mut stack = vec![(root_off, root_len)];
    while let Some((off, len)) = stack.pop() {
        let dir = decompress(&archive[off as usize..(off + len) as usize], internal);
        let mut p = 0;
        let n = read_varint(&dir, &mut p) as usize;
        let mut ids = Vec::with_capacity(n);
        let mut last = 0;
        for _ in 0..n {
            last += read_varint(&dir, &mut p);
            ids.push(last);
        }
        let runs: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
        let lens: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
        let mut offs = Vec::with_capacity(n);
        for i in 0..n {
            let raw = read_varint(&dir, &mut p);
            offs.push(if raw == 0 && i > 0 {
                offs[i - 1] + lens[i - 1]
            } else {
                raw - 1
            });
        }
        for i in 0..n {
            if runs[i] == 0 {
                stack.push((leaf_off + offs[i], lens[i]));
                continue;
            }
            let start = (data_off + offs[i]) as usize;
            let payload = decompress(&archive[start..start + lens[i] as usize], tile_comp);
            for k in 0..runs[i] {
                tiles.insert(ids[i] + k, payload.clone());
            }
        }
    }
    tiles
}

/// Zoom of a `PMTiles` tile id: ids start at sum(4^i for i < z).
fn zoom_of(tile_id: u64) -> u8 {
    let (mut z, mut base) = (0u8, 0u64);
    while tile_id >= base + 4u64.pow(u32::from(z)) {
        base += 4u64.pow(u32::from(z));
        z += 1;
    }
    z
}

/// A decoded road: zoom, kind, `kind_detail`, `is_bridge`, ref, and the primary
/// shield's network and text.
#[derive(Debug)]
struct Road {
    zoom: u8,
    kind: String,
    detail: Option<String>,
    bridge: bool,
    reference: Option<String>,
    network: Option<String>,
    shield: Option<String>,
}

fn roads_in(tiles: &HashMap<u64, Vec<u8>>) -> Vec<Road> {
    let mut out = Vec::new();
    for (&id, bytes) in tiles {
        let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
        for layer in tile.layers.iter().filter(|l| l.name == "roads") {
            for f in &layer.features {
                let mut props: HashMap<&str, &proto::tile::Value> = HashMap::new();
                for pair in f.tags.chunks(2) {
                    props.insert(
                        layer.keys[pair[0] as usize].as_str(),
                        &layer.values[pair[1] as usize],
                    );
                }
                let text = |k: &str| props.get(k).and_then(|v| v.string_value.clone());
                out.push(Road {
                    zoom: zoom_of(id),
                    kind: text("kind").unwrap_or_default(),
                    detail: text("kind_detail"),
                    bridge: props.get("is_bridge").and_then(|v| v.bool_value) == Some(true),
                    reference: text("ref"),
                    network: text("network"),
                    shield: text("shield_text"),
                });
            }
        }
    }
    out
}

/// Build a tiny archive around London at z0-z12 and return its roads.
fn build(rows: &[Segment]) -> Vec<Road> {
    build_with(rows, "overture", "-0.3,51.4,0.3,51.6", None)
}

/// Build a tiny archive at z0-z12 with roads from `source` in `bbox`, with
/// an OSM file if one is given, and return its roads.
fn build_with(rows: &[Segment], source: &str, bbox: &str, osm_pbf: Option<&Path>) -> Vec<Road> {
    // One fixture lies in Pune: a build over India needs the Survey of India
    // lines (a made-up ring around Pune here).
    let india =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pune-soi-boundary.geojson");
    let mut extra = vec![
        "--roads-source".to_string(),
        source.into(),
        "--india-boundary".into(),
        india.to_string_lossy().into_owned(),
    ];
    if let Some(pbf) = osm_pbf {
        extra.extend(["--osm-pbf".into(), pbf.to_string_lossy().into_owned()]);
    }
    roads_in(&read_all_tiles(&run_fixture(rows, bbox, 12, &extra)))
}

/// Run the pipeline on `rows` in `bbox` up to `max_zoom`, with `extra`
/// flags, and return the `PMTiles` bytes. The land square spans ±40 km
/// around (0, 0), about ±0.36 degrees.
fn run_fixture(rows: &[Segment], bbox: &str, max_zoom: u8, extra: &[String]) -> Vec<u8> {
    run_fixture_on(rows, bbox, max_zoom, extra, None)
}

/// [`run_fixture`] on a rayon pool of `threads` threads, or the global pool.
fn run_fixture_on(
    rows: &[Segment],
    bbox: &str,
    max_zoom: u8,
    extra: &[String],
    threads: Option<usize>,
) -> Vec<u8> {
    run_fixture_with(rows, bbox, max_zoom, extra, threads, &|_| {})
}

/// [`run_fixture_on`] after `more_sources` has written more files into the
/// Overture directory it is given.
fn run_fixture_with(
    rows: &[Segment],
    bbox: &str,
    max_zoom: u8,
    extra: &[String],
    threads: Option<usize>,
    more_sources: &dyn Fn(&Path),
) -> Vec<u8> {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    write_segments(&root.join("overture"), rows);
    more_sources(&root.join("overture"));
    rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
    write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
    write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
    let out = root.join("out.pmtiles");

    let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
    let mut args = vec![
        "geolith".to_string(),
        "--data".into(),
        arg("overture"),
        "--natural-earth".into(),
        arg("ne.sqlite"),
        "--land-polygons".into(),
        arg("land"),
        "--water-polygons".into(),
        arg("water"),
        "--output".into(),
        out.to_string_lossy().into_owned(),
        "--tmpdir".into(),
        arg("tmp"),
        // The node store goes to the temporary directory, not next to an
        // OSM fixture.
        "--node-store".into(),
        arg("nodes.bin"),
        "--no-conflate".into(),
        "--bbox".into(),
        bbox.into(),
        "--max-zoom".into(),
        max_zoom.to_string(),
    ];
    args.extend_from_slice(extra);
    let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");

    match threads {
        Some(n) => rayon::ThreadPoolBuilder::new()
            .num_threads(n)
            .build()
            .expect("thread pool")
            .install(|| geolith_cli::run_with_config(&config)),
        None => geolith_cli::run_with_config(&config),
    }
    .expect("pipeline runs");
    std::fs::read(&out).expect("archive")
}

/// One motorway segment with the Overture `names` column: `primary` and the
/// string map `common`, as the geocoding and tile readers see it.
fn write_named_segment(dir: &Path, primary: &str, common: &[(&str, &str)]) {
    use arrow::array::MapBuilder;
    let part = dir.join("theme=transportation/type=segment");
    std::fs::create_dir_all(&part).expect("partition dir");
    let line = [(-0.05, 51.5), (-0.04, 51.5)];
    let bbox_fields = Fields::from(vec![
        Field::new("xmin", DataType::Float32, false),
        Field::new("ymin", DataType::Float32, false),
        Field::new("xmax", DataType::Float32, false),
        Field::new("ymax", DataType::Float32, false),
    ]);
    let one = |v: f32| Arc::new(Float32Array::from(vec![v])) as ArrayRef;
    let bbox = StructArray::new(
        bbox_fields.clone(),
        vec![one(-0.05), one(51.5), one(-0.04), one(51.5)],
        None,
    );
    let mut map = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new());
    for (lang, name) in common {
        map.keys().append_value(lang);
        map.values().append_value(name);
    }
    map.append(true).expect("map row");
    let common_array = map.finish();
    let primary_array = StringArray::from(vec![primary]);
    let names_fields = Fields::from(vec![
        Field::new("primary", DataType::Utf8, true),
        Field::new("common", common_array.data_type().clone(), true),
    ]);
    let names = StructArray::new(
        names_fields.clone(),
        vec![Arc::new(primary_array) as ArrayRef, Arc::new(common_array)],
        None,
    );
    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("geometry", DataType::Binary, false),
        Field::new("bbox", DataType::Struct(bbox_fields), false),
        Field::new("subtype", DataType::Utf8, true),
        Field::new("class", DataType::Utf8, true),
        Field::new("names", DataType::Struct(names_fields), true),
    ]));
    let wkb = wkb_line(&line);
    let batch = RecordBatch::try_new(
        schema.clone(),
        vec![
            Arc::new(StringArray::from(vec!["named"])) as ArrayRef,
            Arc::new(BinaryArray::from_iter_values([wkb.as_slice()])),
            Arc::new(bbox),
            Arc::new(StringArray::from(vec!["road"])),
            Arc::new(StringArray::from(vec!["motorway"])),
            Arc::new(names),
        ],
    )
    .expect("record batch");
    let file = std::fs::File::create(part.join("part-named.parquet")).expect("parquet file");
    let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
    writer.write(&batch).expect("write");
    writer.close().expect("close");
}

/// The string attributes of every `roads` feature in the archive.
fn road_attributes(tiles: &HashMap<u64, Vec<u8>>) -> Vec<HashMap<String, String>> {
    let mut out = Vec::new();
    for bytes in tiles.values() {
        let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
        for layer in tile.layers.iter().filter(|l| l.name == "roads") {
            for f in &layer.features {
                out.push(
                    f.tags
                        .chunks(2)
                        .filter_map(|pair| {
                            let value = layer.values[pair[1] as usize].string_value.clone()?;
                            Some((layer.keys[pair[0] as usize].clone(), value))
                        })
                        .collect(),
                );
            }
        }
    }
    out
}

/// A road named in Arabic with an English name in Overture `names.common`
/// reaches the archive as `name`, `script` and `name:en`, which is what
/// `get_multiline_name` of `@protomaps/basemaps` reads for `lang: 'en'`.
/// Languages outside the protomaps list are not written.
#[test]
fn an_overture_road_carries_its_script_and_language_names() {
    let named = |dir: &Path| {
        write_named_segment(
            dir,
            "شارع الملك",
            &[
                ("en", "King Street"),
                ("ar", "شارع الملك"),
                ("pnb", "outside the protomaps list"),
            ],
        );
    };
    let archive = run_fixture_with(
        &[],
        "-0.06,51.49,-0.02,51.51",
        12,
        &["--roads-source".to_string(), "overture".into()],
        None,
        &named,
    );
    let roads = road_attributes(&read_all_tiles(&archive));
    let road = roads
        .iter()
        .find(|r| r.get("kind").map(String::as_str) == Some("highway"))
        .expect("the named motorway is in the archive");
    let attr = |k: &str| road.get(k).map(String::as_str);
    assert_eq!(attr("name"), Some("شارع الملك"));
    assert_eq!(attr("script"), Some("Arabic"));
    assert_eq!(attr("name:en"), Some("King Street"));
    assert_eq!(attr("name:ar"), Some("شارع الملك"));
    assert_eq!(attr("name:pnb"), None);
}

/// Feature count per layer name in the one tile at `zoom`.
fn layer_counts_at(tiles: &HashMap<u64, Vec<u8>>, zoom: u8) -> HashMap<String, usize> {
    let at_zoom: Vec<&Vec<u8>> = tiles
        .iter()
        .filter(|(id, _)| zoom_of(**id) == zoom)
        .map(|(_, bytes)| bytes)
        .collect();
    assert_eq!(at_zoom.len(), 1, "expected one tile at z{zoom}");
    let tile = proto::Tile::decode(at_zoom[0].as_slice()).expect("valid MVT");
    tile.layers
        .iter()
        .map(|l| (l.name.clone(), l.features.len()))
        .collect()
}

/// The land square covers the whole bbox, so every tile in it has earth.
/// Across ±0.3 degrees, z14 tile x runs from floor(179.7 / 360 * 16384) =
/// 8178 to floor(180.3 / 360 * 16384) = 8205, 28 columns, and the Mercator
/// rows at the equator match: 784 tiles, more than one 512-tile encode
/// batch, so batches are flushed while the merge is still reading.
#[test]
fn a_build_larger_than_one_encode_batch_writes_every_tile() {
    for format in ["mvt", "mlt"] {
        let args = ["--tile-format".to_string(), format.into()];
        let tiles = read_all_tiles(&run_fixture(&[], "-0.3,-0.3,0.3,0.3", 14, &args));
        let z14 = tiles.keys().filter(|id| zoom_of(**id) == 14).count();
        assert_eq!(z14, 28 * 28, "{format}");
    }
}

/// A `--bbox` build records that bbox in the archive header, so a `TileJSON`
/// built from the header frames the region instead of the whole world. The
/// `PMTiles` v3 spec stores the bounds as little-endian i32 degrees x 1e7 at
/// bytes 102 to 117 (min lon, min lat, max lon, max lat).
#[test]
fn a_bbox_build_records_the_bbox_in_the_header() {
    let archive = run_fixture(&touching_motorways(), "-0.06,51.49,-0.02,51.51", 12, &[]);
    let e7 = |at: usize| i32::from_le_bytes(archive[at..at + 4].try_into().expect("four bytes"));
    assert_eq!(
        [e7(102), e7(106), e7(110), e7(114)],
        [-600_000, 514_900_000, -200_000, 515_100_000]
    );
}

/// Two motorways end to end, from -0.05 to -0.04 to -0.03 degrees at
/// latitude 51.5: both inside z12 tile x 2047, as (lon + 180) / 360 * 4096
/// is 2047.43 at one end and 2047.66 at the other.
fn touching_motorways() -> Vec<Segment> {
    [
        ("west", [(-0.05, 51.5), (-0.04, 51.5)]),
        ("east", [(-0.04, 51.5), (-0.03, 51.5)]),
    ]
    .into_iter()
    .map(|(id, line)| Segment {
        id,
        subtype: "road",
        class: "motorway",
        line,
        flags: Vec::new(),
    })
    .collect()
}

/// Same-attribute roads in a tile merge into one feature, as the protomaps
/// basemap's `postProcess` merges them.
#[test]
fn same_attribute_roads_merge_into_one_tile_feature() {
    let bbox = "-0.06,51.49,-0.02,51.51";
    let tiles = read_all_tiles(&run_fixture(&touching_motorways(), bbox, 12, &[]));
    assert_eq!(layer_counts_at(&tiles, 12).get("roads"), Some(&1));
}

/// `relations.osm` has two primary roads in Pune, ways 10 and 11, with no
/// `ref` tag of their own. Both are members of bus route relation 100,
/// which has `ref=42`: a bus line is not a road route, so the roads get
/// neither a ref nor a shield from it (protomaps keeps only `route=road`).
#[test]
fn a_bus_route_gives_an_osm_road_no_ref_or_shield() {
    let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relations.osm.pbf");
    let roads = build_with(&[], "osm", "73.8,18.5,73.9,18.6", Some(&pbf));
    let primary: Vec<&Road> = roads
        .iter()
        .filter(|r| r.detail.as_deref() == Some("primary"))
        .collect();
    assert!(!primary.is_empty(), "no primary road: {roads:?}");
    assert!(
        primary
            .iter()
            .all(|r| r.reference.is_none() && r.network.is_none() && r.shield.is_none()),
        "{primary:?}"
    );
}

/// `berlin-a115.osm.pbf` is cut from the Geofabrik Berlin extract of
/// 2026-10 with `osmium getid`: motorway way 81631742 (the AVUS,
/// `ref=A 115`, `int_ref=E 51`) with its nodes, and six of the route
/// relations it belongs to: 80053 (`route=road`, `network=e-road`,
/// `ref=E 51`), 5485765 (`route=road`, `network=BAB`, `ref=A 115`), 1516377
/// (`route=road`, no network or ref), 3046906 (Flixbus bus `009`), 9581031
/// (Eurolines bus `EU0328`) and 3144678 (Flixbus `038`, `disused:route=bus`).
/// On every zoom and thread count the primary shield is the Autobahn
/// number, never the E-road (the lowest relation id) or a coach line.
#[test]
fn the_avus_shield_is_its_autobahn_number_on_any_thread_count() {
    let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/berlin-a115.osm.pbf");
    let extra = [
        "--roads-source".to_string(),
        "osm".into(),
        "--osm-pbf".into(),
        pbf.to_string_lossy().into_owned(),
    ];
    let bbox = "13.19,52.40,13.20,52.42";
    let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
    let roads = roads_in(&read_all_tiles(&serial));
    assert!(!roads.is_empty(), "no roads");
    assert!(
        roads.iter().all(|r| r.reference.as_deref() == Some("A 115")
            && r.network.as_deref() == Some("BAB")
            && r.shield.as_deref() == Some("A115")),
        "{roads:?}"
    );
    for threads in [2, 4, 8] {
        let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
        assert!(
            parallel == serial,
            "{threads} threads: archive bytes differ"
        );
    }
}

/// `route-relations-many-blobs.osm.pbf`: two touching motorway ways in
/// London, both members of road routes 1 (`A 1`, `BAB`), 10001 (`E 51`,
/// `e-road`) and 20001 (`039`, `Flixbus`), which osmium wrote into three
/// different blobs. Built from a generated `.osm` (3 nodes, ways 10 and 11,
/// the three routes, and `type=site` relations 2..=20000 between them,
/// each with node 1 as its one member so a `--bbox` extract keeps them)
/// with `osmium cat`.
///
/// The primary shield is the `BAB` route on every run and thread count,
/// and the two pieces, with one set of attributes, merge into one feature.
#[test]
fn osm_route_attributes_and_merged_roads_are_identical_on_any_thread_count() {
    let pbf = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/route-relations-many-blobs.osm.pbf");
    let extra = [
        "--roads-source".to_string(),
        "osm".into(),
        "--osm-pbf".into(),
        pbf.to_string_lossy().into_owned(),
    ];
    let bbox = "-0.06,51.49,-0.02,51.51";
    let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
    let tiles = read_all_tiles(&serial);
    let roads = roads_in(&tiles);
    assert!(
        !roads.is_empty()
            && roads
                .iter()
                .all(|r| r.shield.as_deref() == Some("A1") && r.network.as_deref() == Some("BAB")),
        "{roads:?}"
    );
    assert_eq!(
        layer_counts_at(&tiles, 12).get("roads"),
        Some(&1),
        "the two ways merge"
    );
    for (run, threads) in [8, 4, 8, 2, 8].into_iter().enumerate() {
        let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
        assert!(
            parallel == serial,
            "run {run} on {threads} threads: archive bytes differ: {:?}",
            roads_in(&read_all_tiles(&parallel))
        );
    }
}

/// A motorway with a bridge on its middle 20%-50%: at every zoom the road
/// is drawn, and at z12 it is split into bridge and non-bridge pieces.
#[test]
fn partially_bridged_overture_road_is_split_in_the_archive() {
    let roads = build(&[Segment {
        id: "road",
        subtype: "road",
        class: "motorway",
        line: [(-0.2, 51.5), (0.2, 51.5)],
        flags: vec![("is_bridge", Some((0.2, 0.5)))],
    }]);

    let z12: Vec<_> = roads.iter().filter(|r| r.zoom == 12).collect();
    assert!(z12.iter().all(|r| r.kind == "highway"), "{z12:?}");
    assert!(z12.iter().any(|r| r.bridge), "no bridge piece: {z12:?}");
    assert!(
        z12.iter().any(|r| !r.bridge),
        "whole road marked bridge: {z12:?}"
    );
    // Motorways start at z3.
    assert!(roads.iter().any(|r| r.zoom == 3 && r.kind == "highway"));
    assert!(!roads.iter().any(|r| r.zoom < 3));
}

/// Standard-gauge rail reaches the archive as `kind = rail` from z11, with a
/// whole-segment bridge flag, and never as a road class.
#[test]
fn overture_rail_is_rail_in_the_archive() {
    let roads = build(&[Segment {
        id: "rail",
        subtype: "rail",
        class: "standard_gauge",
        line: [(-0.2, 51.45), (0.2, 51.55)],
        flags: vec![("is_bridge", None)],
    }]);

    assert!(!roads.is_empty());
    assert!(
        roads.iter().all(|r| r.kind == "rail" && r.zoom >= 11),
        "{roads:?}"
    );
    assert!(
        roads
            .iter()
            .all(|r| r.detail.as_deref() == Some("standard_gauge") && r.bridge),
        "{roads:?}"
    );
    assert!(roads.iter().any(|r| r.zoom == 11));
}

/// Build the London fixture from several Overture Parquet files on a rayon
/// pool of `threads` threads and return the raw `PMTiles` bytes.
fn build_archive(files: &[Vec<Segment>], threads: usize) -> Vec<u8> {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    for (i, rows) in files.iter().enumerate() {
        write_segment_file(
            &root.join("overture"),
            &format!("part-{i:05}.parquet"),
            rows,
        );
    }
    rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
    write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
    write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
    let out = root.join("out.pmtiles");

    let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
    let args = vec![
        "geolith".to_string(),
        "--data".into(),
        arg("overture"),
        "--natural-earth".into(),
        arg("ne.sqlite"),
        "--land-polygons".into(),
        arg("land"),
        "--water-polygons".into(),
        arg("water"),
        "--output".into(),
        out.to_string_lossy().into_owned(),
        "--tmpdir".into(),
        arg("tmp"),
        "--roads-source".into(),
        "overture".into(),
        "--no-conflate".into(),
        "--bbox".into(),
        "-0.3,51.4,0.3,51.6".into(),
        "--max-zoom".into(),
        "10".into(),
    ];
    let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
    rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build()
        .expect("thread pool")
        .install(|| geolith_cli::run_with_config(&config))
        .expect("pipeline runs");
    std::fs::read(&out).expect("archive")
}

/// Motorways that share tiles, layer and sort rank but live in different
/// Parquet files, so their features tie on the sort key and reach the merge
/// from different chunks. The first file is much larger than the rest, so
/// on a parallel pool it finishes last while on one thread it finishes
/// first.
fn tied_motorway_files() -> Vec<Vec<Segment>> {
    let motorway = |file: usize, k: usize| {
        let y = 51.45 + 0.1 * (file * 64 + k) as f64 / 1024.0;
        Segment {
            id: Box::leak(format!("motorway-{file}-{k}").into_boxed_str()),
            subtype: "road",
            class: "motorway",
            line: [(-0.25, y), (0.25, y + 0.001)],
            flags: Vec::new(),
        }
    };
    (0..8)
        .map(|file| {
            let rows = if file == 0 { 2_000 } else { 1 };
            (0..rows).map(|k| motorway(file, k)).collect()
        })
        .collect()
}

/// The same input gives the same archive bytes on every run and on any
/// number of threads: feature order inside a tile must not depend on which
/// worker finished first.
#[test]
fn tile_archive_is_byte_identical_across_runs_and_thread_counts() {
    let files = tied_motorway_files();
    let serial = build_archive(&files, 1);
    let tiles = read_all_tiles(&serial);
    assert!(
        !roads_in(&tiles).is_empty(),
        "fixture produced no roads to order"
    );
    for (run, threads) in [4, 8, 4, 8].into_iter().enumerate() {
        let parallel = build_archive(&files, threads);
        let other = read_all_tiles(&parallel);
        let differing = tiles
            .iter()
            .filter(|(id, bytes)| other.get(id) != Some(bytes))
            .count();
        assert_eq!(
            differing,
            0,
            "run {run} on {threads} threads: {differing} of {} tiles differ",
            tiles.len()
        );
        assert!(
            parallel == serial,
            "run {run} on {threads} threads: archive bytes differ"
        );
    }
}

/// The boundaries layer of a Kashmir build: every feature's properties as
/// text, keyed by name.
fn boundary_features(tiles: &HashMap<u64, Vec<u8>>) -> Vec<HashMap<String, String>> {
    let mut out = Vec::new();
    for bytes in tiles.values() {
        let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
        for layer in tile.layers.iter().filter(|l| l.name == "boundaries") {
            for f in &layer.features {
                let mut props = HashMap::new();
                for pair in f.tags.chunks(2) {
                    let value = &layer.values[pair[1] as usize];
                    let text = value
                        .string_value
                        .clone()
                        .or_else(|| value.bool_value.map(|b| b.to_string()))
                        .or_else(|| value.int_value.map(|i| i.to_string()))
                        .or_else(|| value.uint_value.map(|i| i.to_string()))
                        .or_else(|| value.sint_value.map(|i| i.to_string()))
                        .unwrap_or_default();
                    props.insert(layer.keys[pair[0] as usize].clone(), text);
                }
                out.push(props);
            }
        }
    }
    out
}

/// Run a Kashmir tile build (`tests/fixtures/kashmir-boundaries.osm.pbf`:
/// five OSM boundary lines) with or without the Survey of India lines.
fn kashmir_build(
    bbox: &str,
    india_boundary: bool,
) -> Result<HashMap<u64, Vec<u8>>, geolith_cli::CliError> {
    kashmir_build_with(
        bbox,
        india_boundary.then_some("kashmir-soi-boundary.geojson"),
    )
}

/// [`kashmir_build`] with the named file of `tests/fixtures` as
/// `--india-boundary`.
fn kashmir_build_with(
    bbox: &str,
    india_boundary: Option<&str>,
) -> Result<HashMap<u64, Vec<u8>>, geolith_cli::CliError> {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
    let overture = root.join("overture");
    std::fs::create_dir_all(&overture).expect("overture dir");
    rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
    write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
    write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
    let out = root.join("out.pmtiles");
    let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
    let mut args: Vec<String> = [
        "geolith",
        "--data",
        &arg("overture"),
        "--natural-earth",
        &arg("ne.sqlite"),
        "--land-polygons",
        &arg("land"),
        "--water-polygons",
        &arg("water"),
        "--output",
        &out.to_string_lossy(),
        "--tmpdir",
        &arg("tmp"),
        "--node-store",
        &arg("nodes.bin"),
        "--no-conflate",
        "--osm-pbf",
        &fixtures
            .join("kashmir-boundaries.osm.pbf")
            .to_string_lossy(),
        "--bbox",
        bbox,
        "--max-zoom",
        "8",
    ]
    .map(String::from)
    .to_vec();
    if let Some(file) = india_boundary {
        args.push("--india-boundary".into());
        args.push(fixtures.join(file).to_string_lossy().into_owned());
    }
    let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
    geolith_cli::run_with_config(&config)?;
    Ok(read_all_tiles(&std::fs::read(&out).expect("archive")))
}

/// `--india-boundary` takes the lines file `derive.py` writes and DataMeet's
/// polygon file itself, and both give the same tiles. The polygon file used to
/// be read as it came: its polygons went into the boundaries layer as areas,
/// not as the Survey of India line.
#[test]
fn the_polygon_file_and_the_derived_lines_file_give_the_same_tiles() {
    let bbox = "72.5,30.5,80.5,37.5";
    let lines = kashmir_build_with(bbox, Some("kashmir-soi-derived-shape.geojson")).expect("lines");
    let polygons =
        kashmir_build_with(bbox, Some("kashmir-soi-datameet-shape.geojson")).expect("polygons");
    assert!(!lines.is_empty());
    assert_eq!(lines.len(), polygons.len(), "tile count");
    for (id, tile) in &lines {
        assert_eq!(polygons.get(id), Some(tile), "tile {id} differs");
    }
}

/// A file that is not the Survey of India map stops the tile build with a typed
/// error that names it: it used to be read as it came (another country's lines
/// became "India's"), or, empty, as no India at all.
#[test]
fn a_tile_build_refuses_files_that_are_not_the_survey_of_india_map() {
    let dir = tempfile::tempdir().expect("tempdir");
    let germany = dir.path().join("germany.geojson");
    std::fs::write(
        &germany,
        r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[5.8,47.2],[15.1,47.2],[15.1,55.1],[5.8,55.1],[5.8,47.2]]}}]}"#,
    )
    .expect("write");
    let empty = dir.path().join("empty.geojson");
    std::fs::write(&empty, "").expect("write");
    let projected = dir.path().join("projected.geojson");
    std::fs::write(
        &projected,
        r#"{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:3857"}},"features":[{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[8100000,950000],[8500000,950000],[8500000,4400000],[8100000,950000]]}}]}"#,
    )
    .expect("write");
    for (file, expect) in [
        (&germany, "does not reach India"),
        (&empty, "the file is empty"),
        (&projected, "WGS 84"),
    ] {
        let err = kashmir_build_with("72.5,30.5,80.5,37.5", file.to_str())
            .expect_err("the file must be refused");
        let text = geolith::error::report(&err);
        assert!(text.contains(expect), "{expect}: {text}");
        assert!(text.contains(&file.display().to_string()), "{text}");
    }
}

/// A tile build over Kashmir needs the Survey of India lines: the build
/// area touches that land. A build over Berlin does not.
#[test]
fn a_tile_build_on_soi_land_needs_the_boundary_lines() {
    let err = kashmir_build("72.5,30.5,80.5,37.5", false)
        .expect_err("Kashmir without --india-boundary must fail");
    assert!(err.to_string().contains("Survey of India"), "{err}");
}

/// With the Survey of India lines, inside India's land only the lines
/// between Indian divisions stay, without claims: no country line (the line
/// of control), no Pakistani region line, no county line that carries
/// `disputed_by`. A Pakistani line outside the land stays.
#[test]
fn inside_soi_land_only_indian_division_lines_are_drawn() {
    let tiles = kashmir_build("72.5,30.5,80.5,37.5", true).expect("build");
    let features = boundary_features(&tiles);
    let has = |kind: &str, detail: &str| {
        features.iter().any(|p| {
            p.get("kind").map(String::as_str) == Some(kind)
                && p.get("kind_detail").map(String::as_str) == Some(detail)
        })
    };
    assert!(
        has("region", "4"),
        "the Indian region line stays: {features:?}"
    );
    assert!(has("county", "5"), "a Pakistani line outside India stays");
    assert!(has("country", "2"), "the Survey of India line is drawn");
    assert!(!has("region", "3"), "the Pakistani region line goes");
    assert!(!has("county", "6"), "the Indian line with a claim goes");
    assert!(
        features.iter().all(|p| !p.contains_key("disputed")
            && !p.contains_key("disputed_by")
            && !p.contains_key("claimed_by")
            && !p.contains_key("__owner")),
        "no claim and no private mark in a tile: {features:?}"
    );
}

// ─── --reclaim-source-after-read never deletes what it could not use ───

/// A Parquet file with an `id` column and no `geometry` column.
fn write_file_without_geometry(dir: &Path, file: &str) {
    let part = dir.join("theme=transportation/type=segment");
    std::fs::create_dir_all(&part).expect("partition dir");
    let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Utf8, true)]));
    let batch = RecordBatch::try_new(
        schema.clone(),
        vec![Arc::new(StringArray::from(vec![Some("a")]))],
    )
    .expect("batch");
    let out = std::fs::File::create(part.join(file)).expect("create");
    let mut writer = ArrowWriter::try_new(out, schema, None).expect("writer");
    writer.write(&batch).expect("write");
    writer.close().expect("close");
}

/// Run a London build with `--reclaim-source-after-read` over one good road
/// file and whatever `more_sources` adds. Returns the Overture directory
/// (kept alive by the returned guard) and the build's result as text.
fn run_with_reclaim(more_sources: &dyn Fn(&Path)) -> (tempfile::TempDir, Result<(), String>) {
    run_london(
        more_sources,
        &|_| {},
        &["--reclaim-source-after-read", "--allow-missing-type"],
    )
}

/// A data folder with no buildings, no water, no divisions: `discover` said
/// nothing, and the build shipped a planet without them. With
/// `--reclaim-source-after-read` it stops before it deletes the one road file.
#[test]
fn reclaim_stops_on_a_data_folder_that_lacks_a_type_and_keeps_the_files() {
    let (dir, result) = run_london(&|_| {}, &|_| {}, &["--reclaim-source-after-read"]);
    let err = result.expect_err("a type is missing");
    assert!(err.contains("holds no Parquet file of"), "{err}");
    assert!(err.contains("buildings/building"), "{err}");
    assert!(err.contains("--allow-missing-type"), "{err}");
    assert!(
        !err.contains("transportation/segment"),
        "the type that is there is not named: {err}"
    );
    let road = dir
        .path()
        .join("overture/theme=transportation/type=segment/part-00000.parquet");
    assert!(road.exists(), "the source file is kept");
}

/// Without the reclaim flag the same folder builds, with a warning.
#[test]
fn a_data_folder_that_lacks_a_type_still_builds_without_the_reclaim_flag() {
    let (_dir, result) = run_london(&|_| {}, &|_| {}, &[]);
    result.expect("builds");
}

/// A London build over one good road file. `more_sources` adds Overture
/// files, `before` runs on the (not yet existing) `--tmpdir` path's parent
/// directory `root` after the fixtures are written, and `extra` are more
/// flags.
fn run_london(
    more_sources: &dyn Fn(&Path),
    before: &dyn Fn(&Path),
    extra: &[&str],
) -> (tempfile::TempDir, Result<(), String>) {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    let rows = [Segment {
        id: "a",
        subtype: "road",
        class: "motorway",
        line: [(-0.1, 51.5), (0.1, 51.5)],
        flags: vec![],
    }];
    write_segments(&root.join("overture"), &rows);
    more_sources(&root.join("overture"));
    rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
    write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
    write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);

    before(root);

    let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
    let mut args: Vec<String> = vec![
        "geolith".to_string(),
        "--data".into(),
        arg("overture"),
        "--natural-earth".into(),
        arg("ne.sqlite"),
        "--land-polygons".into(),
        arg("land"),
        "--water-polygons".into(),
        arg("water"),
        "--output".into(),
        arg("out.pmtiles"),
        "--tmpdir".into(),
        arg("tmp"),
        "--no-conflate".into(),
        "--roads-source".into(),
        "overture".into(),
        "--bbox".into(),
        "-0.3,51.4,0.3,51.6".into(),
        "--max-zoom".into(),
        "8".into(),
    ];
    args.extend(extra.iter().map(|a| (*a).to_string()));
    let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
    let result = geolith_cli::run_with_config(&config).map_err(|e| geolith_cli::error::report(&e));
    (dir, result)
}

fn segment_dir(dir: &tempfile::TempDir) -> std::path::PathBuf {
    dir.path()
        .join("overture/theme=transportation/type=segment")
}

#[test]
fn a_file_that_gave_features_is_reclaimed() {
    let (dir, result) = run_with_reclaim(&|_| {});
    result.expect("the build succeeds");
    assert!(
        !segment_dir(&dir).join("part-00000.parquet").exists(),
        "a source that was read in full is deleted"
    );
}

#[test]
fn a_file_without_a_geometry_column_stops_the_build_and_is_kept() {
    let (dir, result) = run_with_reclaim(&|overture| {
        write_file_without_geometry(overture, "part-bad.parquet");
    });
    let error = result.expect_err("the build stops");
    assert!(error.contains("part-bad.parquet"), "{error}");
    assert!(error.contains("geometry"), "{error}");
    assert!(
        segment_dir(&dir).join("part-bad.parquet").exists(),
        "a file that could not be read is never deleted"
    );
}

#[test]
fn a_file_that_gave_no_feature_is_kept() {
    let (dir, result) = run_with_reclaim(&|overture| {
        write_segment_file(overture, "part-empty.parquet", &[]);
    });
    result.expect("an empty file is not an error");
    assert!(
        segment_dir(&dir).join("part-empty.parquet").exists(),
        "a file with zero features is kept"
    );
    assert!(
        !segment_dir(&dir).join("part-00000.parquet").exists(),
        "the good file is still reclaimed"
    );
}

#[test]
fn a_build_removes_its_own_sort_files_and_leaves_the_rest_of_tmpdir() {
    let (dir, result) = run_london(
        &|_| {},
        &|root| {
            let tmp = root.join("tmp");
            std::fs::create_dir_all(tmp.join("keep-dir")).expect("dir");
            std::fs::write(tmp.join("keep.txt"), b"not geolith's").expect("write");
            std::fs::write(tmp.join("keep-dir/inner.txt"), b"inner").expect("write");
        },
        &[],
    );
    result.expect("the build succeeds");
    let tmp = dir.path().join("tmp");
    assert_eq!(
        std::fs::read(tmp.join("keep.txt")).expect("kept"),
        b"not geolith's"
    );
    assert!(tmp.join("keep-dir/inner.txt").exists());
    let mut names: Vec<String> = std::fs::read_dir(&tmp)
        .expect("tmpdir is still there")
        .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    assert_eq!(names, ["keep-dir", "keep.txt"], "no sort run, no marker");
}

#[test]
fn a_build_removes_a_tmpdir_it_created_itself() {
    let (dir, result) = run_london(&|_| {}, &|_| {}, &[]);
    result.expect("the build succeeds");
    assert!(!dir.path().join("tmp").exists());
}

// ─── the credit of the data a tile build read ───

/// The `attribution` of the archive's JSON metadata.
fn archive_attribution(archive: &[u8]) -> String {
    let (offset, length) = (u64_at(archive, 24) as usize, u64_at(archive, 32) as usize);
    let json = decompress(&archive[offset..offset + length], archive[97]);
    let metadata: serde_json::Value = serde_json::from_slice(&json).expect("metadata JSON");
    metadata["attribution"]
        .as_str()
        .expect("attribution")
        .to_owned()
}

#[test]
fn a_tile_archive_credits_the_data_the_build_read() {
    let (dir, result) = run_london(&|_| {}, &|_| {}, &[]);
    result.expect("the build succeeds");
    let attribution = archive_attribution(&std::fs::read(dir.path().join("out.pmtiles")).unwrap());
    assert!(
        attribution.contains("&copy; OpenStreetMap contributors (ODbL)</a>, Overture Maps Foundation, Natural Earth (public domain)"),
        "{attribution}"
    );
    assert!(
        !attribution.contains("DataMeet"),
        "no India boundary was read: {attribution}"
    );
    assert!(attribution.ends_with("| © geolith"), "{attribution}");
}

#[test]
fn a_tile_archive_built_with_the_india_boundary_credits_datameet() {
    let boundary = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/kashmir-soi-boundary.geojson")
        .to_string_lossy()
        .into_owned();
    let (dir, result) = run_london(&|_| {}, &|_| {}, &["--india-boundary", &boundary]);
    result.expect("the build succeeds");
    let attribution = archive_attribution(&std::fs::read(dir.path().join("out.pmtiles")).unwrap());
    assert!(
        attribution.contains(
            "Natural Earth (public domain) | India boundary: DataMeet India community (CC BY 4.0) | © geolith"
        ),
        "{attribution}"
    );
}