geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
//! `geolith dataset cdse`: the NDVI dekads of the Copernicus Data Space.
//!
//! Ported from the former `scripts/datasets/cdse.ts` (`list`, `missing`, `merge`,
//! `series-range`, `window`) and the `cdse`, `cdse-clip`, `cdse-probe` and
//! `cdse-ls` verbs of the former `scripts/datasets/download.sh`. The STAC catalogue is
//! public and lists every dekad it has processed; it lags the S3 store by
//! weeks, so `missing` names the dekads it lacks and `merge` fills the list
//! from a direct S3 listing. A whole file is fetched here in closed 128 MiB
//! windows signed with the `SigV4` signer; a window of the raster
//! (`--mode clip`) is read by `gdal_translate`, the one optional external
//! tool, and an absent or broken GDAL is refused with [`Exit`] `3`.
//!
//! Keys come from `CDSE_S3_ACCESS_KEY`/`CDSE_S3_SECRET_KEY` (the process
//! environment or the `.env` file) or the optional mode-600
//! `sources.cdse_credentials_file` (`CDSE_ENV_FILE`).
//! They never reach an argument, a printed line or a `.src` sidecar; GDAL
//! receives them through its environment only.

use std::collections::BTreeMap;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, JsonResultExt as _, Result, WithinExt as _,
};
use serde_json::Value;

use crate::cli::{
    CdseAction, CdseArgs, CdseListArgs, CdseLsArgs, CdseMergeArgs, CdseMissingArgs,
    CdseSeriesRangeArgs, CdseWindowArgs,
};
use crate::exit::Exit;
use crate::layout::{Settings, today_utc, unix_seconds};
use crate::s3::sigv4::{Credentials, SignableRequest, amz_date, empty_payload_sha256, sign};
use crate::settings;

/// The public STAC root.
pub const DEFAULT_STAC: &str = "https://stac.dataspace.copernicus.eu/v1";

/// The NDVI 300 m 10-daily v3 collection.
const COLLECTION: &str = "clms_ndvi_global_300m_10daily_v3_cog";

/// The NDVI grid: origin x and y, pixel size x and y, width and height.
pub const NDVI_GRID: [f64; 6] = [
    -180.001_488_095_238_1,
    80.001_488_095_238_09,
    0.002_976_190_476_204,
    -0.002_976_190_476_189_8,
    120_960.0,
    47_040.0,
];

/// The day of a dekad start to its index.
const DEKADS: [(&str, u8); 3] = [("01", 1), ("11", 2), ("21", 3)];

/// Cells an area value may reach past its area (`numbers::FALLBACK_REACH`).
const FALLBACK_REACH: f64 = 2.0;

/// The S3 root of the NDVI 300 m v3 product under `eodata/`.
pub const S3_ROOT: &str = "CLMS/bio-geophysical/vegetation_indices/ndvi_global_300m_10daily_v3";

/// The CDSE S3 endpoint.
pub const DEFAULT_ENDPOINT: &str = "https://eodata.dataspace.copernicus.eu";

/// The region the CDSE endpoint signs with, as `curl --aws-sigv4` does.
const REGION: &str = "default";

/// Bytes per closed range of a whole-file fetch.
const CHUNK_BYTES: u64 = 128 * 1024 * 1024;

/// Attempts per closed range before a file is left for the next run.
const CHUNK_ATTEMPTS: u32 = 5;

/// Attempts per S3 listing page.
const LIST_ATTEMPTS: u32 = 10;

/// Seconds between two attempts.
const RETRY_DELAY: u64 = 10;

/// The block size the clip is written in.
const BLOCKSIZE: &str = "512";

/// One dekad of the catalogue: its S3 key, its local name and its size.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListLine {
    /// The key under `eodata/`.
    pub key: String,
    /// `ndvi300-v3.<YYYY>.<MM>.<dekad>.tif`.
    pub name: String,
    /// Size in bytes, as the catalogue or the store reports it.
    pub bytes: u64,
}

impl ListLine {
    /// The line a list file holds: `final <key> <name> <bytes>`.
    #[must_use]
    pub fn final_line(&self) -> String {
        format!("final {} {} {}", self.key, self.name, self.bytes)
    }
}

/// Every item of one dekad: the newest `processing:version` wins.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Group {
    name: String,
    best: ListLine,
    version: String,
    replaced: Vec<(ListLine, String)>,
}

/// A `ureq` agent with the download timeouts.
fn agent() -> Result<ureq::Agent> {
    Ok(ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(1800)))
        .http_status_as_error(false)
        .build()
        .into())
}

/// RFC 3986 percent-encoding of one query component.
fn encode_component(text: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(text.len());
    for byte in text.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
            out.push(char::from(byte));
        } else {
            let _ = write!(out, "%{byte:02X}");
        }
    }
    out
}

/// Whether `text` is `YYYY-MM-DD`.
#[must_use]
pub fn is_date(text: &str) -> bool {
    let bytes = text.as_bytes();
    bytes.len() == 10
        && bytes[4] == b'-'
        && bytes[7] == b'-'
        && bytes
            .iter()
            .enumerate()
            .all(|(index, byte)| matches!(index, 4 | 7) || byte.is_ascii_digit())
}

/// `V3.0.10` → `[3, 0, 10]`, compared component by component.
#[must_use]
pub fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering {
    let parts = |text: &str| -> Vec<i64> {
        let mut out = Vec::new();
        let mut digits = String::new();
        for byte in text.bytes() {
            if byte.is_ascii_digit() {
                digits.push(char::from(byte));
            } else if !digits.is_empty() {
                out.push(digits.parse::<i64>().unwrap_or(0));
                digits.clear();
            }
        }
        if !digits.is_empty() {
            out.push(digits.parse::<i64>().unwrap_or(0));
        }
        out
    };
    let (pa, pb) = (parts(a), parts(b));
    for index in 0..pa.len().max(pb.len()) {
        let left = pa.get(index).copied().unwrap_or(0);
        let right = pb.get(index).copied().unwrap_or(0);
        match left.cmp(&right) {
            std::cmp::Ordering::Equal => {}
            other => return other,
        }
    }
    std::cmp::Ordering::Equal
}

/// `YYYY-MM-DDTHH:MM:SSZ` of a first date and a trait-free calendar.
fn parts_of(date: &str) -> (i64, u8, u8) {
    let year = date.get(..4).and_then(|v| v.parse().ok()).unwrap_or(0);
    let month = date.get(5..7).and_then(|v| v.parse().ok()).unwrap_or(1);
    let day = date.get(8..10).and_then(|v| v.parse().ok()).unwrap_or(1);
    (year, month, day)
}

/// The last day of `month` of `year`.
fn last_day(year: i64, month: u8) -> u8 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        _ if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29,
        _ => 28,
    }
}

/// `YYYY-MM-DD` of a year, month and day; a month 0 or negative rolls into
/// the year before, as `Date.UTC` does.
fn date_of(year: i64, month: i64, day: u8) -> String {
    let (year, month) = if month < 1 {
        let back = (1 - month) / 12 + 1;
        (year - back, (month + 12 * back) as u8)
    } else if month > 12 {
        (year + (month - 1) / 12, ((month - 1) % 12 + 1) as u8)
    } else {
        (year, month as u8)
    };
    format!("{year:04}-{month:02}-{day:02}")
}

/// The local name of the dekad that starts on `day`.
fn local_name(year: i64, month: u8, day: &str) -> Option<String> {
    let dekad = DEKADS
        .iter()
        .find(|(start, _)| *start == day)
        .map(|(_, index)| index)?;
    Some(format!("ndvi300-v3.{year}.{month:02}.{dekad}.tif"))
}

/// The GET of `url`, its JSON body.
fn get_json(agent: &ureq::Agent, url: &str) -> Result<Value> {
    let mut response = agent
        .get(url)
        .header("accept", "application/geo+json")
        .call()
        .within(format!("GET {url}"))?;
    let status = response.status().as_u16();
    if !(200..300).contains(&status) {
        return Err(DatasetError::fetch(format!("GET {url}: HTTP {status}")));
    }
    let bytes = response
        .body_mut()
        .with_config()
        .limit(32 * 1024 * 1024)
        .read_to_vec()
        .within(format!("reading the body of {url}"))?;
    serde_json::from_slice(&bytes).json_of(format!("parsing the body of {url}"))
}

/// Every item of the pages at `url` and of each page its `rel=next` names.
fn features(agent: &ureq::Agent, url: &str) -> Result<Vec<Value>> {
    let mut out = Vec::new();
    let mut next = Some(url.to_owned());
    while let Some(url) = next {
        let page = get_json(agent, &url)?;
        if let Some(list) = page.get("features").and_then(Value::as_array) {
            out.extend(list.iter().cloned());
        }
        next = page
            .get("links")
            .and_then(Value::as_array)
            .and_then(|links| {
                links
                    .iter()
                    .find(|link| link.get("rel").and_then(Value::as_str) == Some("next"))
            })
            .and_then(|link| link.get("href").and_then(Value::as_str))
            .map(str::to_owned);
    }
    Ok(out)
}

/// The dekad of one STAC item, and its `processing:version`.
fn entry_of(item: &Value) -> Result<(ListLine, String)> {
    let id = item.get("id").and_then(Value::as_str).unwrap_or("(no id)");
    let properties = item.get("properties");
    let start = properties
        .and_then(|value| value.get("start_datetime"))
        .and_then(Value::as_str);
    let version = properties
        .and_then(|value| value.get("processing:version"))
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned();
    let asset = item.get("assets").and_then(|value| value.get("ndvi"));
    let href = asset
        .and_then(|value| value.get("href"))
        .and_then(Value::as_str);
    let bytes = asset
        .and_then(|value| value.get("file:size"))
        .and_then(Value::as_u64);
    let Some(start) = start else {
        return Err(DatasetError::fetch(format!(
            "item {id}: start_datetime is not a dekad start"
        )));
    };
    let Some(name) = dekad_name(start) else {
        return Err(DatasetError::fetch(format!(
            "item {id}: start_datetime {start} is not a dekad start"
        )));
    };
    let Some(href) = href.filter(|href| href.starts_with("s3://eodata/")) else {
        return Err(DatasetError::fetch(format!(
            "item {id}: ndvi asset href is not s3://eodata/…"
        )));
    };
    let Some(bytes) = bytes.filter(|bytes| *bytes > 0) else {
        return Err(DatasetError::fetch(format!(
            "item {id}: ndvi asset has no file:size"
        )));
    };
    Ok((
        ListLine {
            key: href.trim_start_matches("s3://eodata/").to_owned(),
            name,
            bytes,
        },
        version,
    ))
}

/// The local name of the dekad an item's `start_datetime` names.
fn dekad_name(start: &str) -> Option<String> {
    let date = start.get(..10)?;
    if !is_date(date) || start.as_bytes().get(10) != Some(&b'T') {
        return None;
    }
    let (year, month, day) = parts_of(date);
    local_name(year, month, &format!("{day:02}"))
}

/// The dekads of `features`, each with its newest version first.
fn groups(features: &[Value]) -> Result<Vec<Group>> {
    let mut by_name: BTreeMap<String, Vec<(ListLine, String)>> = BTreeMap::new();
    for feature in features {
        let (line, version) = entry_of(feature)?;
        by_name
            .entry(line.name.clone())
            .or_default()
            .push((line, version));
    }
    let mut out = Vec::with_capacity(by_name.len());
    for (name, mut entries) in by_name {
        entries.sort_by(|a, b| compare_versions(&b.1, &a.1));
        let Some((best, version)) = entries.first().cloned() else {
            continue;
        };
        out.push(Group {
            name,
            best,
            version,
            replaced: entries.into_iter().skip(1).collect(),
        });
    }
    Ok(out)
}

/// The lines of `cdse list`: one `final` line per dekad, oldest first, and a
/// `#` line naming every entry a newer `processing:version` replaced.
///
/// # Errors
///
/// Fails when a date is not `YYYY-MM-DD`, the catalogue cannot be read, or an
/// item is not a dekad of the product.
pub fn list(from: &str, to: &str, stac: &str) -> Result<Vec<String>> {
    if !is_date(from) || !is_date(to) {
        return Err(DatasetError::fetch(
            "list needs --from and --to as YYYY-MM-DD",
        ));
    }
    let stac = stac.trim_end_matches('/');
    let url = format!(
        "{stac}/collections/{COLLECTION}/items?datetime={}&limit=100",
        encode_component(&format!("{from}T00:00:00Z/{to}T23:59:59Z"))
    );
    let agent = agent()?;
    let mut lines = Vec::new();
    for group in groups(&features(&agent, &url)?)? {
        for (other, version) in &group.replaced {
            lines.push(format!(
                "# {}: {} ({version}) replaced by {}",
                group.name, other.key, group.version
            ));
        }
        lines.push(group.best.final_line());
    }
    Ok(lines)
}

/// The name a `final` list line of `text` carries.
fn name_of_line(line: &str) -> Option<&str> {
    let mut parts = line.split(' ');
    let status = parts.next()?;
    parts.next()?;
    let name = parts.next()?;
    let bytes = parts.next()?;
    if status != "final" || parts.next().is_some() {
        return None;
    }
    if !bytes.bytes().all(|byte| byte.is_ascii_digit()) || !is_ndvi_name(name) {
        return None;
    }
    Some(name)
}

/// Whether `name` is `ndvi300-v3.<YYYY>.<MM>.<1-3>.tif`.
fn is_ndvi_name(name: &str) -> bool {
    let Some(rest) = name.strip_prefix("ndvi300-v3.") else {
        return false;
    };
    let Some(rest) = rest.strip_suffix(".tif") else {
        return false;
    };
    let parts: Vec<&str> = rest.split('.').collect();
    if parts.len() != 3 {
        return false;
    }
    let [year, month, dekad] = [parts[0], parts[1], parts[2]];
    year.len() == 4
        && year.bytes().all(|byte| byte.is_ascii_digit())
        && month.len() == 2
        && month.bytes().all(|byte| byte.is_ascii_digit())
        && matches!(dekad, "1" | "2" | "3")
}

/// The S3 prefixes of the dekads of `from`..`to` that started on or before
/// `today` and are absent from the list `list_text`.
#[must_use]
pub fn missing(list_text: &str, from: &str, to: &str, today: &str) -> Vec<String> {
    let have: std::collections::BTreeSet<&str> =
        list_text.split('\n').filter_map(name_of_line).collect();
    let mut out = Vec::new();
    let (year, month, _) = parts_of(from);
    let (mut year, mut month) = (year, i64::from(month));
    loop {
        let month_start = date_of(year, month, 1);
        if month_start.as_str() > to {
            break;
        }
        for (day, _) in DEKADS {
            let start = date_of(year, month, day.parse().unwrap_or(1));
            if start.as_str() < from || start.as_str() > to || start.as_str() > today {
                continue;
            }
            if local_name(year, u8::try_from(month).unwrap_or(1), day)
                .is_some_and(|name| !have.contains(name.as_str()))
            {
                out.push(format!("{S3_ROOT}/{year}/{month:02}/{day}/"));
            }
        }
        month += 1;
        if month > 12 {
            month = 1;
            year += 1;
        }
    }
    out
}

/// The `(key, bytes)` of one S3 listing line of the NDVI COG.
fn s3_ndvi(line: &str) -> Option<(String, String, String, u64)> {
    let (key, bytes) = line.rsplit_once(' ')?;
    let bytes = bytes.parse::<u64>().ok()?;
    if !key.contains("_cog/") {
        return None;
    }
    let file = key.rsplit('/').next()?;
    let parts: Vec<&str> = file.split('_').collect();
    if parts.len() != 7 || parts[0] != "c" || parts[1] != "gls" || parts[2] != "NDVI300-NDVI" {
        return None;
    }
    if parts[4] != "GLOBE" || parts[5].is_empty() {
        return None;
    }
    let stamp = parts[3];
    if stamp.len() != 12 || !stamp.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    let version = parts[6].strip_suffix(".tiff")?;
    let digits = version.strip_prefix('V')?;
    let numbers: Vec<&str> = digits.split('.').collect();
    if numbers.is_empty()
        || !numbers
            .iter()
            .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
    {
        return None;
    }
    let (year, month, day) = (
        stamp.get(0..4)?.parse::<i64>().ok()?,
        stamp.get(4..6)?.parse::<u8>().ok()?,
        stamp.get(6..8)?,
    );
    let name = local_name(year, month, day)?;
    Some((key.to_owned(), name, version.to_owned(), bytes))
}

/// The cdse list `list_text` plus a `final` line for every dekad of the S3
/// listing `s3_text` (`<key> <bytes>` lines) it lacks: the NDVI COG of the
/// newest version, each after a `#` line naming its source. A dekad of the
/// list is never replaced. Lines in name order.
#[must_use]
pub fn merge(list_text: &str, s3_text: &str) -> String {
    let lines: Vec<String> = list_text
        .split('\n')
        .filter(|line| !line.trim().is_empty())
        .map(str::to_owned)
        .collect();
    let have: std::collections::BTreeSet<&str> =
        lines.iter().filter_map(|l| name_of_line(l)).collect();
    let mut best: BTreeMap<String, (String, u64, String)> = BTreeMap::new();
    for line in s3_text.split('\n') {
        let Some((key, name, version, bytes)) = s3_ndvi(line.trim()) else {
            continue;
        };
        if have.contains(name.as_str()) {
            continue;
        }
        match best.get(&name) {
            Some((_, _, old)) if compare_versions(&version, old) != std::cmp::Ordering::Greater => {
            }
            _ => {
                best.insert(name, (key, bytes, version));
            }
        }
    }
    let mut by_name: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for line in lines {
        let name = name_of_line(&line).map(str::to_owned).or_else(|| {
            let rest = line.strip_prefix("# ")?;
            Some(rest.split_once(':')?.0.to_owned())
        });
        by_name
            .entry(name.unwrap_or_default())
            .or_default()
            .push(line);
    }
    for (name, (key, bytes, _)) in best {
        let entry = by_name.entry(name.clone()).or_default();
        entry.push(format!(
            "# {name}: from the S3 listing (not in the STAC yet)"
        ));
        entry.push(format!("final {key} {name} {bytes}"));
    }
    by_name
        .into_values()
        .flat_map(|entries| entries.into_iter())
        .collect::<Vec<_>>()
        .join("\n")
}

/// A bounding box of longitudes and latitudes.
#[derive(Debug, Clone, Copy)]
struct Bounds {
    min_x: f64,
    min_y: f64,
    max_x: f64,
    max_y: f64,
}

impl Bounds {
    /// The full box, `f64::INFINITY` outside and `-INFINITY` inside.
    fn empty() -> Self {
        Self {
            min_x: f64::INFINITY,
            min_y: f64::INFINITY,
            max_x: f64::NEG_INFINITY,
            max_y: f64::NEG_INFINITY,
        }
    }

    /// Widen the box by every position of `geometry`.
    fn widen(&mut self, geometry: Option<&Value>) {
        let mut points = Vec::new();
        if let Some(geometry) = geometry {
            positions(
                geometry.get("coordinates").unwrap_or(&Value::Null),
                &mut points,
            );
        }
        for (x, y) in points {
            self.min_x = self.min_x.min(x);
            self.max_x = self.max_x.max(x);
            self.min_y = self.min_y.min(y);
            self.max_y = self.max_y.max(y);
        }
    }

    /// Whether no position was ever added.
    fn is_empty(&self) -> bool {
        !self.min_x.is_finite()
    }
}

/// Push every `[x, y]` of a nested coordinate array.
fn positions(value: &Value, out: &mut Vec<(f64, f64)>) {
    let Some(array) = value.as_array() else {
        return;
    };
    if let Some(x) = array.first().and_then(Value::as_f64) {
        if let Some(y) = array.get(1).and_then(Value::as_f64) {
            out.push((x, y));
        }
        return;
    }
    for item in array {
        positions(item, out);
    }
}

/// The pixel window `<x0> <y0> <width> <height>` of a country's areas and of
/// every feature of `outline`, widened by `FALLBACK_REACH` cells, snapped
/// outward to the `block` grid and clamped to the raster.
///
/// # Errors
///
/// Fails when the grid or the block is invalid, an India window has no
/// outline, the areas hold none of `country`, or they lie outside the grid.
pub fn window(
    areas: &Path,
    outline: Option<&Path>,
    country: &str,
    grid: [f64; 6],
    block: u32,
) -> Result<(i64, i64, u32, u32)> {
    let [ox, oy, px, py, width, height] = grid;
    if grid.iter().any(|value| !value.is_finite()) || px <= 0.0 || py >= 0.0 {
        return Err(DatasetError::usage(
            "--grid must be <x0>,<y0>,<px>,<py>,<width>,<height> with px > 0 > py",
        ));
    }
    if block == 0 {
        return Err(DatasetError::usage("--block must be a positive integer"));
    }
    let country = country.to_uppercase();
    if country == "IN" && outline.is_none() {
        return Err(DatasetError::fetch(
            "window for IN needs --outline <Survey of India GeoJSON>",
        ));
    }
    let mut bounds = Bounds::empty();
    let areas_json = crate::layout::read_json(areas)?;
    for feature in areas_json
        .get("features")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        let code = feature
            .get("properties")
            .and_then(|value| value.get("country"))
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_uppercase();
        if code != country {
            continue;
        }
        bounds.widen(feature.get("geometry"));
    }
    if bounds.is_empty() {
        return Err(DatasetError::fetch(format!(
            "{} has no area of country {country}",
            areas.display()
        )));
    }
    if let Some(outline) = outline {
        let outline_json = crate::layout::read_json(outline)?;
        for feature in outline_json
            .get("features")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            bounds.widen(feature.get("geometry"));
        }
    }
    let block = f64::from(block);
    let down = |value: f64| ((value / block).floor() * block).max(0.0);
    let up = |value: f64| (value / block).ceil() * block;
    let x0 = down(((bounds.min_x - ox) / px).floor() - FALLBACK_REACH);
    let y0 = down(((bounds.max_y - oy) / py).floor() - FALLBACK_REACH);
    let x1 = width.min(up(((bounds.max_x - ox) / px).ceil() + FALLBACK_REACH));
    let y1 = height.min(up(((bounds.min_y - oy) / py).ceil() + FALLBACK_REACH));
    if x1 <= x0 || y1 <= y0 {
        return Err(DatasetError::fetch(format!(
            "the {country} areas lie outside the grid"
        )));
    }
    let (w, h) = (x1 - x0, y1 - y0);
    Ok((x0 as i64, y0 as i64, w.round() as u32, h.round() as u32))
}

/// The start of the dekad 12 before the current one and the end of the
/// current dekad, for `today` (`YYYY-MM-DD`).
#[must_use]
pub fn series_range(today: &str) -> (String, String) {
    let (year, month, day) = parts_of(today);
    let dekad: u8 = if day <= 10 {
        0
    } else if day <= 20 {
        1
    } else {
        2
    };
    let end = if dekad < 2 {
        date_of(year, i64::from(month), dekad * 10 + 10)
    } else {
        date_of(year, i64::from(month), last_day(year, month))
    };
    // 12 dekads are exactly 4 months.
    let start = date_of(year, i64::from(month) - 4, dekad * 10 + 1);
    (start, end)
}

/// The endpoint to read from (`sources.cdse_endpoint`).
#[must_use]
pub fn endpoint() -> String {
    settings::current()
        .sources
        .cdse_endpoint
        .clone()
        .unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned())
}

/// The key pair: the environment first, then the mode-600 file.
///
/// # Errors
///
/// Fails with [`Exit`] `2` when neither names a key id and a secret, and when
/// the file is readable by others.
pub fn credentials() -> Result<Credentials> {
    settings::current().cdse_credentials()?.ok_or_else(|| DatasetError::fetch("set CDSE_S3_ACCESS_KEY and CDSE_S3_SECRET_KEY, or name a sources.cdse_credentials_file \
         (CDSE account, S3 keys)",))
}

/// One signed client of the CDSE S3 endpoint.
struct Source {
    agent: ureq::Agent,
    endpoint: String,
    host: String,
    credentials: Credentials,
}

impl Source {
    /// # Errors
    ///
    /// Fails when the endpoint is not a URL.
    fn new(endpoint: &str, credentials: Credentials) -> Result<Self> {
        let rest = endpoint
            .split_once("://")
            .map_or(endpoint, |(_, rest)| rest);
        let host = rest.split('/').next().unwrap_or_default();
        if host.is_empty() {
            return Err(DatasetError::fetch(format!(
                "endpoint {endpoint} is not a URL"
            )));
        }
        Ok(Self {
            agent: agent()?,
            endpoint: endpoint.trim_end_matches('/').to_owned(),
            host: host.to_owned(),
            credentials,
        })
    }

    /// The status and the body of a signed `GET` of `path`.
    ///
    /// # Errors
    ///
    /// Fails when the request cannot be made.
    fn get(
        &self,
        path: &str,
        query: &[(String, String)],
        range: Option<String>,
        limit: u64,
    ) -> Result<(u16, Vec<u8>)> {
        let mut url = format!("{}{path}", self.endpoint);
        if !query.is_empty() {
            url.push('?');
            url.push_str(&crate::s3::sigv4::canonical_query(query));
        }
        let mut headers = Vec::new();
        if let Some(range) = &range {
            headers.push(("range".to_owned(), range.clone()));
        }
        let request = SignableRequest {
            method: "GET",
            host: &self.host,
            path,
            query: query.to_vec(),
            headers,
            payload_sha256: empty_payload_sha256(),
        };
        let signed = sign(
            &request,
            &self.credentials,
            REGION,
            &amz_date(unix_seconds()),
        )?;
        let mut http = self.agent.get(&url);
        for (name, value) in &signed {
            http = http.header(name, value);
        }
        if let Some(range) = range {
            http = http.header("range", range);
        }
        let mut response = http.call().within(format!("GET {url}"))?;
        let status = response.status().as_u16();
        let body = response
            .body_mut()
            .with_config()
            .limit(limit)
            .read_to_vec()
            .within(format!("reading the body of {url}"))?;
        Ok((status, body))
    }
}

/// The `(key, bytes)` of every object under each `prefix`.
///
/// # Errors
///
/// Fails when a listing page cannot be read or answers a non-2xx status.
fn s3_keys(source: &Source, prefixes: &[String]) -> Result<Vec<(String, u64)>> {
    let mut out = Vec::new();
    for prefix in prefixes {
        let mut token: Option<String> = None;
        loop {
            let mut query = vec![
                ("list-type".to_owned(), "2".to_owned()),
                ("prefix".to_owned(), prefix.clone()),
            ];
            if let Some(token) = &token {
                query.push(("continuation-token".to_owned(), token.clone()));
            }
            let mut attempt = 0;
            let text = loop {
                attempt += 1;
                match source.get("/eodata", &query, None, 8 * 1024 * 1024) {
                    Ok((status, body)) if (200..300).contains(&status) => {
                        break String::from_utf8_lossy(&body).into_owned();
                    }
                    Ok(_) | Err(_) if attempt >= LIST_ATTEMPTS => {
                        return Err(DatasetError::fetch(format!(
                            "cannot list s3://eodata/{prefix}"
                        )));
                    }
                    Ok(_) | Err(_) => std::thread::sleep(Duration::from_secs(RETRY_DELAY)),
                }
            };
            for contents in between(&text, "<Contents>", "</Contents>") {
                let Some(key) = tag(contents, "Key") else {
                    continue;
                };
                let Some(bytes) = tag(contents, "Size").and_then(|size| size.parse::<u64>().ok())
                else {
                    continue;
                };
                out.push((unescape(key), bytes));
            }
            token = if text.contains("<IsTruncated>true</IsTruncated>") {
                tag(&text, "NextContinuationToken").map(unescape)
            } else {
                None
            };
            if token.is_none() {
                break;
            }
        }
    }
    Ok(out)
}

/// Every substring of `xml` between `start` and the `end` after it.
fn between<'a>(xml: &'a str, start: &str, end: &str) -> Vec<&'a str> {
    let mut out = Vec::new();
    let mut rest = xml;
    while let Some((_, after)) = rest.split_once(start) {
        let Some((inside, tail)) = after.split_once(end) else {
            break;
        };
        out.push(inside);
        rest = tail;
    }
    out
}

/// The text of the first `<name>` element of `xml`.
fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
    let open = format!("<{name}>");
    let close = format!("</{name}>");
    let (_, after) = xml.split_once(&open)?;
    let (inside, _) = after.split_once(&close)?;
    Some(inside)
}

/// The five XML entities an S3 listing may carry.
fn unescape(text: &str) -> String {
    text.replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&#39;", "'")
}

/// The size of `path`, or 0.
fn file_size(path: &Path) -> u64 {
    fs::metadata(path).map(|meta| meta.len()).unwrap_or(0)
}

/// `<dest>.part`.
fn part_of(dest: &Path) -> PathBuf {
    PathBuf::from(format!("{}.part", dest.display()))
}

/// The bytes `start..=end` of `key`, `attempts` tries of a closed range.
fn get_range(source: &Source, key: &str, start: u64, end: u64, attempts: u32) -> Result<Vec<u8>> {
    let path = format!("/eodata/{key}");
    let range = format!("bytes={start}-{end}");
    let want = usize::try_from(end - start + 1).unwrap_or(usize::MAX);
    let mut attempt = 0;
    loop {
        attempt += 1;
        let last = attempt >= attempts;
        match source.get(
            &path,
            &[],
            Some(range.clone()),
            u64::try_from(want + 1).unwrap_or(u64::MAX),
        ) {
            Ok((status, bytes)) => {
                // A 200 for a resumed range would append the whole file.
                let partial = if start == 0 {
                    (200..300).contains(&status)
                } else {
                    status == 206
                };
                if partial && bytes.len() == want {
                    return Ok(bytes);
                }
                if last {
                    return Err(DatasetError::fetch(format!(
                        "GET {path}: window {start}-{end} answered {status}, {} bytes",
                        bytes.len()
                    )));
                }
            }
            Err(error) => {
                if last {
                    return Err(error).within(format!("GET {path}: window {start}-{end}"));
                }
            }
        }
        std::thread::sleep(Duration::from_secs(RETRY_DELAY));
    }
}

/// One list line: `final <key> <ndvi name> <bytes>`.
#[must_use]
pub fn list_line(line: &str) -> Option<ListLine> {
    let mut parts = line.split_whitespace();
    let status = parts.next()?;
    let key = parts.next()?;
    let name = parts.next()?;
    let bytes = parts.next()?;
    if status != "final" || parts.next().is_some() || name.contains('/') || !is_ndvi_name(name) {
        return None;
    }
    Some(ListLine {
        key: key.to_owned(),
        name: name.to_owned(),
        bytes: bytes.parse().ok()?,
    })
}

/// Download `entry` into `dest` through closed `chunk`-byte windows,
/// appending to `<dest>.part`; the lines it prints land in `out`.
fn download_one(
    source: &Source,
    entry: &ListLine,
    dest: &Path,
    chunk: u64,
    tries: u32,
    out: &mut Vec<String>,
) -> Result<()> {
    let name = dest
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    if dest.is_file() && file_size(dest) == entry.bytes {
        out.push(format!("SKIP {name}"));
        return Ok(());
    }
    let part = part_of(dest);
    if part.is_file() && file_size(&part) > entry.bytes {
        // A shrunken listing: appending would corrupt the raster.
        fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
    }
    let mut start = file_size(&part);
    if start > 0 {
        out.push(format!("RESUME {name} from {start}"));
    }
    while start < entry.bytes {
        let end = (start + chunk - 1).min(entry.bytes - 1);
        let bytes = get_range(source, &entry.key, start, end, tries).within(format!(
            "{name}: window {start}-{end} failed after {tries} attempts"
        ))?;
        let mut file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&part)
            .io_at(IoOp::Open, &part)?;
        file.write_all(&bytes).io_at(IoOp::Write, &part)?;
        drop(file);
        start = end + 1;
    }
    if file_size(&part) != entry.bytes {
        eprintln!(
            "size mismatch for {}: got {}, expected {}",
            entry.key,
            file_size(&part),
            entry.bytes
        );
        fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
        return Err(DatasetError::fetch(format!(
            "{} is not {} bytes",
            entry.key, entry.bytes
        )));
    }
    fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
    out.push(format!("OK {name}"));
    Ok(())
}

/// Download every file of `list` whole, into `dest_dir`.
///
/// # Errors
///
/// Fails with [`Exit`] `1` when a file is missing, naming each one, `2` when
/// the keys are absent, and when a window cannot be read.
pub fn download_full(list: &Path, dest_dir: &Path) -> Result<()> {
    let source = Source::new(&endpoint(), credentials()?)?;
    download_full_with(&source, list, dest_dir, CHUNK_BYTES, CHUNK_ATTEMPTS)
}

/// [`download_full`] over a client and a window size, for a test.
///
/// # Errors
///
/// Fails with [`Exit`] `1` when a file is missing, naming each one.
fn download_full_with(
    source: &Source,
    list: &Path,
    dest_dir: &Path,
    chunk: u64,
    tries: u32,
) -> Result<()> {
    let text = fs::read_to_string(list).io_at(IoOp::Read, list)?;
    fs::create_dir_all(dest_dir).io_at(IoOp::Create, dest_dir)?;
    let mut failed: Vec<String> = Vec::new();
    let mut out = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some(entry) = list_line(line) else {
            eprintln!("bad list line: {line}");
            failed.push(line.to_owned());
            continue;
        };
        let dest = dest_dir.join(&entry.name);
        match download_one(source, &entry, &dest, chunk, tries, &mut out) {
            Ok(()) => {}
            Err(error) => {
                eprintln!("{error:#}");
                failed.push(entry.key.clone());
            }
        }
    }
    for line in &out {
        println!("{line}");
    }
    if failed.is_empty() {
        return Ok(());
    }
    for key in failed {
        println!("FAILED {key}");
    }
    Err(Exit(1).into())
}

/// Whether `gdal_translate` runs.
#[must_use]
pub fn gdal_available() -> bool {
    Command::new("gdal_translate")
        .arg("--version")
        .output()
        .is_ok_and(|output| output.status.success())
}

/// `GDAL 3.13.3` from `gdal_translate --version`.
fn gdal_version(gdal: &Path) -> Option<String> {
    let output = Command::new(gdal).arg("--version").output().ok()?;
    if !output.status.success() {
        return None;
    }
    let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
    text.push_str(&String::from_utf8_lossy(&output.stderr));
    let first = text.trim().split(',').next()?.trim().to_owned();
    (!first.is_empty()).then_some(first)
}

/// The CDSE keys and endpoint in a child's environment only, never its argv.
fn clip_env(command: &mut Command, source: &Source) {
    for name in [
        "AWS_SESSION_TOKEN",
        "AWS_PROFILE",
        "AWS_DEFAULT_REGION",
        "AWS_CONFIG_FILE",
        "AWS_SHARED_CREDENTIALS_FILE",
    ] {
        command.env_remove(name);
    }
    let https = if source.endpoint.starts_with("http://") {
        "NO"
    } else {
        "YES"
    };
    command
        .env("AWS_REGION", REGION)
        .env("AWS_ACCESS_KEY_ID", &source.credentials.key_id)
        .env("AWS_SECRET_ACCESS_KEY", &source.credentials.secret)
        .env("AWS_S3_ENDPOINT", &source.host)
        .env("AWS_HTTPS", https)
        .env("AWS_VIRTUAL_HOSTING", "FALSE")
        .env("GDAL_HTTP_MULTIRANGE", "YES")
        .env("GDAL_DISABLE_READDIR_ON_OPEN", "EMPTY_DIR")
        .env("GDAL_HTTP_MAX_RETRY", LIST_ATTEMPTS.to_string())
        .env("GDAL_HTTP_RETRY_DELAY", RETRY_DELAY.to_string());
}

/// `<dest>.src`, recording the key and window of a clip.
fn src_of(dest: &Path) -> PathBuf {
    PathBuf::from(format!("{}.src", dest.display()))
}

/// The clip's record: `<key> <x0> <y0> <w> <h>`.
fn clip_record(key: &str, window: (i64, i64, u32, u32)) -> String {
    let (x0, y0, w, h) = window;
    format!("{key} {x0} {y0} {w} {h}")
}

/// Write `text` to `path` through `<path>.partial` and a rename.
pub(crate) fn write_atomic(path: &Path, text: &str) -> Result<()> {
    let partial = PathBuf::from(format!("{}.partial", path.display()));
    fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
    fs::rename(&partial, path).io_at(IoOp::RenameTo, path)
}

/// Read the window of `key` into `dest` with GDAL; `false` when GDAL failed.
fn clip_one(
    source: &Source,
    gdal: &Path,
    key: &str,
    dest: &Path,
    window: (i64, i64, u32, u32),
    out: &mut Vec<String>,
) -> Result<bool> {
    let name = dest
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let record = clip_record(key, window);
    let src = src_of(dest);
    if dest.is_file() && src.is_file() {
        let have = fs::read_to_string(&src).unwrap_or_default();
        if have.trim_end() == record {
            out.push(format!("SKIP {name}"));
            return Ok(true);
        }
    }
    if dest.is_file() {
        out.push(format!("RECLIP {name} (now {record})"));
    }
    let partial = PathBuf::from(format!("{}.partial", dest.display()));
    let _ = fs::remove_file(&partial);
    let (x0, y0, w, h) = window;
    let mut command = Command::new(gdal);
    clip_env(&mut command, source);
    command
        .arg("-q")
        .args(["-srcwin", &x0.to_string(), &y0.to_string()])
        .args([&w.to_string(), &h.to_string()])
        .arg("-of")
        .arg("COG")
        .args(["-co", "COMPRESS=DEFLATE", "-co", "PREDICTOR=2"])
        .args(["-co", &format!("BLOCKSIZE={BLOCKSIZE}")])
        .arg(format!("/vsis3/eodata/{key}"))
        .arg(&partial);
    let status = command.status();
    if status.is_ok_and(|status| status.success()) {
        let _ = fs::remove_file(&src);
        fs::rename(&partial, dest).io_at(IoOp::Rename, &partial)?;
        write_atomic(&src, &format!("{record}\n"))?;
        out.push(format!("OK {name}"));
        return Ok(true);
    }
    let _ = fs::remove_file(&partial);
    let _ = fs::remove_file(format!("{}.aux.xml", partial.display()));
    Ok(false)
}

/// Clip every file of `list` to `window`, into `dest_dir`.
///
/// # Errors
///
/// Fails with [`Exit`] `3` when GDAL is absent, `2` when the keys are absent,
/// and `1` when a clip fails, naming each key.
pub fn download_clip(list: &Path, dest_dir: &Path, window: (i64, i64, u32, u32)) -> Result<()> {
    if !gdal_available() {
        eprintln!("gdal_translate not found; the NDVI clip needs GDAL (brew install gdal)");
        return Err(DatasetError::Exit(Exit(3)));
    }
    let source = Source::new(&endpoint(), credentials()?)?;
    download_clip_with(&source, Path::new("gdal_translate"), list, dest_dir, window)
}

/// [`download_clip`] over a client and a GDAL path, for a test.
///
/// # Errors
///
/// Fails with [`Exit`] `1` when a clip fails, naming each key.
fn download_clip_with(
    source: &Source,
    gdal: &Path,
    list: &Path,
    dest_dir: &Path,
    window: (i64, i64, u32, u32),
) -> Result<()> {
    let text = fs::read_to_string(list).io_at(IoOp::Read, list)?;
    fs::create_dir_all(dest_dir).io_at(IoOp::Create, dest_dir)?;
    let mut failed: Vec<String> = Vec::new();
    let mut out = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some(entry) = list_line(line) else {
            eprintln!("bad list line: {line}");
            failed.push(line.to_owned());
            continue;
        };
        let dest = dest_dir.join(&entry.name);
        match clip_one(source, gdal, &entry.key, &dest, window, &mut out) {
            Ok(true) => {}
            Ok(false) => {
                eprintln!("{}: the clip failed", entry.name);
                failed.push(entry.key.clone());
            }
            Err(error) => {
                eprintln!("{error:#}");
                failed.push(entry.key.clone());
            }
        }
    }
    for line in &out {
        println!("{line}");
    }
    if failed.is_empty() {
        return Ok(());
    }
    for key in failed {
        println!("FAILED {key}");
    }
    Err(Exit(1).into())
}

/// A CDSE store client: the endpoint and the keys, opened once by the
/// streaming baseline pass, which downloads one file per step.
pub struct Client {
    source: Source,
}

impl Client {
    /// Open the store with the endpoint and the keys of the environment.
    ///
    /// # Errors
    ///
    /// Fails when the keys are absent or the credentials file is unreadable.
    pub fn open() -> Result<Self> {
        Ok(Self {
            source: Source::new(&endpoint(), credentials()?)?,
        })
    }

    /// Download `entry` whole into `dest_dir`.
    ///
    /// # Errors
    ///
    /// Fails when a window cannot be read after its attempts.
    pub fn download_entry(&self, entry: &ListLine, dest_dir: &Path) -> Result<()> {
        fs::create_dir_all(dest_dir).io_at(IoOp::Create, dest_dir)?;
        let dest = dest_dir.join(&entry.name);
        let mut out = Vec::new();
        download_one(
            &self.source,
            entry,
            &dest,
            CHUNK_BYTES,
            CHUNK_ATTEMPTS,
            &mut out,
        )?;
        for line in out {
            println!("{line}");
        }
        Ok(())
    }

    /// Clip `entry` to `window` into `dest_dir` with `gdal_translate`.
    ///
    /// # Errors
    ///
    /// Fails with [`Exit`] `1` when the clip fails, naming the file.
    pub fn clip_entry(
        &self,
        entry: &ListLine,
        dest_dir: &Path,
        window: (i64, i64, u32, u32),
    ) -> Result<()> {
        fs::create_dir_all(dest_dir).io_at(IoOp::Create, dest_dir)?;
        let dest = dest_dir.join(&entry.name);
        let mut out = Vec::new();
        if clip_one(
            &self.source,
            Path::new("gdal_translate"),
            &entry.key,
            &dest,
            window,
            &mut out,
        )? {
            for line in out {
                println!("{line}");
            }
            return Ok(());
        }
        eprintln!("{}: the clip failed", entry.name);
        Err(Exit(1).into())
    }

    /// Read one pixel of `entry` over `/vsis3/`: the pass's GDAL probe.
    ///
    /// # Errors
    ///
    /// Fails with [`Exit`] `3` naming the failing step.
    pub fn probe_entry(&self, entry: &ListLine, window: (i64, i64, u32, u32)) -> Result<()> {
        probe_entry_with(&self.source, Path::new("gdal_translate"), entry, window)
    }
}

/// Check GDAL and read one pixel of the first listed key over `/vsis3/`.
///
/// # Errors
///
/// Fails with [`Exit`] `3` naming the failing step, `2` when the list names
/// no file or the keys are absent.
pub fn probe(list: &Path, window: (i64, i64, u32, u32)) -> Result<()> {
    probe_with(Path::new("gdal_translate"), list, window)
}

/// [`probe`] over a GDAL path, for a test.
///
/// # Errors
///
/// Fails with [`Exit`] `3` naming the failing step.
fn probe_with(gdal: &Path, list: &Path, window: (i64, i64, u32, u32)) -> Result<()> {
    let text = fs::read_to_string(list).io_at(IoOp::Read, list)?;
    let Some(entry) = text
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty() && !line.starts_with('#'))
        .and_then(list_line)
    else {
        return Err(DatasetError::fetch(format!(
            "{} lists no file to probe",
            list.display()
        )));
    };
    let source = Source::new(&endpoint(), credentials()?)?;
    probe_entry_with(&source, gdal, &entry, window)
}

/// [`probe_with`] over one list entry.
///
/// # Errors
///
/// Fails with [`Exit`] `3` naming the failing step.
fn probe_entry_with(
    source: &Source,
    gdal: &Path,
    entry: &ListLine,
    window: (i64, i64, u32, u32),
) -> Result<()> {
    let Some(version) = gdal_version(gdal) else {
        eprintln!(
            "GDAL is broken: `gdal_translate --version` failed; fix GDAL (brew install gdal) and rerun"
        );
        return Err(DatasetError::Exit(Exit(3)));
    };
    let dir = std::env::temp_dir().join(format!("geolith-probe-{}", unix_seconds()));
    fs::create_dir_all(&dir).io_at(IoOp::Create, &dir)?;
    let target = dir.join("probe.tif");
    let (x0, y0, _, _) = window;
    let mut command = Command::new(gdal);
    clip_env(&mut command, source);
    let status = command
        .arg("-q")
        .args(["-srcwin", &x0.to_string(), &y0.to_string(), "1", "1"])
        .arg("-of")
        .arg("GTiff")
        .arg(format!("/vsis3/eodata/{}", entry.key))
        .arg(&target)
        .status();
    let _ = fs::remove_dir_all(&dir);
    if !status.is_ok_and(|status| status.success()) {
        eprintln!(
            "GDAL cannot read /vsis3/eodata/{} (one pixel); check GDAL and the CDSE keys, then rerun",
            entry.key
        );
        return Err(DatasetError::Exit(Exit(3)));
    }
    println!("PROBE OK {version}");
    Ok(())
}

/// Write the NDVI lists of a windowed dataset: the series range of the STAC,
/// then the dekads only S3 holds; returns the `lists` directory.
///
/// # Errors
///
/// Fails when the range, the catalogue, the S3 listing or a list write fails,
/// and when the keys the S3 fallback needs are absent.
pub fn source_lists(s: &Settings, quiet: bool) -> Result<PathBuf> {
    let lists = s
        .data_root
        .join("datasets")
        .join(&s.dataset)
        .join(&s.cc)
        .join("lists");
    fs::create_dir_all(&lists).io_at(IoOp::Create, &lists)?;
    let current = settings::current();
    let today = current
        .run
        .cdse_today
        .clone()
        .filter(|value| is_date(value))
        .unwrap_or_else(today_utc);
    let (from, to) = series_range(&today);
    let stac = current.sources.cdse_stac.as_deref().unwrap_or(DEFAULT_STAC);
    let text = list(&from, &to, stac)?.join("\n");
    let path = lists.join("series.txt");
    write_atomic(&path, &text)?;
    let prefixes = missing(&text, &from, &to, &today);
    if prefixes.is_empty() {
        return Ok(lists);
    }
    let source = Source::new(&endpoint(), credentials()?)?;
    let keys = s3_keys(&source, &prefixes)?;
    if keys.is_empty() {
        return Ok(lists);
    }
    let s3_text = keys
        .iter()
        .map(|(key, bytes)| format!("{key} {bytes}"))
        .collect::<Vec<_>>()
        .join("\n");
    let merged = merge(&text, &s3_text);
    write_atomic(&path, &merged)?;
    if !quiet {
        for line in merged.lines() {
            if line.starts_with("# ") && line.contains("from the S3 listing") {
                println!("{line}");
            }
        }
    }
    Ok(lists)
}

/// Run `geolith dataset cdse`.
///
/// # Errors
///
/// Fails with [`Exit`] `2` on a usage error, and when the catalogue, the
/// files or the grid cannot be read.
pub fn run(args: &CdseArgs) -> Result<()> {
    match &args.action {
        CdseAction::List(a) => list_verb(a),
        CdseAction::Missing(a) => missing_verb(a),
        CdseAction::Merge(a) => merge_verb(a),
        CdseAction::Ls(a) => ls_verb(a),
        CdseAction::SeriesRange(a) => series_range_verb(a),
        CdseAction::Window(a) => window_verb(a),
    }
}

/// `cdse list --from --to [--stac]`.
fn list_verb(args: &CdseListArgs) -> Result<()> {
    if !is_date(&args.from) || !is_date(&args.to) {
        eprintln!("list needs --from and --to as YYYY-MM-DD");
        return Err(DatasetError::Exit(Exit(2)));
    }
    let text = list(
        &args.from,
        &args.to,
        args.stac.as_deref().unwrap_or(DEFAULT_STAC),
    )?
    .join("\n");
    if !text.is_empty() {
        println!("{text}");
    }
    Ok(())
}

/// `cdse missing --list --from --to [--today]`.
fn missing_verb(args: &CdseMissingArgs) -> Result<()> {
    let today = args.today.clone().unwrap_or_else(today_utc);
    if !is_date(&args.from) || !is_date(&args.to) || !is_date(&today) {
        eprintln!("missing needs --from and --to (YYYY-MM-DD) [--today]");
        return Err(DatasetError::Exit(Exit(2)));
    }
    let text = fs::read_to_string(&args.list).io_at(IoOp::Read, &args.list)?;
    let found = missing(&text, &args.from, &args.to, &today);
    if !found.is_empty() {
        println!("{}", found.join("\n"));
    }
    Ok(())
}

/// `cdse merge --list --s3`.
fn merge_verb(args: &CdseMergeArgs) -> Result<()> {
    let list_text = fs::read_to_string(&args.list).io_at(IoOp::Read, &args.list)?;
    let s3_text = fs::read_to_string(&args.s3).io_at(IoOp::Read, &args.s3)?;
    let text = merge(&list_text, &s3_text);
    if !text.is_empty() {
        println!("{text}");
    }
    Ok(())
}

/// `cdse ls --prefixes`.
///
/// # Errors
///
/// Fails with [`Exit`] `2` when the keys are absent, and when the listing
/// cannot be read.
fn ls_verb(args: &CdseLsArgs) -> Result<()> {
    let text = fs::read_to_string(&args.prefixes).io_at(IoOp::Read, &args.prefixes)?;
    let prefixes: Vec<String> = text
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .map(str::to_owned)
        .collect();
    if prefixes.is_empty() {
        return Ok(());
    }
    let source = Source::new(&endpoint(), credentials()?)?;
    for (key, bytes) in s3_keys(&source, &prefixes)? {
        println!("{key} {bytes}");
    }
    Ok(())
}

/// `cdse series-range [--today]`.
fn series_range_verb(args: &CdseSeriesRangeArgs) -> Result<()> {
    let today = args.today.clone().unwrap_or_else(today_utc);
    if !is_date(&today) {
        eprintln!("--today must be YYYY-MM-DD");
        return Err(DatasetError::Exit(Exit(2)));
    }
    let (from, to) = series_range(&today);
    println!("{from} {to}");
    Ok(())
}

/// `cdse window --areas [--country] [--outline] [--grid] [--block]`.
fn window_verb(args: &CdseWindowArgs) -> Result<()> {
    let grid = match &args.grid {
        Some(text) => {
            let values: Vec<f64> = text
                .split(',')
                .filter_map(|value| value.trim().parse::<f64>().ok())
                .collect();
            if values.len() != 6 {
                eprintln!("--grid must be <x0>,<y0>,<px>,<py>,<width>,<height>");
                return Err(DatasetError::Exit(Exit(2)));
            }
            [
                values[0], values[1], values[2], values[3], values[4], values[5],
            ]
        }
        None => NDVI_GRID,
    };
    let (x0, y0, w, h) = window(
        &args.areas,
        args.outline.as_deref(),
        &args.country,
        grid,
        args.block,
    )?;
    println!("{x0} {y0} {w} {h}");
    Ok(())
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::settings::read_env_file;
    use std::io::{BufRead as _, BufReader};
    use std::net::{TcpListener, TcpStream};
    use std::os::unix::fs::PermissionsExt as _;
    use std::sync::{Arc, Mutex};

    /// A STAC item starting on `day`.
    fn item(day: &str, version: &str, size: u64) -> Value {
        let compact = day.replace('-', "");
        let (year, month, date) = (
            day.get(0..4).expect("year"),
            day.get(5..7).expect("month"),
            day.get(8..10).expect("day"),
        );
        let name = format!("c_gls_NDVI300_{compact}0000_GLOBE_OLCI_{version}");
        serde_json::json!({
            "id": format!("{name}_cog"),
            "properties": {
                "start_datetime": format!("{day}T00:00:00Z"),
                "processing:version": version,
            },
            "assets": {
                "ndvi": {
                    "href": format!("s3://eodata/{S3_ROOT}/{year}/{month}/{date}/{name}_cog/c_gls_NDVI300-NDVI_{compact}0000_GLOBE_OLCI_{version}.tiff"),
                    "file:size": size,
                },
            },
        })
    }

    /// The key of an item built by [`item`].
    fn key_of(item: &Value) -> String {
        item["assets"]["ndvi"]["href"]
            .as_str()
            .expect("href")
            .trim_start_matches("s3://eodata/")
            .to_owned()
    }

    /// A STAC host serving `pages`; page n links `rel=next` to page n+1.
    /// Returns the origin and every request target seen.
    fn stac_server(pages: Vec<Vec<Value>>) -> (String, Arc<Mutex<Vec<String>>>) {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let address = listener.local_addr().expect("address").to_string();
        let origin = address.clone();
        let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let shared = Arc::clone(&seen);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(stream) = stream else { continue };
                let pages = pages.clone();
                let address = address.clone();
                let shared = Arc::clone(&shared);
                std::thread::spawn(move || {
                    let _ = serve_stac(stream, &pages, &address, &shared);
                });
            }
        });
        (format!("http://{origin}/v1"), seen)
    }

    fn serve_stac(
        mut stream: TcpStream,
        pages: &[Vec<Value>],
        address: &str,
        seen: &Arc<Mutex<Vec<String>>>,
    ) -> std::io::Result<()> {
        let mut reader = BufReader::new(stream.try_clone()?);
        let mut line = String::new();
        reader.read_line(&mut line)?;
        let target = line
            .split_whitespace()
            .nth(1)
            .unwrap_or_default()
            .to_owned();
        loop {
            let mut header = String::new();
            reader.read_line(&mut header)?;
            if header.trim().is_empty() {
                break;
            }
        }
        seen.lock().expect("seen").push(target.clone());
        let page: usize = target
            .split("page=")
            .nth(1)
            .and_then(|rest| rest.split('&').next())
            .and_then(|value| value.parse().ok())
            .unwrap_or(0);
        let features = pages.get(page).cloned().unwrap_or_default();
        let links = if page + 1 < pages.len() {
            format!(
                r#"[{{"rel":"next","href":"http://{address}/v1/collections/{COLLECTION}/items?page={}"}}]"#,
                page + 1
            )
        } else {
            "[]".to_owned()
        };
        let body = format!(
            r#"{{"type":"FeatureCollection","features":{},"links":{links}}}"#,
            serde_json::to_string(&features).expect("features")
        );
        let head = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/geo+json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
            body.len()
        );
        stream.write_all(head.as_bytes())?;
        stream.write_all(body.as_bytes())?;
        stream.flush()
    }

    /// One request the fake store saw.
    #[derive(Debug, Clone)]
    pub(crate) struct Record {
        pub(crate) target: String,
        pub(crate) range: Option<String>,
        authorization: String,
    }

    /// A CDSE-shaped store: `objects` by key, listings by prefix.
    pub(crate) struct Store {
        source: Source,
        pub(crate) log: Arc<Mutex<Vec<Record>>>,
    }

    impl Store {
        /// A streaming client of this store.
        pub(crate) fn client(&self) -> Client {
            Client {
                source: Source::new(&self.source.endpoint, self.source.credentials.clone())
                    .expect("a fake store is a URL"),
            }
        }
    }

    pub(crate) fn store(objects: Vec<(String, Vec<u8>)>, listings: Vec<(String, String)>) -> Store {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let address = listener.local_addr().expect("address").to_string();
        let log: Arc<Mutex<Vec<Record>>> = Arc::new(Mutex::new(Vec::new()));
        let objects: Arc<BTreeMap<String, Vec<u8>>> = Arc::new(objects.into_iter().collect());
        let listings: Arc<BTreeMap<String, String>> = Arc::new(listings.into_iter().collect());
        let shared = Arc::clone(&log);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(stream) = stream else { continue };
                let objects = Arc::clone(&objects);
                let listings = Arc::clone(&listings);
                let shared = Arc::clone(&shared);
                std::thread::spawn(move || {
                    let _ = serve_store(stream, &objects, &listings, &shared);
                });
            }
        });
        let source = Source::new(
            &format!("http://{address}"),
            Credentials {
                key_id: "AKIACDSETESTKEY".to_owned(),
                secret: "SEKRET-cdse-never-printed".to_owned(),
            },
        )
        .expect("a fake store is a URL");
        Store { source, log }
    }

    fn serve_store(
        mut stream: TcpStream,
        objects: &BTreeMap<String, Vec<u8>>,
        listings: &BTreeMap<String, String>,
        log: &Arc<Mutex<Vec<Record>>>,
    ) -> std::io::Result<()> {
        let mut reader = BufReader::new(stream.try_clone()?);
        let mut line = String::new();
        reader.read_line(&mut line)?;
        let target = line
            .split_whitespace()
            .nth(1)
            .unwrap_or_default()
            .to_owned();
        let (mut range, mut authorization) = (None, String::new());
        loop {
            let mut header = String::new();
            reader.read_line(&mut header)?;
            if header.trim().is_empty() {
                break;
            }
            let lower = header.to_ascii_lowercase();
            if let Some(value) = lower.strip_prefix("range:") {
                range = Some(value.trim().to_owned());
            }
            if lower.starts_with("authorization:") {
                authorization = header
                    .split_once(':')
                    .map(|(_, value)| value.trim().to_owned())
                    .unwrap_or_default();
            }
        }
        log.lock().expect("log").push(Record {
            target: target.clone(),
            range: range.clone(),
            authorization,
        });
        let (status, body): (&str, Vec<u8>) = if target.starts_with("/eodata?") {
            let prefix = target
                .split("prefix=")
                .nth(1)
                .and_then(|rest| rest.split('&').next())
                .map(|value| value.replace("%2F", "/").replace("%2f", "/"))
                .unwrap_or_default();
            let body = listings.get(&prefix).cloned().unwrap_or_default();
            ("200 OK", body.into_bytes())
        } else if let Some(key) = target.strip_prefix("/eodata/") {
            let bytes = objects.get(key).cloned().unwrap_or_default();
            match range.as_deref().map(parse_range) {
                Some(Some((start, end))) => {
                    let start = start.min(bytes.len());
                    let end = (end + 1).min(bytes.len());
                    ("206 Partial Content", bytes[start..end].to_vec())
                }
                _ => ("200 OK", bytes),
            }
        } else {
            ("404 Not Found", Vec::new())
        };
        let head = format!(
            "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
            body.len()
        );
        stream.write_all(head.as_bytes())?;
        stream.write_all(&body)?;
        stream.flush()
    }

    /// `bytes=<start>-<end>` to its two numbers.
    fn parse_range(text: &str) -> Option<(usize, usize)> {
        let rest = text.trim().strip_prefix("bytes=")?;
        let (start, end) = rest.split_once('-')?;
        Some((start.parse().ok()?, end.parse().ok()?))
    }

    #[test]
    fn a_stac_page_names_the_dekads_in_name_order() {
        let (a, b, c) = (
            item("2026-09-01", "V3.0.1", 1_250_000_001),
            item("2026-09-11", "V3.0.1", 1_250_000_002),
            item("2026-09-21", "V3.0.1", 1_250_000_003),
        );
        let (origin, seen) = stac_server(vec![vec![c.clone(), a.clone()], vec![b.clone()]]);
        let lines = list("2026-09-01", "2026-09-30", &origin).expect("list");
        assert_eq!(
            lines,
            [
                format!("final {} ndvi300-v3.2026.09.1.tif 1250000001", key_of(&a)),
                format!("final {} ndvi300-v3.2026.09.2.tif 1250000002", key_of(&b)),
                format!("final {} ndvi300-v3.2026.09.3.tif 1250000003", key_of(&c)),
            ]
        );
        let seen = seen.lock().expect("seen");
        assert!(
            seen[0].starts_with(&format!(
                "/v1/collections/{COLLECTION}/items?datetime=2026-09-01T00%3A00%3A00Z%2F2026-09-30T23%3A59%3A59Z&limit=100"
            )),
            "{}",
            seen[0]
        );
        assert!(seen.iter().any(|target| target.contains("page=1")));
    }

    #[test]
    fn a_reprocessed_dekad_keeps_the_larger_version() {
        let old = item("2025-12-21", "V3.0.1", 100);
        let newer = item("2025-12-21", "V3.0.10", 200);
        let (origin, _) = stac_server(vec![vec![newer.clone(), old.clone()]]);
        let lines = list("2025-12-21", "2025-12-31", &origin).expect("list");
        assert_eq!(
            lines,
            [
                format!(
                    "# ndvi300-v3.2025.12.3.tif: {} (V3.0.1) replaced by V3.0.10",
                    key_of(&old)
                ),
                format!("final {} ndvi300-v3.2025.12.3.tif 200", key_of(&newer)),
            ]
        );
    }

    #[test]
    fn an_item_that_is_not_a_dekad_start_is_named() {
        let mut bad = item("2026-09-05", "V3.0.1", 7);
        bad["id"] = Value::String("c_gls_NDVI300_20260905".to_owned());
        let (origin, _) = stac_server(vec![vec![bad]]);
        let error = list("2026-09-01", "2026-09-30", &origin).expect_err("a failure");
        assert!(
            error.to_string().contains("c_gls_NDVI300_20260905"),
            "{error}"
        );
    }

    #[test]
    fn missing_lists_only_the_dekads_the_catalogue_lacks() {
        let list_text = [
            ListLine {
                key: "a".to_owned(),
                name: "ndvi300-v3.2026.10.1.tif".to_owned(),
                bytes: 9,
            }
            .final_line(),
            ListLine {
                key: "b".to_owned(),
                name: "ndvi300-v3.2026.10.2.tif".to_owned(),
                bytes: 9,
            }
            .final_line(),
        ]
        .join("\n");
        assert_eq!(
            missing(&list_text, "2026-10-01", "2026-11-20", "2026-11-18"),
            [
                format!("{S3_ROOT}/2026/10/21/"),
                format!("{S3_ROOT}/2026/11/01/"),
                format!("{S3_ROOT}/2026/11/11/"),
            ]
        );
        assert!(missing(&list_text, "2026-10-01", "2026-10-20", "2026-11-18").is_empty());
        // A dekad that starts after today is never listed.
        assert!(missing(&list_text, "2026-10-01", "2026-11-20", "2026-10-11").is_empty());
    }

    #[test]
    fn merge_fills_only_the_missing_dekads_and_keeps_the_newest_version() {
        let listed = ListLine {
            key: format!(
                "{S3_ROOT}/2026/10/11/x_cog/c_gls_NDVI300-NDVI_202610110000_GLOBE_OLCI_V3.0.1.tiff"
            ),
            name: "ndvi300-v3.2026.10.2.tif".to_owned(),
            bytes: 9,
        };
        let dir = |day: &str, version: &str| {
            let compact = day.replace('-', "");
            let year = &day[0..4];
            let month = &day[5..7];
            let date = &day[8..10];
            format!(
                "{S3_ROOT}/{year}/{month}/{date}/c_gls_NDVI300_{compact}0000_GLOBE_OLCI_{version}"
            )
        };
        let s3 = [
            format!(
                "{}_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff 1151405426",
                dir("2026-10-21", "V3.0.1")
            ),
            format!(
                "{}_cog/c_gls_NDVI300-NOBS_202610210000_GLOBE_OLCI_V3.0.1.tiff 250690453",
                dir("2026-10-21", "V3.0.1")
            ),
            format!(
                "{}_nc/c_gls_NDVI300_202610210000_GLOBE_OLCI_V3.0.1.nc 2583893193",
                dir("2026-10-21", "V3.0.1")
            ),
            format!(
                "{}_cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.1.tiff 1078825184",
                dir("2026-11-01", "V3.0.1")
            ),
            format!(
                "{}_cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.2.tiff 1078825185",
                dir("2026-11-01", "V3.0.2")
            ),
            // A dekad already in the list is never replaced from S3.
            format!(
                "{}_cog/c_gls_NDVI300-NDVI_202610110000_GLOBE_OLCI_V3.0.9.tiff 5",
                dir("2026-10-11", "V3.0.9")
            ),
        ]
        .join("\n");
        let merged = merge(&listed.final_line(), &s3);
        let finals: Vec<&str> = merged
            .lines()
            .filter(|line| line.starts_with("final "))
            .collect();
        assert_eq!(
            finals,
            [
                listed.final_line(),
                format!(
                    "final {}_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff ndvi300-v3.2026.10.3.tif 1151405426",
                    dir("2026-10-21", "V3.0.1")
                ),
                format!(
                    "final {}_cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.2.tiff ndvi300-v3.2026.11.1.tif 1078825185",
                    dir("2026-11-01", "V3.0.2")
                ),
            ]
        );
        assert!(
            merged
                .contains("# ndvi300-v3.2026.10.3.tif: from the S3 listing (not in the STAC yet)"),
            "{merged}"
        );
        assert_eq!(merge(&listed.final_line(), ""), listed.final_line());
    }

    #[test]
    fn the_series_is_the_current_dekad_and_the_twelve_before_it() {
        assert_eq!(
            series_range("2026-11-18"),
            ("2026-07-11".to_owned(), "2026-11-20".to_owned())
        );
        assert_eq!(
            series_range("2026-01-31"),
            ("2025-09-21".to_owned(), "2026-01-31".to_owned())
        );
        assert_eq!(
            series_range("2026-11-22"),
            ("2026-07-21".to_owned(), "2026-11-30".to_owned())
        );
    }

    /// A square `[x0, y0]`–`[x1, y1]` polygon.
    fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Value {
        serde_json::json!({
            "type": "Polygon",
            "coordinates": [[[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]],
        })
    }

    /// Write `areas` and an outline of one feature; returns both paths.
    fn window_files(dir: &Path, areas: Value, outline: Value) -> (PathBuf, PathBuf) {
        let areas_path = dir.join("areas.geojson");
        let outline_path = dir.join("outline.geojson");
        fs::write(
            &areas_path,
            serde_json::json!({"type": "FeatureCollection", "features": areas}).to_string(),
        )
        .expect("areas");
        fs::write(
            &outline_path,
            serde_json::json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": outline}]})
                .to_string(),
        )
        .expect("outline");
        (areas_path, outline_path)
    }

    #[test]
    fn the_window_is_the_country_bbox_snapped_out_to_the_block_grid() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let areas = serde_json::json!([
            {"type": "Feature", "properties": {"country": "IN"}, "geometry": square(74.1, 28.1, 76.0, 29.9)},
            {"type": "Feature", "properties": {"country": "IN"}, "geometry": {
                "type": "MultiPolygon",
                "coordinates": [square(75.0, 29.0, 77.9, 29.5)["coordinates"].clone()],
            }},
            // Another country never widens the window.
            {"type": "Feature", "properties": {"country": "NP"}, "geometry": square(80.0, 21.0, 85.0, 35.0)},
        ]);
        let (areas_path, outline_path) =
            window_files(dir.path(), areas, square(75.0, 29.0, 76.0, 29.5));
        let grid = [70.0, 36.0, 0.25, -0.25, 64.0, 64.0];
        assert_eq!(
            window(&areas_path, Some(&outline_path), "IN", grid, 16).expect("window"),
            (0, 16, 48, 32)
        );
        let (areas_path, outline_path) = window_files(
            dir.path(),
            serde_json::json!([
                {"type": "Feature", "properties": {"country": "IN"}, "geometry": square(74.1, 28.1, 76.0, 29.9)},
            ]),
            square(75.0, 29.0, 79.0, 34.5),
        );
        assert_eq!(
            window(&areas_path, Some(&outline_path), "IN", grid, 16).expect("window"),
            (0, 0, 48, 48)
        );
    }

    #[test]
    fn an_india_window_needs_the_survey_of_india_outline() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let (areas_path, _) = window_files(
            dir.path(),
            serde_json::json!([
                {"type": "Feature", "properties": {"country": "IN"}, "geometry": square(74.1, 28.1, 76.0, 29.9)},
            ]),
            square(75.0, 29.0, 76.0, 29.5),
        );
        let error = window(&areas_path, None, "IN", NDVI_GRID, 512).expect_err("a refusal");
        assert!(
            error
                .to_string()
                .contains("window for IN needs --outline <Survey of India GeoJSON>"),
            "{error}"
        );
    }

    /// One list file of one dekad of `bytes` bytes.
    fn one_line(dir: &Path, key: &str, name: &str, bytes: u64) -> PathBuf {
        let path = dir.join("series.txt");
        fs::write(
            &path,
            ListLine {
                key: key.to_owned(),
                name: name.to_owned(),
                bytes,
            }
            .final_line(),
        )
        .expect("write");
        path
    }

    /// `size` bytes of a repeating pattern.
    pub(crate) fn object(size: usize) -> Vec<u8> {
        (0..size)
            .map(|index| u8::try_from(index % 251).unwrap_or_default())
            .collect()
    }

    #[test]
    fn a_whole_file_is_fetched_in_closed_windows() {
        let bytes = object(300);
        let store = store(vec![("k/ndvi.tiff".to_owned(), bytes.clone())], Vec::new());
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 300);
        let dest = dir.path().join("final");
        download_full_with(&store.source, &list, &dest, 128, 2).expect("download");
        assert_eq!(
            fs::read(dest.join("ndvi300-v3.2026.10.1.tif")).expect("read"),
            bytes
        );
        let log = store.log.lock().expect("log");
        let ranges: Vec<Option<String>> = log.iter().map(|record| record.range.clone()).collect();
        assert_eq!(
            ranges,
            [
                Some("bytes=0-127".to_owned()),
                Some("bytes=128-255".to_owned()),
                Some("bytes=256-299".to_owned()),
            ]
        );
    }

    #[test]
    fn a_resumed_part_asks_for_the_rest_only() {
        let bytes = object(200);
        let store = store(vec![("k/ndvi.tiff".to_owned(), bytes.clone())], Vec::new());
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 200);
        let dest = dir.path().join("final/ndvi300-v3.2026.10.1.tif");
        fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
        fs::write(part_of(&dest), &bytes[..100]).expect("write");
        download_full_with(&store.source, &list, dest.parent().expect("parent"), 128, 2)
            .expect("download");
        assert_eq!(fs::read(&dest).expect("read"), bytes);
        let log = store.log.lock().expect("log");
        assert_eq!(log[0].range.as_deref(), Some("bytes=100-199"));
    }

    #[test]
    fn a_part_longer_than_the_listing_is_discarded() {
        let bytes = object(120);
        let store = store(vec![("k/ndvi.tiff".to_owned(), bytes.clone())], Vec::new());
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 120);
        let dest = dir.path().join("final/ndvi300-v3.2026.10.1.tif");
        fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
        fs::write(part_of(&dest), vec![9_u8; 400]).expect("write");
        download_full_with(&store.source, &list, dest.parent().expect("parent"), 128, 2)
            .expect("download");
        assert_eq!(fs::read(&dest).expect("read"), bytes);
        let log = store.log.lock().expect("log");
        assert_eq!(log[0].range.as_deref(), Some("bytes=0-119"));
    }

    #[test]
    fn the_secret_never_reaches_a_line_or_a_header_value() {
        let bytes = object(64);
        let store = store(vec![("k/ndvi.tiff".to_owned(), bytes)], Vec::new());
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 64);
        download_full_with(&store.source, &list, &dir.path().join("final"), 128, 1)
            .expect("download");
        let entries = fs::read_dir(dir.path().join("final")).expect("the dir");
        for entry in entries {
            let entry = entry.expect("an entry");
            let text = String::from_utf8_lossy(&fs::read(entry.path()).expect("read")).into_owned();
            assert!(!text.contains("SEKRET-cdse-never-printed"));
        }
        let log = store.log.lock().expect("log");
        for record in log.iter() {
            assert!(
                !record.authorization.contains("SEKRET-cdse-never-printed"),
                "{}",
                record.target
            );
            assert!(record.authorization.contains("AKIACDSETESTKEY"));
        }
        let credentials = Credentials {
            key_id: "id".to_owned(),
            secret: "SEKRET-cdse-never-printed".to_owned(),
        };
        assert!(!format!("{credentials:?}").contains("SEKRET-cdse-never-printed"));
    }

    #[test]
    fn a_credentials_file_wider_than_six_hundred_is_refused() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("cdse.env");
        fs::write(
            &path,
            "export CDSE_S3_ACCESS_KEY = \"AKIAEXAMPLE\"\nCDSE_S3_SECRET_KEY='s3cret'\n",
        )
        .expect("write");
        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("chmod");
        let values = read_env_file(&path).expect("a 600 file is read");
        assert_eq!(
            values.get("CDSE_S3_ACCESS_KEY").map(String::as_str),
            Some("AKIAEXAMPLE")
        );
        assert_eq!(
            values.get("CDSE_S3_SECRET_KEY").map(String::as_str),
            Some("s3cret")
        );
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("chmod");
        let error = read_env_file(&path).expect_err("a 644 file is refused");
        assert!(error.to_string().contains("chmod 600"), "{error}");
    }

    #[test]
    fn merge_lists_the_prefix_when_the_store_holds_the_dekad() {
        let store = store(
            Vec::new(),
            vec![(
                format!("{S3_ROOT}/2026/10/21/"),
                format!(
                    "<ListBucketResult><IsTruncated>false</IsTruncated><Contents><Key>{S3_ROOT}/2026/10/21/x_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff</Key><Size>42</Size></Contents></ListBucketResult>"
                ),
            )],
        );
        let keys = s3_keys(&store.source, &[format!("{S3_ROOT}/2026/10/21/")]).expect("listing");
        assert_eq!(
            keys,
            [(
                format!(
                    "{S3_ROOT}/2026/10/21/x_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff"
                ),
                42
            )]
        );
    }

    /// A temp dir holding a `gdal_translate` that records its argv and the
    /// key it was handed through its environment.
    fn fake_gdal(dir: &Path) -> PathBuf {
        let path = dir.join("gdal_translate");
        fs::write(
            &path,
            "#!/bin/sh\n\
             d=$(dirname \"$0\")\n\
             printf '%s\\n' \"$@\" >\"$d/argv.txt\"\n\
             printf '%s\\n' \"$AWS_SECRET_ACCESS_KEY\" \"$AWS_S3_ENDPOINT\" >\"$d/env.txt\"\n\
             for a in \"$@\"; do last=$a; done\n\
             printf 'COG' >\"$last\"\n\
             exit 0\n",
        )
        .expect("script");
        fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod");
        path
    }

    #[test]
    fn a_clip_hands_the_window_on_argv_and_the_keys_in_the_environment() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let gdal = fake_gdal(dir.path());
        let source = Source::new(
            "https://eodata.example",
            Credentials {
                key_id: "AKIACDSETESTKEY".to_owned(),
                secret: "SEKRET-cdse-never-printed".to_owned(),
            },
        )
        .expect("a URL");
        let dest = dir.path().join("final/ndvi300-v3.2026.10.1.tif");
        fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
        let mut out = Vec::new();
        let ok = clip_one(
            &source,
            &gdal,
            "k/ndvi.tiff",
            &dest,
            (10, 20, 512, 512),
            &mut out,
        )
        .expect("clip");
        assert!(ok);
        assert_eq!(out, ["OK ndvi300-v3.2026.10.1.tif"]);
        let argv = fs::read_to_string(dir.path().join("argv.txt")).expect("argv");
        assert!(argv.contains("-srcwin\n10\n20\n512\n512\n"), "{argv}");
        assert!(argv.contains("/vsis3/eodata/k/ndvi.tiff"), "{argv}");
        assert!(!argv.contains("SEKRET-cdse-never-printed"), "{argv}");
        let env = fs::read_to_string(dir.path().join("env.txt")).expect("env");
        assert!(env.contains("SEKRET-cdse-never-printed"), "{env}");
        assert!(env.contains("eodata.example"), "{env}");
        let sidecar = fs::read_to_string(src_of(&dest)).expect("the record");
        assert_eq!(sidecar.trim_end(), "k/ndvi.tiff 10 20 512 512");
        assert!(!sidecar.contains("SEKRET"));
        // A second run of the same record is a skip, and changes nothing.
        let mut again = Vec::new();
        assert!(
            clip_one(
                &source,
                &gdal,
                "k/ndvi.tiff",
                &dest,
                (10, 20, 512, 512),
                &mut again
            )
            .expect("clip")
        );
        assert_eq!(again, ["SKIP ndvi300-v3.2026.10.1.tif"]);
    }

    #[test]
    fn an_absent_gdal_is_a_refusal_naming_the_tool() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 8);
        let text = fs::read_to_string(&list).expect("read the list");
        let entry = text
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty() && !line.starts_with('#'))
            .and_then(list_line)
            .expect("a list line");
        // Keys of its own: the test never depends on the machine's settings.
        let source = Source::new(
            "https://eodata.example",
            Credentials {
                key_id: "AKIACDSETESTKEY".to_owned(),
                secret: "SEKRET-cdse-never-printed".to_owned(),
            },
        )
        .expect("a URL");
        let error = probe_entry_with(
            &source,
            Path::new("/nonexistent/gdal_translate"),
            &entry,
            (0, 0, 512, 512),
        )
        .expect_err("a refusal");
        assert_eq!(error.exit(), Some(Exit(3)));
        assert!(error.to_string().contains("exit 3"), "{error}");
    }

    #[test]
    fn a_bad_list_line_is_named_and_fails() {
        let store = store(Vec::new(), Vec::new());
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = dir.path().join("series.txt");
        fs::write(&list, "midday k/ndvi.tiff x.tif 8\n").expect("write");
        let error = download_full_with(&store.source, &list, &dir.path().join("final"), 128, 1)
            .expect_err("a failure");
        assert_eq!(error.exit(), Some(Exit(1)));
        assert!(store.log.lock().expect("log").is_empty());
    }
}