geolith-dataset-builder 0.4.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! Dataset config: what a raster holds and how to draw it.
//!
//! One JSON file per dataset (for example `packages/dataset-builder/data/datasets/rainfall.json`),
//! parsed with `serde_json`. Unknown keys are an error, so a typo cannot
//! silently drop a field.
//!
//! Notes on `rainfall.json` (JSON has no comments):
//! - `valid_max` 5000 mm is a sanity cap per pentad, above any recorded
//!   5-day rainfall total.
//! - `nodata` -9999 is applied from the config: CHIRPS v3.0 files carry no
//!   nodata tag and hold -9999 on ocean cells.
//! - CHIRPS v3.0 finals are published as `.cog`, prelims as `.tif`, hence
//!   the separate `prelim_file_template`.
//! - The ramp is `ColorBrewer` `YlGnBu`, colour-blind safe, in mm per pentad.
//! - `stale_after_days` 18: a pentad (up to 6 days), the prelim's ~2-day
//!   delay and a weekly batch make a normal worst age of about 15 days.
//!
//! Notes on `ndvi.json` (Copernicus Land Monitoring Service NDVI 300 m v3,
//! 10-daily, from the CDSE STAC collection `clms_ndvi_global_300m_10daily_v3_cog`):
//! - Raw `uint8`, decoded `raw * 0.004 - 0.08`; raw 0..=250 is -0.08..=0.92.
//!   Raw 252 (unknown), 253 (snow) and 254 (water) are `flags`, 255 is
//!   `nodata`; raw 251 decodes to 0.924, above `valid_max`, so it is masked
//!   too.
//! - `max_zoom` 9: the pixel is 1/336° (≈ 0.00298°); a z9 256-px tile pixel
//!   is ≈ 0.00275°.
//! - `stale_after_days` 24: a dekad (up to 11 days), the 3-day timeliness
//!   (`P3D`) and a weekly batch.
//! - `record_start` 2014-01-01: CDSE S3 and the STAC hold the 2014-01-01 and
//!   2014-01-11 dekads, though the collection's temporal extent starts 2014-01-21.
//! - `reader` `windowed`: a global raster is ≈ 1.25 GB, read by windows.
//! - `comparison` `average`: the baseline is the 2019–2025 average, not a
//!   30-year normal; `anomaly_pct_min_normal` null: no percentage anomaly.
//! - `baseline` 2019-2025 and `sensor` Sentinel-3 OLCI: one sensor only.
//!   PROBA-V (2014–2018) reads lower than OLCI by a median 0.034 NDVI per
//!   district and dekad slot, and a mixed baseline flips the sign of 161 of
//!   787 anomalies of 2026-10 dekad 2 (P2 report, `real_baseline`).
//! - `{year}` in the attribution is the latest period's year in a build, the
//!   baseline range in normals ([`DatasetConfig::attribution_for`]).
//! - The ramp is `ColorBrewer` `YlGn` plus a bare-soil brown at -0.08,
//!   colour-blind safe.

use std::path::Path;

use crate::error::{DatasetError, IoStepExt as _, JsonResultExt as _, Result, WithinExt as _};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use geolith::terrain::Crs;

/// Largest map-layer zoom a config may ask for.
const MAX_ZOOM_LIMIT: u8 = 22;

/// A raster dataset, as described by its JSON config.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DatasetConfig {
    /// Stable machine id, e.g. `rainfall`.
    pub id: String,
    /// Display name.
    pub name: String,
    /// Unit of the decoded values, e.g. `mm`.
    pub unit: String,
    /// Length of the period each raster covers.
    pub period: PeriodKind,
    /// Multiplier applied to a raw value.
    pub scale: f64,
    /// Added to a raw value after `scale`.
    pub offset: f64,
    /// Smallest valid decoded value.
    pub valid_min: f64,
    /// Largest valid decoded value.
    pub valid_max: f64,
    /// Raw value that marks a cell without data.
    pub nodata: Option<f64>,
    /// Raw values that also mean "no data" (for example class codes).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub flags: Vec<f64>,
    /// EPSG code of the raster grid, when the files lack geokeys.
    pub crs_epsg: Option<u32>,
    /// File name pattern of one period's raster (the `final/` folder).
    pub file_template: String,
    /// File name pattern in the `prelim/` folder; `file_template` when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prelim_file_template: Option<String>,
    /// Colour ramp of the map layer, in increasing value order.
    pub ramp: Vec<RampStop>,
    /// Highest zoom of the map layer.
    pub max_zoom: u8,
    /// Map-layer tile edge in pixels: 256 or 512.
    pub tile_size: u32,
    /// First day of the season, `MM-DD`.
    pub season_start: Option<String>,
    /// Days after the latest `period_end` until a page is stale.
    pub stale_after_days: u16,
    /// Attribution carried by every output.
    pub attribution: String,
    /// Where the source data is published.
    pub source_url: String,
    /// Licence of the source data.
    pub licence: String,
    /// What a period's value is compared with.
    #[serde(default)]
    pub comparison: Comparison,
    /// Normals below this give no percentage anomaly; `None` (JSON `null`)
    /// never gives one. `Some(1.0)` when the key is absent.
    #[serde(default = "default_anomaly_pct_min_normal")]
    pub anomaly_pct_min_normal: Option<f64>,
    /// First day of the source record, `YYYY-MM-DD`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record_start: Option<String>,
    /// How the rasters are read.
    #[serde(default)]
    pub reader: Reader,
    /// Baseline years `YYYY-YYYY` of the normals a build must compare with;
    /// any baseline when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub baseline: Option<String>,
    /// Sensor of every baseline and series raster, named in the comparison.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sensor: Option<String>,
    /// Class breaks of `series.json` and of the `index.json` class codes;
    /// a build writes neither without them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub classes: Option<Classes>,
    /// Periods with a map layer, the latest included: `tiles.pmtiles`, then
    /// `tiles/<period_end>.pmtiles` for the ones before it. 1 when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layer_periods: Option<u8>,
    /// Highest zoom of the layers before the latest; `max_zoom` when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history_max_zoom: Option<u8>,
}

/// Largest `layer_periods`: the series length of a build.
pub const MAX_LAYER_PERIODS: u8 = 12;

/// Classes of the public time series: a value class and a comparison class
/// per area and period, each the count of breaks at or below the number.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Classes {
    /// Breaks of the value, increasing.
    pub value: Vec<f64>,
    /// Breaks of the comparison number, increasing.
    pub comparison: Vec<f64>,
    /// What the comparison number is.
    pub comparison_kind: ClassComparison,
}

/// The number a comparison class is taken of.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClassComparison {
    /// `value / normal × 100`, not comparable when the normal is below
    /// `anomaly_pct_min_normal` (or there is no threshold).
    PctOfNormal,
    /// `value − normal`.
    AnomalyAbs,
}

/// The P1 percentage threshold: normals below 1 unit give no percentage.
const fn default_anomaly_pct_min_normal() -> Option<f64> {
    Some(1.0)
}

/// What a period's value is compared with.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Comparison {
    /// A climate normal of the slot.
    #[default]
    Normal,
    /// The average of the slot over the baseline years.
    Average,
}

/// How the rasters are read.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Reader {
    /// The whole raster at once.
    #[default]
    Whole,
    /// Windows of the raster, as needed.
    Windowed,
}

/// Length of the period one raster covers.
#[non_exhaustive]
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(rename_all = "lowercase", try_from = "String")]
pub enum PeriodKind {
    /// Six pentads per month: days 1-5, 6-10, 11-15, 16-20, 21-25, 26-end.
    #[default]
    Pentad,
    /// Three dekads per month: days 1-10, 11-20, 21-end.
    Dekad,
}

impl PeriodKind {
    /// The config spelling, e.g. `pentad`.
    pub(crate) const fn name(self) -> &'static str {
        match self {
            Self::Pentad => "pentad",
            Self::Dekad => "dekad",
        }
    }

    /// The file template placeholder, e.g. `{pentad}`.
    const fn token(self) -> &'static str {
        match self {
            Self::Pentad => "{pentad}",
            Self::Dekad => "{dekad}",
        }
    }

    /// Periods in a month: 6 pentads or 3 dekads.
    #[must_use]
    pub const fn periods_per_month(self) -> u8 {
        match self {
            Self::Pentad => 6,
            Self::Dekad => 3,
        }
    }

    /// First day of each period of a month, in order.
    #[must_use]
    pub const fn starts(self) -> &'static [u8] {
        match self {
            Self::Pentad => &[1, 6, 11, 16, 21, 26],
            Self::Dekad => &[1, 11, 21],
        }
    }
}

impl TryFrom<String> for PeriodKind {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.as_str() {
            "pentad" => Ok(Self::Pentad),
            "dekad" => Ok(Self::Dekad),
            other => Err(format!(
                "unknown period {other:?}: expected \"pentad\" or \"dekad\""
            )),
        }
    }
}

/// One stop of the colour ramp.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RampStop {
    /// Decoded value at which `color` applies.
    pub value: f64,
    /// RGBA colour; JSON `#rrggbb` (opaque) or `#rrggbbaa`.
    #[serde(
        serialize_with = "serialize_color",
        deserialize_with = "deserialize_color"
    )]
    pub color: [u8; 4],
}

/// Parse `#rrggbb` (alpha 255) or `#rrggbbaa`.
fn parse_color(text: &str) -> Option<[u8; 4]> {
    let hex = text.strip_prefix('#')?;
    if !(hex.len() == 6 || hex.len() == 8) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let channel = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
    let alpha = if hex.len() == 8 { channel(6)? } else { 255 };
    Some([channel(0)?, channel(2)?, channel(4)?, alpha])
}

fn deserialize_color<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 4], D::Error> {
    let text = String::deserialize(deserializer)?;
    parse_color(&text).ok_or_else(|| {
        serde::de::Error::custom(format!("colour {text:?} is not #rrggbb or #rrggbbaa"))
    })
}

fn serialize_color<S: Serializer>(color: &[u8; 4], serializer: S) -> Result<S::Ok, S::Error> {
    let [r, g, b, a] = *color;
    let text = if a == 255 {
        format!("#{r:02x}{g:02x}{b:02x}")
    } else {
        format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
    };
    serializer.serialize_str(&text)
}

/// Whether `text` is a calendar day `MM-DD` (29 February allowed).
fn is_month_day(text: &str) -> bool {
    let bytes = text.as_bytes();
    if bytes.len() != 5 || bytes[2] != b'-' {
        return false;
    }
    let (Ok(month), Ok(day)) = (text[..2].parse::<u8>(), text[3..].parse::<u8>()) else {
        return false;
    };
    let days = match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => 29,
        _ => return false,
    };
    bytes
        .iter()
        .enumerate()
        .all(|(i, b)| i == 2 || b.is_ascii_digit())
        && (1..=days).contains(&day)
}

/// Whether `text` is a Gregorian date `YYYY-MM-DD`.
fn is_iso_date(text: &str) -> bool {
    let Some((year, month_day)) = text.split_at_checked(4) else {
        return false;
    };
    let Some(month_day) = month_day.strip_prefix('-') else {
        return false;
    };
    let Ok(year) = year.parse::<i32>() else {
        return false;
    };
    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    text.as_bytes()[..4].iter().all(u8::is_ascii_digit)
        && is_month_day(month_day)
        && (leap || month_day != "02-29")
}

impl DatasetConfig {
    /// Read and validate the config at `path`.
    ///
    /// # Errors
    ///
    /// Fails, naming `path`, when the file cannot be read or is not a valid
    /// config.
    pub fn load(path: &Path) -> Result<Self> {
        let text = std::fs::read_to_string(path)
            .io_step(format!("reading dataset config {}", path.display()))?;
        Self::from_json_str(&text).within(format!("invalid dataset config {}", path.display()))
    }

    /// Parse and validate a config from JSON text.
    ///
    /// # Errors
    ///
    /// Fails on malformed JSON, an unknown key, a ramp with fewer than two
    /// stops or values not strictly increasing, `valid_min >= valid_max`,
    /// `max_zoom > 22`, a tile size other than 256 or 512, a `season_start`
    /// that is not `MM-DD` or not the first day of a period, or an
    /// unsupported `crs_epsg`.
    pub fn from_json_str(s: &str) -> Result<Self> {
        let config: Self = serde_json::from_str(s).json_of("parsing dataset config JSON")?;
        config.validate()?;
        Ok(config)
    }

    fn validate(&self) -> Result<()> {
        if self.ramp.len() < 2 {
            return Err(DatasetError::config(format!(
                "ramp needs at least 2 stops, found {}",
                self.ramp.len()
            )));
        }
        if self.ramp.windows(2).any(|w| w[0].value >= w[1].value) {
            return Err(DatasetError::config(
                "ramp values must be strictly increasing",
            ));
        }
        if self.valid_min >= self.valid_max {
            return Err(DatasetError::config(format!(
                "valid_min {} must be below valid_max {}",
                self.valid_min, self.valid_max
            )));
        }
        if self.max_zoom > MAX_ZOOM_LIMIT {
            return Err(DatasetError::config(format!(
                "max_zoom {} is above {MAX_ZOOM_LIMIT}",
                self.max_zoom
            )));
        }
        if !matches!(self.tile_size, 256 | 512) {
            return Err(DatasetError::config(format!(
                "tile_size {} must be 256 or 512",
                self.tile_size
            )));
        }
        if let Some(day) = &self.season_start {
            if !is_month_day(day) {
                return Err(DatasetError::config(format!(
                    "season_start {day:?} is not MM-DD"
                )));
            }
            let starts: Vec<String> = self
                .period
                .starts()
                .iter()
                .map(|d| format!("{d:02}"))
                .collect();
            if !starts.iter().any(|start| day.ends_with(start.as_str())) {
                return Err(DatasetError::config(format!(
                    "season_start {day:?} is not the first day of a {} (days {})",
                    self.period.name(),
                    starts.join(", ")
                )));
            }
        }
        let templates = [
            ("file_template", Some(&self.file_template)),
            ("prelim_file_template", self.prelim_file_template.as_ref()),
        ];
        for (key, template) in templates {
            let Some(template) = template else { continue };
            let own = template.matches(self.period.token()).count();
            let other = [PeriodKind::Pentad, PeriodKind::Dekad]
                .into_iter()
                .filter(|kind| *kind != self.period)
                .map(|kind| template.matches(kind.token()).count())
                .sum::<usize>();
            if own != 1 || other != 0 {
                return Err(DatasetError::config(format!(
                    "{key} {template:?} must hold {} exactly once and no other period \
                     placeholder ({} period)",
                    self.period.token(),
                    self.period.name()
                )));
            }
        }
        if let Some(day) = &self.record_start
            && !is_iso_date(day)
        {
            return Err(DatasetError::config(format!(
                "record_start {day:?} is not a date YYYY-MM-DD"
            )));
        }
        if let Some(years) = &self.baseline {
            let year = |s: &str| s.len() == 4 && s.bytes().all(|b| b.is_ascii_digit());
            match years.split_once('-') {
                Some((first, last)) if year(first) && year(last) && first <= last => {}
                _ => {
                    return Err(DatasetError::config(format!(
                        "baseline {years:?} is not YYYY-YYYY with the first year first"
                    )));
                }
            }
        }
        if self.sensor.as_deref().is_some_and(|s| s.trim().is_empty()) {
            return Err(DatasetError::config("sensor is empty"));
        }
        if let Some(classes) = &self.classes {
            for (name, breaks) in [
                ("classes.value", &classes.value),
                ("classes.comparison", &classes.comparison),
            ] {
                if breaks.is_empty() || breaks.len() > crate::series::MAX_BREAKS {
                    return Err(DatasetError::config(format!(
                        "{name} needs 1 to {} breaks, not {}",
                        crate::series::MAX_BREAKS,
                        breaks.len()
                    )));
                }
                if breaks.iter().any(|b| !b.is_finite()) || breaks.windows(2).any(|w| w[0] >= w[1])
                {
                    return Err(DatasetError::config(format!(
                        "{name} breaks must be finite and increasing: {breaks:?}"
                    )));
                }
            }
        }
        if let Some(n) = self.layer_periods
            && !(1..=MAX_LAYER_PERIODS).contains(&n)
        {
            return Err(DatasetError::config(format!(
                "layer_periods {n} is not 1 to {MAX_LAYER_PERIODS}"
            )));
        }
        if let Some(z) = self.history_max_zoom
            && z > self.max_zoom
        {
            return Err(DatasetError::config(format!(
                "history_max_zoom {z} is above max_zoom {}",
                self.max_zoom
            )));
        }
        if let Some(code) = self.crs_epsg {
            Crs::from_epsg(code).within(format!("crs_epsg {code}"))?;
        }
        Ok(())
    }

    /// Decode a raw raster value: `raw * scale + offset`.
    ///
    /// `None` for NaN, the nodata value, a value in `flags`, or a decoded
    /// value outside `[valid_min, valid_max]`.
    #[must_use]
    pub fn decode(&self, raw: f32) -> Option<f64> {
        let raw = f64::from(raw);
        if raw.is_nan() || self.nodata == Some(raw) || self.flags.contains(&raw) {
            return None;
        }
        let value = raw * self.scale + self.offset;
        (self.valid_min..=self.valid_max)
            .contains(&value)
            .then_some(value)
    }

    /// The label of the comparison over `baseline` (`YYYY-YYYY`): for an
    /// `average` dataset `vs 2019–2025 average` (en dash), followed by
    /// ` (<sensor>)` when the config names one; `None` for a `normal` one.
    #[must_use]
    pub fn comparison_label(&self, baseline: &str) -> Option<String> {
        match self.comparison {
            Comparison::Normal => None,
            Comparison::Average => {
                let range = match baseline.split_once('-') {
                    Some((first, last)) => format!("{first}\u{2013}{last}"),
                    None => baseline.to_owned(),
                };
                Some(match &self.sensor {
                    Some(sensor) => format!("vs {range} average ({sensor})"),
                    None => format!("vs {range} average"),
                })
            }
        }
    }

    /// The attribution with `{year}` replaced by `years`: one year when both
    /// are equal, else `first–last` (en dash). Unchanged without `{year}`.
    #[must_use]
    pub fn attribution_for(&self, years: (i32, i32)) -> String {
        let (first, last) = years;
        let text = if first == last {
            first.to_string()
        } else {
            format!("{first}\u{2013}{last}")
        };
        self.attribution.replace("{year}", &text)
    }

    /// File name pattern of the `prelim/` folder.
    #[must_use]
    pub fn prelim_template(&self) -> &str {
        self.prelim_file_template
            .as_deref()
            .unwrap_or(&self.file_template)
    }

    /// The grid CRS named by `crs_epsg`, if any.
    ///
    /// Validation rejects unsupported codes, so a loaded config never loses
    /// its CRS here.
    #[must_use]
    pub fn crs(&self) -> Option<Crs> {
        self.crs_epsg.and_then(|code| Crs::from_epsg(code).ok())
    }
}

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

    /// A valid config as JSON text, with `overrides` replacing or adding keys.
    fn config_json(overrides: &[(&str, &str)]) -> String {
        let mut fields: Vec<(String, String)> = vec![
            ("id".into(), "\"t\"".into()),
            ("name".into(), "\"T\"".into()),
            ("unit".into(), "\"mm\"".into()),
            ("period".into(), "\"pentad\"".into()),
            ("scale".into(), "1.0".into()),
            ("offset".into(), "0.0".into()),
            ("valid_min".into(), "0.0".into()),
            ("valid_max".into(), "5000.0".into()),
            ("nodata".into(), "-9999.0".into()),
            ("crs_epsg".into(), "4326".into()),
            (
                "file_template".into(),
                "\"t.{year}.{month}.{pentad}.tif\"".into(),
            ),
            ("max_zoom".into(), "6".into()),
            ("tile_size".into(), "256".into()),
            ("season_start".into(), "\"06-01\"".into()),
            ("stale_after_days".into(), "18".into()),
            ("attribution".into(), "\"a\"".into()),
            ("source_url".into(), "\"https://example.org\"".into()),
            ("licence".into(), "\"CC BY 4.0\"".into()),
            (
                "ramp".into(),
                r##"[{"value": 0.0, "color": "#ffffd9"}, {"value": 5.0, "color": "#0c2c84"}]"##
                    .into(),
            ),
        ];
        for (key, value) in overrides {
            match fields.iter_mut().find(|(k, _)| k == key) {
                Some(field) => field.1 = (*value).to_owned(),
                None => fields.push(((*key).to_owned(), (*value).to_owned())),
            }
        }
        let body: Vec<String> = fields
            .iter()
            .map(|(k, v)| format!("\"{k}\": {v}"))
            .collect();
        format!("{{{}}}", body.join(", "))
    }

    #[test]
    fn rainfall_config_loads() {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/rainfall.json");
        let config = DatasetConfig::load(&path).expect("rainfall.json loads");
        assert_eq!(config.max_zoom, 6);
        assert_eq!(config.tile_size, 256);
        assert_eq!(
            config.attribution,
            "Rainfall: CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara. CC BY 4.0. \
             DOI 10.15780/G2JQ0P"
        );
        assert_eq!(config.licence, "CC BY 4.0");
        assert_eq!(config.season_start.as_deref(), Some("06-01"));
        assert_eq!(config.period, PeriodKind::Pentad);
        assert_eq!(config.crs(), Some(geolith::terrain::Crs::Wgs84));
        // Real CHIRPS v3.0 names from the host listings (2026-11-17).
        use crate::rasters::match_template;
        assert!(match_template(&config.file_template, "chirps-v3.0.2026.10.6.cog").is_some());
        assert!(match_template(&config.file_template, "chirps-v3.0.1991.01.1.cog").is_some());
        assert!(match_template(config.prelim_template(), "chirps-v3.0.2026.11.2.tif").is_some());
        assert!(match_template(config.prelim_template(), "chirps-v3.0.2026.11.2.cog").is_none());
        assert_eq!(config.nodata, Some(-9999.0));
        assert_eq!(config.stale_after_days, 18);
    }

    #[test]
    fn stale_after_days_is_required() {
        let json = config_json(&[]).replace("\"stale_after_days\": 18, ", "");
        assert!(!json.contains("stale_after_days"), "{json}");
        let err = DatasetConfig::from_json_str(&json).expect_err("no stale_after_days");
        assert!(
            geolith::error::report(&err).contains("stale_after_days"),
            "{err:#}"
        );
        let set = DatasetConfig::from_json_str(&config_json(&[("stale_after_days", "24")]))
            .expect("valid config");
        assert_eq!(set.stale_after_days, 24);
    }

    #[test]
    fn prelim_template_defaults_to_file_template() {
        let plain = DatasetConfig::from_json_str(&config_json(&[])).expect("valid config");
        assert_eq!(plain.prelim_template(), "t.{year}.{month}.{pentad}.tif");
        let split = DatasetConfig::from_json_str(&config_json(&[(
            "prelim_file_template",
            "\"p.{year}.{month}.{pentad}.tif\"",
        )]))
        .expect("valid config");
        assert_eq!(split.prelim_template(), "p.{year}.{month}.{pentad}.tif");
        assert_eq!(split.file_template, "t.{year}.{month}.{pentad}.tif");
    }

    #[test]
    fn load_names_the_missing_path() {
        let err = DatasetConfig::load(std::path::Path::new("/nonexistent/rain.json"))
            .expect_err("no such file");
        assert!(
            geolith::error::report(&err).contains("/nonexistent/rain.json"),
            "{err:#}"
        );
    }

    #[test]
    fn decode_masks_nodata_and_range() {
        let config = DatasetConfig::from_json_str(&config_json(&[])).expect("valid config");
        assert_eq!(config.decode(-9999.0), None);
        assert_eq!(config.decode(f32::NAN), None);
        assert_eq!(config.decode(-1.0), None);
        assert_eq!(config.decode(5000.5), None);
        assert_eq!(config.decode(0.0), Some(0.0));
        assert_eq!(config.decode(42.5), Some(42.5));
    }

    #[test]
    fn decode_applies_scale_then_offset() {
        let config = DatasetConfig::from_json_str(&config_json(&[
            ("scale", "0.004"),
            ("offset", "-0.08"),
            ("valid_min", "-1.0"),
            ("valid_max", "1.0"),
            ("nodata", "255.0"),
        ]))
        .expect("valid config");
        let decoded = config.decode(250.0).expect("250 is in range");
        assert!((decoded - 0.92).abs() < 1e-12, "{decoded}");
        assert_eq!(config.decode(255.0), None);
    }

    #[test]
    fn ramp_colours_parse() {
        let config = DatasetConfig::from_json_str(&config_json(&[(
            "ramp",
            r##"[{"value": 0.0, "color": "#0c2c84"}, {"value": 1.0, "color": "#0c2c8480"}]"##,
        )]))
        .expect("valid config");
        let opaque = config
            .ramp
            .iter()
            .find(|stop| stop.value == 0.0)
            .expect("stop at 0");
        assert_eq!(opaque.color, [12, 44, 132, 255]);
        let translucent = config
            .ramp
            .iter()
            .find(|stop| stop.value == 1.0)
            .expect("stop at 1");
        assert_eq!(translucent.color, [12, 44, 132, 128]);
    }

    #[test]
    fn a_season_start_off_a_period_start_is_rejected() {
        let err = DatasetConfig::from_json_str(&config_json(&[("season_start", "\"06-03\"")]))
            .expect_err("06-03 is inside pentad 06-1");
        assert!(geolith::error::report(&err).contains("06-03"), "{err:#}");
        for day in ["06-01", "06-06", "02-26", "12-21"] {
            let json = config_json(&[("season_start", &format!("\"{day}\""))]);
            let config = DatasetConfig::from_json_str(&json)
                .unwrap_or_else(|e| panic!("{day} starts a pentad: {e:#}"));
            assert_eq!(config.season_start.as_deref(), Some(day));
        }
    }

    #[test]
    fn bad_configs_are_rejected() {
        let cases: [(&str, &str); 9] = [
            ("ramp", r##"[{"value": 0.0, "color": "#ffffd9"}]"##),
            (
                "ramp",
                r##"[{"value": 5.0, "color": "#ffffd9"}, {"value": 5.0, "color": "#0c2c84"}]"##,
            ),
            ("valid_min", "10.0"),
            ("max_zoom", "23"),
            ("tile_size", "300"),
            ("season_start", "\"June 1\""),
            ("unknwon_key", "1"),
            (
                "ramp",
                r##"[{"value": 0.0, "color": "ffffd9"}, {"value": 5.0, "color": "#0c2c84"}]"##,
            ),
            ("crs_epsg", "27700"),
        ];
        for (key, value) in cases {
            let json = if key == "valid_min" {
                config_json(&[("valid_min", value), ("valid_max", "0.0")])
            } else {
                config_json(&[(key, value)])
            };
            assert!(
                DatasetConfig::from_json_str(&json).is_err(),
                "{key} = {value} must be rejected"
            );
        }

        let err = DatasetConfig::from_json_str(&config_json(&[("period", "\"week\"")]))
            .expect_err("week is no period");
        assert!(geolith::error::report(&err).contains("week"), "{err:#}");
    }

    fn repo_config(name: &str) -> DatasetConfig {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("data/datasets")
            .join(name);
        DatasetConfig::load(&path).unwrap_or_else(|e| panic!("{name} loads: {e:#}"))
    }

    /// A valid NDVI-like dekad config, with `overrides`.
    fn dekad_json(overrides: &[(&str, &str)]) -> String {
        let mut all = vec![
            ("period", "\"dekad\""),
            ("file_template", "\"ndvi300-v3.{year}.{month}.{dekad}.tif\""),
            ("season_start", "null"),
        ];
        all.extend_from_slice(overrides);
        config_json(&all)
    }

    #[test]
    fn rainfall_json_parses_with_p1_defaults() {
        let config = repo_config("rainfall.json");
        assert_eq!(config.comparison, Comparison::Normal);
        assert_eq!(config.reader, Reader::Whole);
        assert_eq!(config.anomaly_pct_min_normal, Some(1.0));
        assert!(config.flags.is_empty(), "{:?}", config.flags);
        assert_eq!(config.record_start, None);
        let again = serde_json::to_string(&config).expect("serialises");
        let reparsed = DatasetConfig::from_json_str(&again).expect("re-parses");
        assert_eq!(reparsed, config);
    }

    #[test]
    fn ndvi_json_parses() {
        let config = repo_config("ndvi.json");
        assert_eq!(config.period, PeriodKind::Dekad);
        assert_eq!(config.scale, 0.004);
        assert_eq!(config.offset, -0.08);
        assert_eq!(config.nodata, Some(255.0));
        assert_eq!(config.flags, [252.0, 253.0, 254.0]);
        assert_eq!(config.reader, Reader::Windowed);
        assert_eq!(config.comparison, Comparison::Average);
        assert_eq!(config.anomaly_pct_min_normal, None);
        assert_eq!(config.record_start.as_deref(), Some("2014-01-01"));
        assert_eq!(config.baseline.as_deref(), Some("2019-2025"));
        assert_eq!(config.sensor.as_deref(), Some("Sentinel-3 OLCI"));
        assert_eq!(config.max_zoom, 9);
        assert_eq!(config.season_start, None);
        assert_eq!(config.stale_after_days, 24);
        let again = serde_json::to_string(&config).expect("serialises");
        assert_eq!(
            DatasetConfig::from_json_str(&again).expect("re-parses"),
            config
        );
    }

    #[test]
    fn ndvi_raw_flags_and_nodata_are_masked() {
        let config = repo_config("ndvi.json");
        let low = config.decode(0.0).expect("raw 0 is valid");
        assert!((low - -0.08).abs() < 1e-12, "{low}");
        let high = config.decode(250.0).expect("raw 250 is valid");
        assert!((high - 0.92).abs() < 1e-12, "{high}");
        for raw in 251..=255u8 {
            assert_eq!(config.decode(f32::from(raw)), None, "raw {raw}");
        }
        assert_eq!(config.decode(f32::NAN), None);
    }

    #[test]
    fn dekad_templates_match() {
        use crate::rasters::{Period, match_template};
        assert_eq!(
            match_template(
                "ndvi300-v3.{year}.{month}.{dekad}.tif",
                "ndvi300-v3.2026.10.2.tif"
            ),
            Some(Period {
                year: 2026,
                month: 10,
                index: 2,
                kind: PeriodKind::Dekad,
            })
        );
        assert_eq!(
            match_template(
                "ndvi300-v3.{year}.{month}.{dekad}.tif",
                "ndvi300-v3.2026.10.4.tif"
            ),
            None
        );
        DatasetConfig::from_json_str(&dekad_json(&[])).expect("a dekad template is valid");
        for template in [
            "\"n.{year}.{month}.{pentad}.{dekad}.tif\"",
            "\"n.{year}.{month}.tif\"",
            "\"n.{year}.{month}.{pentad}.tif\"",
            "\"n.{year}.{month}.{dekad}.{dekad}.tif\"",
        ] {
            let err = DatasetConfig::from_json_str(&dekad_json(&[("file_template", template)]))
                .expect_err(template);
            assert!(
                geolith::error::report(&err).contains("file_template"),
                "{err:#}"
            );
        }
        let err = DatasetConfig::from_json_str(&dekad_json(&[(
            "prelim_file_template",
            "\"p.{year}.{month}.{pentad}.tif\"",
        )]))
        .expect_err("a pentad prelim template in a dekad config");
        assert!(
            geolith::error::report(&err).contains("prelim_file_template"),
            "{err:#}"
        );
        let err = DatasetConfig::from_json_str(&config_json(&[(
            "file_template",
            "\"t.{year}.{month}.{dekad}.tif\"",
        )]))
        .expect_err("a dekad template in a pentad config");
        assert!(geolith::error::report(&err).contains("{pentad}"), "{err:#}");
    }

    #[test]
    fn season_start_must_start_a_dekad() {
        for day in ["06-01", "06-11", "02-21"] {
            let json = dekad_json(&[("season_start", &format!("\"{day}\""))]);
            let config = DatasetConfig::from_json_str(&json)
                .unwrap_or_else(|e| panic!("{day} starts a dekad: {e:#}"));
            assert_eq!(config.season_start.as_deref(), Some(day));
        }
        for day in ["06-06", "06-26", "06-02"] {
            let json = dekad_json(&[("season_start", &format!("\"{day}\""))]);
            let err = DatasetConfig::from_json_str(&json).expect_err(day);
            let text = geolith::error::report(&err);
            assert!(text.contains(day) && text.contains("dekad"), "{text}");
        }
    }

    #[test]
    fn record_start_must_be_a_date() {
        let set = DatasetConfig::from_json_str(&dekad_json(&[("record_start", "\"2014-01-21\"")]))
            .expect("valid record_start");
        assert_eq!(set.record_start.as_deref(), Some("2014-01-21"));
        for bad in [
            "\"2014-1-21\"",
            "\"21-01-2014\"",
            "\"2014-02-30\"",
            "\"2015-02-29\"",
        ] {
            let err =
                DatasetConfig::from_json_str(&dekad_json(&[("record_start", bad)])).expect_err(bad);
            assert!(
                geolith::error::report(&err).contains("record_start"),
                "{err:#}"
            );
        }
        DatasetConfig::from_json_str(&dekad_json(&[("record_start", "\"2016-02-29\"")]))
            .expect("a leap day is a date");
    }

    #[test]
    fn repo_configs_carry_the_series_classes() {
        let rainfall = repo_config("rainfall.json");
        let classes = rainfall.classes.expect("rainfall classes");
        assert_eq!(classes.value, [1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0]);
        assert_eq!(classes.comparison, [25.0, 50.0, 80.0, 120.0, 150.0, 200.0]);
        assert_eq!(classes.comparison_kind, ClassComparison::PctOfNormal);
        assert_eq!(rainfall.layer_periods, Some(12));
        assert_eq!(rainfall.history_max_zoom, None);
        let ndvi = repo_config("ndvi.json");
        let classes = ndvi.classes.expect("ndvi classes");
        assert_eq!(classes.value, [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]);
        assert_eq!(classes.comparison, [-0.1, -0.05, -0.02, 0.02, 0.05, 0.1]);
        assert_eq!(classes.comparison_kind, ClassComparison::AnomalyAbs);
        // The anomaly breaks are symmetric around 0.
        let mirrored: Vec<f64> = classes.comparison.iter().rev().map(|b| -b).collect();
        assert_eq!(mirrored, classes.comparison);
        assert_eq!(ndvi.layer_periods, Some(12));
        assert_eq!(ndvi.history_max_zoom, Some(7));
    }

    #[test]
    fn bad_classes_and_layer_settings_are_refused() {
        let classes = |value: &str, comparison: &str| {
            format!(
                r#"{{"value":{value},"comparison":{comparison},"comparison_kind":"anomaly_abs"}}"#
            )
        };
        let ok = classes("[0.2,0.5]", "[-0.1,0.1]");
        DatasetConfig::from_json_str(&dekad_json(&[("classes", &ok)])).expect("valid classes");
        let too_many = format!(
            "[{}]",
            (0..36).map(|i| i.to_string()).collect::<Vec<_>>().join(",")
        );
        for bad in [
            classes("[]", "[1]"),
            classes("[0.5,0.2]", "[1]"),
            classes("[0.2,0.2]", "[1]"),
            classes("[1]", &too_many),
            r#"{"value":[1],"comparison":[1],"comparison_kind":"ratio"}"#.to_owned(),
            r#"{"value":[1],"comparison":[1],"comparison_kind":"anomaly_abs","x":1}"#.to_owned(),
        ] {
            assert!(
                DatasetConfig::from_json_str(&dekad_json(&[("classes", &bad)])).is_err(),
                "accepted {bad}"
            );
        }
        for (key, value, good) in [
            ("layer_periods", "1", true),
            ("layer_periods", "12", true),
            ("layer_periods", "0", false),
            ("layer_periods", "13", false),
            ("history_max_zoom", "0", true),
        ] {
            let parsed = DatasetConfig::from_json_str(&dekad_json(&[(key, value)]));
            assert_eq!(parsed.is_ok(), good, "{key} {value}: {parsed:?}");
        }
        let above = DatasetConfig::from_json_str(&dekad_json(&[("history_max_zoom", "23")]));
        assert!(above.is_err());
    }

    #[test]
    fn a_baseline_is_two_years_first_first() {
        let rainfall = repo_config("rainfall.json");
        assert_eq!(rainfall.baseline, None);
        assert_eq!(rainfall.sensor, None);
        for good in ["2019-2025", "2020-2020"] {
            DatasetConfig::from_json_str(&dekad_json(&[("baseline", &format!("\"{good}\""))]))
                .unwrap_or_else(|e| panic!("{good}: {e:#}"));
        }
        for bad in ["2025-2019", "2019", "19-25", "2019-2025-1", ""] {
            assert!(
                DatasetConfig::from_json_str(&dekad_json(&[("baseline", &format!("\"{bad}\""))]))
                    .is_err(),
                "{bad:?} accepted"
            );
        }
        assert!(DatasetConfig::from_json_str(&dekad_json(&[("sensor", "\" \"")])).is_err());
    }

    #[test]
    fn the_comparison_label_never_says_normal() {
        let ndvi = repo_config("ndvi.json");
        let label = ndvi.comparison_label("2019-2025").expect("average label");
        assert_eq!(label, "vs 2019\u{2013}2025 average (Sentinel-3 OLCI)");
        assert!(!label.to_lowercase().contains("normal"), "{label}");
        let no_sensor = DatasetConfig {
            sensor: None,
            ..ndvi
        };
        assert_eq!(
            no_sensor.comparison_label("2014-2025").as_deref(),
            Some("vs 2014\u{2013}2025 average")
        );
        assert_eq!(
            repo_config("rainfall.json").comparison_label("1991-2020"),
            None
        );
    }

    #[test]
    fn the_copernicus_year_is_filled() {
        let ndvi = repo_config("ndvi.json");
        assert_eq!(
            ndvi.attribution_for((2026, 2026)),
            "Contains modified Copernicus Land Monitoring Service information 2026"
        );
        assert_eq!(
            ndvi.attribution_for((2014, 2025)),
            "Contains modified Copernicus Land Monitoring Service information 2014\u{2013}2025"
        );
        let rainfall = repo_config("rainfall.json");
        assert_eq!(rainfall.attribution_for((2014, 2025)), rainfall.attribution);
        assert!(!rainfall.attribution.contains("{year}"));
    }

    #[test]
    fn period_kinds_know_their_starts() {
        assert_eq!(PeriodKind::default(), PeriodKind::Pentad);
        assert_eq!(PeriodKind::Pentad.periods_per_month(), 6);
        assert_eq!(PeriodKind::Dekad.periods_per_month(), 3);
        assert_eq!(PeriodKind::Pentad.starts(), [1, 6, 11, 16, 21, 26]);
        assert_eq!(PeriodKind::Dekad.starts(), [1, 11, 21]);
    }
}