sugarrush 2026.8.3

A terminal UI for viewing Nightscout CGM (blood glucose sensor) data
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
//! Config loading from ~/.config/sugarrush/config.toml.

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::theme::ThemeConfig;
use crate::units::Units;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Base URL of the single Nightscout instance (legacy single-site form).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Read-only token for the single-site form.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    /// One or more named sites (multi-site form). Takes precedence over the
    /// top-level `url`/`token` when non-empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sites: Vec<Site>,
    #[serde(default = "default_units")]
    pub units: Units,
    #[serde(default = "default_refresh")]
    pub refresh_secs: u64,
    #[serde(default)]
    pub alerts: AlertsConfig,
    #[serde(default, skip_serializing_if = "is_default_theme")]
    pub theme: ThemeConfig,
    /// How the graph draws readings.
    #[serde(default)]
    pub graph_style: GraphStyle,
    /// How many days of history the AGP view folds over.
    #[serde(default = "default_agp_days")]
    pub agp_days: u32,
    /// How many days a sensor is expected to last, so its age can be read as
    /// time remaining. A G6/G7 runs 10, a Libre 14; `0` means the sensor is
    /// never called expiring, for uploaders that log no sensor change at all.
    #[serde(default = "default_sensor_days")]
    pub sensor_days: u32,
    /// Minimap navigator settings.
    #[serde(default)]
    pub minimap: MinimapConfig,
    /// Optional private local history for outage context and instant startup.
    #[serde(default)]
    pub history_cache: HistoryCacheConfig,
    /// Which parts of a reading a status bar draws.
    #[serde(default)]
    pub bar: BarConfig,
    /// Whether `treatment --non-interactive` may write without a human.
    ///
    /// Off by default, and deliberately a config key rather than a flag: the
    /// interactive path is guarded by typing the person's name, and the
    /// unattended path skips that by construction. Requiring the grant to exist
    /// at rest means a careless script — or anything that can compose a command
    /// line on this machine — cannot reach a health-record write just because
    /// the binary is installed. Turning it on is a decision someone makes once,
    /// in a file they own, and `sugarrush about` reports it.
    #[serde(default, skip_serializing_if = "is_false")]
    pub allow_unattended_writes: bool,
}

fn is_false(value: &bool) -> bool {
    !*value
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct HistoryCacheConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_cache_days")]
    pub retention_days: u32,
}

impl Default for HistoryCacheConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            retention_days: default_cache_days(),
        }
    }
}

fn default_cache_days() -> u32 {
    14
}

/// The 24h (configurable) overview strip and its mouse navigation.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct MinimapConfig {
    /// Show the strip and enable mouse capture (drag to pan, click to jump).
    #[serde(default = "minimap_enabled")]
    pub enabled: bool,
    /// Width of the overview window in hours.
    #[serde(default = "minimap_span")]
    pub span_hours: u32,
}

impl Default for MinimapConfig {
    fn default() -> Self {
        Self {
            enabled: minimap_enabled(),
            span_hours: minimap_span(),
        }
    }
}

fn minimap_enabled() -> bool {
    true
}
fn minimap_span() -> u32 {
    24
}

/// Which parts of a reading a status bar is given.
///
/// A bar is the one place a reading is read at a glance and out of the corner
/// of an eye, and four facts crowded into a pill is three too many for some
/// people. Each part is dropped at the source rather than left to the bar to
/// hide, so every format agrees about what the reading says.
///
/// `units` and `sparkline` reach only the JSON payload: the plain, polybar,
/// tmux and i3blocks lines have never carried a unit and no text format draws
/// a trace, so switching them on cannot add anything there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BarConfig {
    /// The trend arrow after the reading.
    #[serde(default = "bar_part")]
    pub arrow: bool,
    /// The change since the previous reading.
    #[serde(default = "bar_part")]
    pub delta: bool,
    /// The unit label, for a bar that renders one (JSON only).
    #[serde(default = "bar_part")]
    pub units: bool,
    /// The last hour, for a bar that draws it (JSON only).
    #[serde(default = "bar_part")]
    pub sparkline: bool,
}

impl Default for BarConfig {
    fn default() -> Self {
        Self {
            arrow: bar_part(),
            delta: bar_part(),
            units: bar_part(),
            sparkline: bar_part(),
        }
    }
}

fn bar_part() -> bool {
    true
}

/// Marker style for the graph's readings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GraphStyle {
    /// Thin connected braille line.
    Line,
    /// Discrete medium dots (default).
    #[default]
    Dots,
    /// Discrete chunky blocks.
    Blocks,
}

impl GraphStyle {
    /// Cycle to the next/previous style.
    pub fn cycle(self, dir: i32) -> Self {
        let order = [GraphStyle::Line, GraphStyle::Dots, GraphStyle::Blocks];
        let idx = order.iter().position(|&s| s == self).unwrap_or(0) as i32;
        order[(idx + dir).rem_euclid(order.len() as i32) as usize]
    }

    pub fn label(self) -> &'static str {
        match self {
            GraphStyle::Line => "line",
            GraphStyle::Dots => "dots",
            GraphStyle::Blocks => "blocks",
        }
    }
}

/// A named Nightscout site.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Site {
    /// Immutable internal identity. Names are editable labels and must never
    /// key private data or alarm continuity.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub id: String,
    #[serde(default = "default_site_name")]
    pub name: String,
    pub url: String,
    pub token: String,
    /// Optional careportal token used only for explicitly confirmed treatment
    /// writes. Reads always continue to use `token`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_token: Option<String>,
    /// IANA timezone for this person's AGP and clinical exports. Viewer-local
    /// time remains the backward-compatible default when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// Optional complete alert settings for this person. When absent, the
    /// top-level `[alerts]` settings apply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alerts: Option<AlertsConfig>,
}

impl Site {
    pub fn stable_id(&self) -> String {
        if uuid::Uuid::parse_str(&self.id).is_ok() {
            self.id.clone()
        } else {
            uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, self.base_url().as_bytes()).to_string()
        }
    }
    /// Trimmed base URL without a trailing slash.
    pub fn base_url(&self) -> &str {
        self.url.trim_end_matches('/')
    }

    /// True when the token travels in clear text: plain `http://` to anything
    /// but the local machine. The token is a query parameter, so anyone on the
    /// path can read it (and the glucose data with it).
    pub fn is_insecure(&self) -> bool {
        is_insecure_url(self.base_url())
    }

    pub fn resolve_alerts(&self, global: &AlertsConfig, units: Units) -> (Alerts, Vec<String>) {
        self.alerts
            .as_ref()
            .map(|local| local.resolve_checked(units))
            .unwrap_or_else(|| global.resolve_checked(units))
    }
}

/// True when a webhook URL would send the alert in clear text.
///
/// `push_url` had none of the scrutiny the site URL gets — no wizard gate, no
/// settings warning, no footer banner — despite being the one channel that
/// leaves the machine. The documented example is a public ntfy topic, where
/// anyone who learns the topic name is subscribed to a stranger's
/// hypoglycaemia; over plain http it's readable by the network too.
pub fn is_insecure_url(url: &str) -> bool {
    let url = url.trim().trim_end_matches('/');
    let Some(rest) = url.strip_prefix("http://") else {
        return false;
    };
    let host = rest.split('/').next().unwrap_or("");
    let host = host.split(':').next().unwrap_or(host);
    !matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]")
}

/// Clean up a Nightscout URL as typed: trim it, default the scheme to HTTPS,
/// drop a trailing slash, and strip an API path if one was pasted along.
///
/// People copy the URL out of a browser tab that's showing
/// `…/api/v1/entries.json?count=10`, or type a bare `mysite.herokuapp.com`.
/// Both are unambiguous — accept them rather than failing a live-test with a
/// confusing 404.
pub fn normalize_site_url(input: &str) -> Result<String> {
    let raw = input.trim();
    if raw.is_empty() {
        bail!("the URL is empty");
    }
    // Resolve the scheme first: trimming slashes before this would turn a bare
    // "https://" into the hostname "https:".
    let mut s = match raw.split_once("://") {
        Some((scheme, rest)) if scheme.eq_ignore_ascii_case("https") => {
            format!("https://{rest}")
        }
        Some((scheme, rest)) if scheme.eq_ignore_ascii_case("http") => format!("http://{rest}"),
        Some((scheme, _)) => bail!("unsupported scheme '{scheme}://' — use https://"),
        // A bare host: assume HTTPS rather than silently downgrading.
        None => format!("https://{raw}"),
    };
    // Strip a pasted API path: everything from `/api/` onwards belongs to the
    // client, not the base URL.
    if let Some(idx) = s.to_lowercase().find("/api/") {
        s.truncate(idx);
    } else if s.to_lowercase().ends_with("/api") {
        s.truncate(s.len() - 4);
    }
    let s = s.trim_end_matches('/').to_string();
    let host = s
        .split_once("://")
        .map(|(_, rest)| rest.split('/').next().unwrap_or(""))
        .unwrap_or("");
    if host.is_empty() {
        bail!("no host in '{input}'");
    }
    Ok(s)
}

/// Alert thresholds as written in config.toml. Glucose bounds are expressed in
/// the configured display `units`; omitted fields fall back to unit-independent
/// physiological defaults. Call [`AlertsConfig::resolve`] to get mg/dL values.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AlertsConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urgent_low: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub low: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub high: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urgent_high: Option<f64>,
    /// Warn when the newest reading is older than this many minutes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stale_minutes: Option<i64>,
    /// Fire desktop notifications on threshold crossings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub desktop: Option<bool>,
    /// Play a looping audible alarm on urgent/stale states.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sound: Option<bool>,
    /// Also show urgent alerts on Omarchy's on-screen display, which no
    /// notification policy can suppress. Ignored where that shell is absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub osd: Option<bool>,
    /// How long the snooze key silences the audible alarm, in minutes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snooze_minutes: Option<i64>,
    /// Start of the quiet-hours window, `HH:MM` (empty/absent = disabled).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quiet_start: Option<String>,
    /// End of the quiet-hours window, `HH:MM`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quiet_end: Option<String>,
    /// Whether urgent-low still sounds during quiet hours (safety override).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quiet_urgent_low: Option<bool>,
    /// Escalate an unacknowledged urgent alert after this many minutes
    /// (0 disables escalation).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub escalate_minutes: Option<i64>,
    /// Optional webhook / ntfy topic URL to POST urgent alerts to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub push_url: Option<String>,
    /// Whether `push_url` is actually used. Lets the settings screen turn push
    /// alerts off without discarding the configured URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub push_enabled: Option<bool>,
    /// Whether desktop notifications spell out the alert and the reading.
    /// `false` keeps them content-free for lock screens and shared displays.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notify_content: Option<bool>,
    /// Warn when the forecast predicts a low/high crossing within this many
    /// minutes (0 disables predictive alerts).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predict_horizon_minutes: Option<i64>,
}

impl AlertsConfig {
    pub fn from_resolved(alerts: &Alerts, units: Units) -> Self {
        Self {
            urgent_low: Some(units.from_mgdl(alerts.urgent_low)),
            low: Some(units.from_mgdl(alerts.low)),
            high: Some(units.from_mgdl(alerts.high)),
            urgent_high: Some(units.from_mgdl(alerts.urgent_high)),
            stale_minutes: Some(alerts.stale_minutes),
            desktop: Some(alerts.desktop),
            osd: Some(alerts.osd),
            sound: Some(alerts.sound),
            snooze_minutes: Some(alerts.snooze_minutes),
            quiet_start: alerts.quiet_start.map(fmt_hhmm),
            quiet_end: alerts.quiet_end.map(fmt_hhmm),
            quiet_urgent_low: Some(alerts.quiet_urgent_low),
            escalate_minutes: Some(alerts.escalate_minutes),
            push_url: alerts.push_url.clone(),
            push_enabled: Some(alerts.push_enabled),
            notify_content: Some(alerts.notify_content),
            predict_horizon_minutes: Some(alerts.predict_horizon_minutes),
        }
    }

    /// Resolve to concrete mg/dL thresholds, converting any user-supplied
    /// values from `units` and filling gaps with defaults.
    #[cfg(test)]
    pub fn resolve(&self, units: Units) -> Alerts {
        self.resolve_checked(units).0
    }

    /// Resolve, and report anything that had to be coerced.
    ///
    /// A threshold that can't alarm is worse than no threshold at all, and the
    /// realistic way to get one is a unit mismatch: the shipped example is in
    /// mmol/L, so a US user who changes `units` to `mgdl` and nothing else ends
    /// up with `low = 3.9 mg/dL`. Nothing then reads as low — a 40 mg/dL hypo
    /// classifies as *urgent high*, because it is above every threshold.
    ///
    /// So an implausible value is not clamped toward the edge of the range
    /// (`3.9` → `20` still can't alarm); it falls back to the physiological
    /// default and says so. The settings screen has enforced the same
    /// invariants for a while — this brings the config-file path in line.
    pub fn resolve_checked(&self, units: Units) -> (Alerts, Vec<String>) {
        let d = Alerts::default();
        let mut warnings = Vec::new();
        let mut threshold = |raw: Option<f64>, default: f64, name: &str| {
            plausible(raw, default, name, units, &mut warnings)
        };
        let (urgent_low, low, high, urgent_high) = (
            threshold(self.urgent_low, d.urgent_low, "urgent_low"),
            threshold(self.low, d.low, "low"),
            threshold(self.high, d.high, "high"),
            threshold(self.urgent_high, d.urgent_high, "urgent_high"),
        );
        // Crossed thresholds silently empty a band and misclassify every
        // reading in it, so order is restored rather than trusted.
        let (urgent_low, low, high, urgent_high) =
            order_thresholds(urgent_low, low, high, urgent_high, units, &mut warnings);

        let stale_minutes = match self.stale_minutes {
            Some(m) if m < 1 => {
                warnings.push(format!(
                    "stale_minutes = {m} would make every reading stale — using {}",
                    d.stale_minutes
                ));
                d.stale_minutes
            }
            other => other.unwrap_or(d.stale_minutes),
        };

        let alerts = Alerts {
            urgent_low,
            low,
            high,
            urgent_high,
            stale_minutes,
            desktop: self.desktop.unwrap_or(d.desktop),
            osd: self.osd.unwrap_or(d.osd),
            sound: self.sound.unwrap_or(d.sound),
            snooze_minutes: self.snooze_minutes.unwrap_or(d.snooze_minutes),
            quiet_start: self.quiet_start.as_deref().and_then(parse_hhmm),
            quiet_end: self.quiet_end.as_deref().and_then(parse_hhmm),
            quiet_urgent_low: self.quiet_urgent_low.unwrap_or(d.quiet_urgent_low),
            escalate_minutes: self.escalate_minutes.unwrap_or(d.escalate_minutes),
            push_url: self.push_url.clone(),
            push_enabled: self.push_enabled.unwrap_or(d.push_enabled),
            notify_content: self.notify_content.unwrap_or(d.notify_content),
            predict_horizon_minutes: self
                .predict_horizon_minutes
                .unwrap_or(d.predict_horizon_minutes),
        };
        (alerts, warnings)
    }
}

/// Lowest and highest glucose a threshold can meaningfully sit at, in mg/dL.
/// A CGM reports roughly 40–400; outside this band a threshold cannot separate
/// real readings from each other, so it can only ever mis-classify them.
const MIN_PLAUSIBLE_MGDL: f64 = 20.0;
const MAX_PLAUSIBLE_MGDL: f64 = 500.0;

/// One threshold, converted and sanity-checked against the physiological range.
fn plausible(
    raw: Option<f64>,
    default: f64,
    name: &str,
    units: Units,
    warnings: &mut Vec<String>,
) -> f64 {
    let Some(v) = raw else { return default };
    let mgdl = units.to_mgdl(v);
    if (MIN_PLAUSIBLE_MGDL..=MAX_PLAUSIBLE_MGDL).contains(&mgdl) {
        return mgdl;
    }
    warnings.push(format!(
        "{name} = {v} {} is outside the physiological range — check `units` — using {} {}",
        units.label(),
        units.format(default),
        units.label()
    ));
    default
}

/// Restore `urgent_low <= low <= high <= urgent_high`, reporting any change.
fn order_thresholds(
    urgent_low: f64,
    low: f64,
    high: f64,
    urgent_high: f64,
    units: Units,
    warnings: &mut Vec<String>,
) -> (f64, f64, f64, f64) {
    if urgent_low <= low && low <= high && high <= urgent_high {
        return (urgent_low, low, high, urgent_high);
    }
    let mut v = [urgent_low, low, high, urgent_high];
    v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    warnings.push(format!(
        "alert thresholds were out of order — using {} <= {} <= {} <= {} {}",
        units.format(v[0]),
        units.format(v[1]),
        units.format(v[2]),
        units.format(v[3]),
        units.label()
    ));
    (v[0], v[1], v[2], v[3])
}

/// Create (or truncate) a file that only the owner can read, with the mode set
/// at creation time so a secret is never written to a briefly-readable file.
#[cfg(unix)]
fn create_private(path: &Path) -> std::io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;
    std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)
}

#[cfg(not(unix))]
fn create_private(path: &Path) -> std::io::Result<File> {
    File::create(path)
}

/// Write a file only the owner can read. Used for anything holding personal
/// data — the token, and exports of someone's glucose history.
pub fn write_private(path: &Path, body: &str) -> Result<()> {
    if let Some(dir) = path.parent() {
        if !dir.as_os_str().is_empty() {
            std::fs::create_dir_all(dir)
                .with_context(|| format!("failed to create {}", dir.display()))?;
        }
    }
    let mut f =
        create_private(path).with_context(|| format!("failed to create {}", path.display()))?;
    f.write_all(body.as_bytes())
        .with_context(|| format!("failed to write {}", path.display()))?;
    set_owner_only(path);
    Ok(())
}

/// Restrict `path` to owner read/write (no-op off Unix).
pub fn set_owner_only(path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
    }
    #[cfg(not(unix))]
    let _ = path;
}

/// Parse `HH:MM` into minutes-of-day (0..1440).
pub fn parse_hhmm(s: &str) -> Option<i32> {
    let (h, m) = s.trim().split_once(':')?;
    let h: i32 = h.parse().ok()?;
    let m: i32 = m.parse().ok()?;
    if (0..24).contains(&h) && (0..60).contains(&m) {
        Some(h * 60 + m)
    } else {
        None
    }
}

/// Format minutes-of-day as `HH:MM`.
pub fn fmt_hhmm(min: i32) -> String {
    let m = min.rem_euclid(1440);
    format!("{:02}:{:02}", m / 60, m % 60)
}

/// Resolved alert thresholds and behaviour, always in mg/dL.
#[derive(Debug, Clone)]
pub struct Alerts {
    pub urgent_low: f64,
    pub low: f64,
    pub high: f64,
    pub urgent_high: f64,
    pub stale_minutes: i64,
    pub desktop: bool,
    pub osd: bool,
    pub sound: bool,
    pub snooze_minutes: i64,
    /// Quiet-hours window as minutes-of-day; `None` when disabled.
    pub quiet_start: Option<i32>,
    pub quiet_end: Option<i32>,
    pub quiet_urgent_low: bool,
    pub escalate_minutes: i64,
    pub push_url: Option<String>,
    pub push_enabled: bool,
    pub notify_content: bool,
    pub predict_horizon_minutes: i64,
}

impl Default for Alerts {
    fn default() -> Self {
        Self {
            urgent_low: 55.0,
            low: 70.0,
            high: 180.0,
            urgent_high: 250.0,
            stale_minutes: 15,
            desktop: true,
            osd: true,
            sound: true,
            snooze_minutes: 15,
            quiet_start: None,
            quiet_end: None,
            quiet_urgent_low: true,
            escalate_minutes: 0,
            push_url: None,
            push_enabled: true,
            notify_content: true,
            predict_horizon_minutes: 30,
        }
    }
}

impl Alerts {
    /// True when `min_of_day` falls inside the quiet-hours window (handles
    /// windows that cross midnight). Always false when quiet hours are unset.
    pub fn in_quiet_hours(&self, min_of_day: i32) -> bool {
        match (self.quiet_start, self.quiet_end) {
            (Some(s), Some(e)) if s <= e => min_of_day >= s && min_of_day < e,
            (Some(s), Some(e)) => min_of_day >= s || min_of_day < e,
            _ => false,
        }
    }
}

fn default_units() -> Units {
    Units::Mmol
}
fn default_sensor_days() -> u32 {
    10
}

fn default_agp_days() -> u32 {
    14
}
fn default_refresh() -> u64 {
    30
}
fn default_site_name() -> String {
    "default".to_string()
}
fn is_default_theme(t: &ThemeConfig) -> bool {
    toml::Value::try_from(t)
        .map(|v| v.as_table().map(|tbl| tbl.is_empty()).unwrap_or(true))
        .unwrap_or(false)
}

fn unknown_key(key: &str) -> String {
    format!(
        "unknown setting {key:?}. Known settings: {}",
        Config::KEYS.join(", ")
    )
}

impl AlertsConfig {
    /// Re-express the glucose thresholds from one display unit in another.
    ///
    /// Only the four bounds: minutes are minutes, and a snooze is a snooze.
    fn convert(&mut self, from: Units, to: Units) {
        if from == to {
            return;
        }
        let redo = |value: &mut Option<f64>| {
            if let Some(shown) = value {
                let mgdl = from.to_mgdl(*shown);
                *shown = match to {
                    // The precision each unit is written in: a tenth of a
                    // mmol/L, a whole mg/dL.
                    Units::Mmol => (to.from_mgdl(mgdl) * 10.0).round() / 10.0,
                    Units::Mgdl => to.from_mgdl(mgdl).round(),
                };
            }
        };
        redo(&mut self.urgent_low);
        redo(&mut self.low);
        redo(&mut self.high);
        redo(&mut self.urgent_high);
    }
}

impl Config {
    /// The keys `sugarrush config` will read and write.
    ///
    /// A curated list rather than every serialisable field: these are the ones
    /// the settings screen edits, so a value set here is one the app already
    /// knows how to validate and round-trip. Site URLs and tokens are absent
    /// on purpose — a token belongs in the wizard or the settings screen, not
    /// in a shell history.
    pub const KEYS: &[&str] = &[
        "units",
        "refresh_secs",
        "agp_days",
        "sensor_days",
        "alerts.urgent_low",
        "alerts.low",
        "alerts.high",
        "alerts.urgent_high",
        "alerts.stale_minutes",
        "alerts.snooze_minutes",
        "alerts.escalate_minutes",
        "alerts.desktop",
        "alerts.sound",
        "alerts.quiet_urgent_low",
        "bar.arrow",
        "bar.delta",
        "bar.units",
        "bar.sparkline",
    ];

    /// The value of `key` as it would be written to the file, or `None` for a
    /// key that has never been set (the default applies).
    pub fn get_key(&self, key: &str) -> std::result::Result<Option<String>, String> {
        let a = &self.alerts;
        let out = match key {
            "units" => Some(match self.units {
                Units::Mmol => "mmol".to_string(),
                Units::Mgdl => "mgdl".to_string(),
            }),
            "refresh_secs" => Some(self.refresh_secs.to_string()),
            "agp_days" => Some(self.agp_days.to_string()),
            "sensor_days" => Some(self.sensor_days.to_string()),
            "alerts.urgent_low" => a.urgent_low.map(|v| v.to_string()),
            "alerts.low" => a.low.map(|v| v.to_string()),
            "alerts.high" => a.high.map(|v| v.to_string()),
            "alerts.urgent_high" => a.urgent_high.map(|v| v.to_string()),
            "alerts.stale_minutes" => a.stale_minutes.map(|v| v.to_string()),
            "alerts.snooze_minutes" => a.snooze_minutes.map(|v| v.to_string()),
            "alerts.escalate_minutes" => a.escalate_minutes.map(|v| v.to_string()),
            "alerts.desktop" => a.desktop.map(|v| v.to_string()),
            "alerts.sound" => a.sound.map(|v| v.to_string()),
            "alerts.quiet_urgent_low" => a.quiet_urgent_low.map(|v| v.to_string()),
            "bar.arrow" => Some(self.bar.arrow.to_string()),
            "bar.delta" => Some(self.bar.delta.to_string()),
            "bar.units" => Some(self.bar.units.to_string()),
            "bar.sparkline" => Some(self.bar.sparkline.to_string()),
            _ => return Err(unknown_key(key)),
        };
        Ok(out)
    }

    /// Set `key` to `value`, or say why not.
    ///
    /// Thresholds are in the display unit, exactly as the file stores them, so
    /// what you type is what the settings screen would show. The caller is
    /// expected to run [`AlertsConfig::resolve_checked`] afterwards and refuse
    /// a change that produces a warning: repairing a value someone asked for
    /// silently is worse than refusing it.
    pub fn set_key(&mut self, key: &str, value: &str) -> std::result::Result<(), String> {
        let number = |what: &str| -> std::result::Result<f64, String> {
            value
                .parse::<f64>()
                .map_err(|_| format!("{what} needs a number, got {value:?}"))
        };
        let whole = |what: &str| -> std::result::Result<i64, String> {
            value
                .parse::<i64>()
                .map_err(|_| format!("{what} needs a whole number, got {value:?}"))
        };
        let flag = |what: &str| -> std::result::Result<bool, String> {
            match value {
                "true" | "on" | "yes" => Ok(true),
                "false" | "off" | "no" => Ok(false),
                _ => Err(format!("{what} is on or off, got {value:?}")),
            }
        };

        match key {
            "units" => {
                let next = match value {
                    "mmol" | "mmol/L" => Units::Mmol,
                    "mgdl" | "mg/dL" => Units::Mgdl,
                    _ => return Err(format!("units is mmol or mgdl, got {value:?}")),
                };
                // Thresholds are stored in the display unit, so changing the
                // unit without converting them reinterprets every number: 3.9
                // mmol/L becomes 3.9 mg/dL, which is not a low, it is a
                // reading no living person has. The check on the way out
                // caught that and refused the write, which made this key
                // unusable rather than dangerous — the settings screen has
                // always converted, because it holds mg/dL internally.
                self.alerts.convert(self.units, next);
                for site in &mut self.sites {
                    if let Some(alerts) = site.alerts.as_mut() {
                        alerts.convert(self.units, next);
                    }
                }
                self.units = next;
            }
            "refresh_secs" => self.refresh_secs = whole(key)?.clamp(5, 600) as u64,
            "agp_days" => self.agp_days = whole(key)?.clamp(1, 90) as u32,
            "sensor_days" => self.sensor_days = whole(key)?.clamp(0, 30) as u32,
            "alerts.urgent_low" => self.alerts.urgent_low = Some(number(key)?),
            "alerts.low" => self.alerts.low = Some(number(key)?),
            "alerts.high" => self.alerts.high = Some(number(key)?),
            "alerts.urgent_high" => self.alerts.urgent_high = Some(number(key)?),
            "alerts.stale_minutes" => self.alerts.stale_minutes = Some(whole(key)?.max(1)),
            "alerts.snooze_minutes" => self.alerts.snooze_minutes = Some(whole(key)?.max(1)),
            "alerts.escalate_minutes" => self.alerts.escalate_minutes = Some(whole(key)?.max(0)),
            "alerts.desktop" => self.alerts.desktop = Some(flag(key)?),
            "alerts.sound" => self.alerts.sound = Some(flag(key)?),
            "alerts.quiet_urgent_low" => self.alerts.quiet_urgent_low = Some(flag(key)?),
            "bar.arrow" => self.bar.arrow = flag(key)?,
            "bar.delta" => self.bar.delta = flag(key)?,
            "bar.units" => self.bar.units = flag(key)?,
            "bar.sparkline" => self.bar.sparkline = flag(key)?,
            _ => return Err(unknown_key(key)),
        }
        Ok(())
    }

    pub fn path() -> Result<PathBuf> {
        let dir = dirs::config_dir().context("could not resolve user config dir")?;
        Ok(dir.join("sugarrush").join("config.toml"))
    }

    /// A self-contained config for `--demo` mode (no real site; the client is
    /// built but never used — demo data is generated locally).
    pub fn demo() -> Self {
        Self {
            url: Some("http://demo.invalid".to_string()),
            token: Some("demo".to_string()),
            sites: Vec::new(),
            allow_unattended_writes: false,
            units: default_units(),
            refresh_secs: 5,
            alerts: AlertsConfig::default(),
            theme: ThemeConfig::default(),
            graph_style: GraphStyle::default(),
            agp_days: default_agp_days(),
            sensor_days: default_sensor_days(),
            minimap: MinimapConfig::default(),
            history_cache: HistoryCacheConfig::default(),
            bar: BarConfig::default(),
        }
    }

    pub fn load() -> Result<Self> {
        let path = Self::path()?;
        let raw = std::fs::read_to_string(&path).with_context(|| {
            format!(
                "could not read config at {}. Copy config.example.toml there to get started.",
                path.display()
            )
        })?;
        let cfg: Config = toml::from_str(&raw)
            .with_context(|| format!("invalid config at {}", path.display()))?;
        Ok(cfg)
    }

    /// Write `body` to `path` atomically, owner-only.
    ///
    /// The config file holds the only copy of the Nightscout token, so it must
    /// never be truncated in place: a write that dies part-way (full disk,
    /// crash, power loss) would leave an empty or half-written file and take
    /// the token with it. Write a sibling temp file created with mode 0600 —
    /// so the token is never briefly world-readable — flush it to disk, then
    /// rename over the target. Rename within a filesystem is atomic: readers
    /// see either the old config or the new one, never a torn one.
    pub fn write_atomic(path: &Path, body: &str) -> Result<()> {
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)
                .with_context(|| format!("failed to create {}", dir.display()))?;
        }
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("config.toml");
        let tmp = path.with_file_name(format!(".{}.{}.tmp", name, std::process::id()));

        let write = |tmp: &Path| -> Result<()> {
            let mut f = create_private(tmp)
                .with_context(|| format!("failed to create {}", tmp.display()))?;
            f.write_all(body.as_bytes())
                .with_context(|| format!("failed to write {}", tmp.display()))?;
            // Get the bytes on disk before the rename publishes the new file.
            f.sync_all()
                .with_context(|| format!("failed to flush {}", tmp.display()))?;
            Ok(())
        };
        if let Err(e) = write(&tmp) {
            let _ = std::fs::remove_file(&tmp);
            return Err(e);
        }
        if let Err(e) = std::fs::rename(&tmp, path) {
            let _ = std::fs::remove_file(&tmp);
            return Err(
                anyhow::Error::new(e).context(format!("failed to replace {}", path.display()))
            );
        }
        // Re-assert the mode: an existing file's permissions survive a rename
        // on some platforms, and the config may predate this code.
        set_owner_only(path);
        Ok(())
    }

    /// True when the config file is group- or world-readable (Unix only) —
    /// the token lives there in plaintext, so it should be `chmod 600`.
    pub fn perms_too_open() -> bool {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(path) = Self::path() {
                if let Ok(meta) = std::fs::metadata(path) {
                    return meta.permissions().mode() & 0o077 != 0;
                }
            }
        }
        false
    }

    /// The configured sites: the `[[sites]]` list if present, otherwise the
    /// legacy top-level `url`/`token` as a single "default" site.
    pub fn resolve_sites(&self) -> Result<Vec<Site>> {
        let mut sites = if !self.sites.is_empty() {
            self.sites.clone()
        } else {
            match (&self.url, &self.token) {
                (Some(url), Some(token)) => vec![Site {
                    id: String::new(),
                    name: default_site_name(),
                    url: url.clone(),
                    token: token.clone(),
                    write_token: None,
                    timezone: None,
                    alerts: None,
                }],
                _ => bail!("config needs either url + token, or at least one [[sites]] entry"),
            }
        };
        // Episode state in the watcher is keyed by site name, so two sites
        // sharing one would share an alert episode: announcing a low for one
        // person would mark it announced for the other.
        let mut seen = std::collections::BTreeSet::new();
        for site in &sites {
            if !seen.insert(site.name.clone()) {
                bail!(
                    "two [[sites]] are both named '{}' — names identify people \
                     in alerts and alarm state, so they must be unique",
                    site.name
                );
            }
        }

        // A hand-written config gets the same tidy-up as the wizard's input —
        // a missing scheme or a pasted `/api/v1/…` path shouldn't be a silent
        // 404. An unparseable URL is left alone so the fetch error names it.
        for site in &mut sites {
            if let Some(timezone) = site.timezone.as_deref() {
                timezone.parse::<chrono_tz::Tz>().with_context(|| {
                    format!("site '{}': invalid IANA timezone '{timezone}'", site.name)
                })?;
            }
            if let Ok(url) = normalize_site_url(&site.url) {
                site.url = url;
            }
            if site.id.is_empty() {
                site.id = site.stable_id();
            } else if uuid::Uuid::parse_str(&site.id).is_err() {
                bail!("site '{}': id must be a UUID", site.name);
            }
        }
        Ok(sites)
    }
}

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

    #[test]
    fn mmol_thresholds_convert_to_mgdl() {
        let raw = AlertsConfig {
            low: Some(3.9),
            urgent_high: Some(13.9),
            ..Default::default()
        };
        let a = raw.resolve(Units::Mmol);
        assert!((a.low - 70.2).abs() < 0.1); // 3.9 * 18
        assert!((a.urgent_high - 250.2).abs() < 0.1);
        // Unset fields keep mg/dL defaults, not converted.
        assert_eq!(a.urgent_low, 55.0);
        assert_eq!(a.high, 180.0);
    }

    #[test]
    fn mgdl_thresholds_pass_through() {
        let raw = AlertsConfig {
            low: Some(70.0),
            ..Default::default()
        };
        assert_eq!(raw.resolve(Units::Mgdl).low, 70.0);
    }

    #[test]
    fn hhmm_round_trips() {
        assert_eq!(parse_hhmm("23:00"), Some(1380));
        assert_eq!(parse_hhmm("07:30"), Some(450));
        assert_eq!(parse_hhmm("24:00"), None);
        assert_eq!(parse_hhmm("nope"), None);
        assert_eq!(fmt_hhmm(1380), "23:00");
        assert_eq!(fmt_hhmm(450), "07:30");
    }

    #[test]
    fn quiet_hours_handles_midnight_wrap() {
        let a = Alerts {
            quiet_start: Some(1380), // 23:00
            quiet_end: Some(420),    // 07:00
            ..Alerts::default()
        };
        assert!(a.in_quiet_hours(1440 - 1)); // 23:59 in window
        assert!(a.in_quiet_hours(0)); // 00:00 in window
        assert!(a.in_quiet_hours(419)); // 06:59 in window
        assert!(!a.in_quiet_hours(420)); // 07:00 out
        assert!(!a.in_quiet_hours(720)); // noon out
                                         // Disabled window is never quiet.
        assert!(!Alerts::default().in_quiet_hours(0));
    }

    #[test]
    fn graph_style_cycles() {
        assert_eq!(GraphStyle::Line.cycle(1), GraphStyle::Dots);
        assert_eq!(GraphStyle::Dots.cycle(1), GraphStyle::Blocks);
        assert_eq!(GraphStyle::Blocks.cycle(1), GraphStyle::Line); // wraps
        assert_eq!(GraphStyle::Line.cycle(-1), GraphStyle::Blocks); // wraps back
    }

    #[test]
    fn empty_config_is_all_defaults() {
        let a = AlertsConfig::default().resolve(Units::Mmol);
        assert_eq!(a.low, 70.0);
        assert!(a.desktop);
        assert_eq!(a.stale_minutes, 15);
    }

    #[test]
    fn write_atomic_replaces_and_stays_owner_only() {
        let dir = std::env::temp_dir().join(format!("sugarrush-test-{}", std::process::id()));
        let path = dir.join("config.toml");
        Config::write_atomic(&path, "first").unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "first");
        // Replacing leaves no temp file behind and keeps the new content.
        Config::write_atomic(&path, "second").unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "second");
        let leftovers = std::fs::read_dir(&dir).unwrap().count();
        assert_eq!(leftovers, 1);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn normalize_defaults_to_https_and_trims() {
        assert_eq!(
            normalize_site_url("  ns.example.com/  ").unwrap(),
            "https://ns.example.com"
        );
        assert_eq!(
            normalize_site_url("https://ns.example.com").unwrap(),
            "https://ns.example.com"
        );
        // A pasted API path belongs to the client, not the base URL.
        assert_eq!(
            normalize_site_url("https://ns.example.com/api/v1/entries.json?count=10").unwrap(),
            "https://ns.example.com"
        );
        assert_eq!(
            normalize_site_url("https://ns.example.com/api").unwrap(),
            "https://ns.example.com"
        );
        // http is preserved (not silently upgraded) — it's flagged elsewhere.
        assert_eq!(
            normalize_site_url("http://192.168.1.5:1337").unwrap(),
            "http://192.168.1.5:1337"
        );
    }

    #[test]
    fn normalize_rejects_junk() {
        assert!(normalize_site_url("").is_err());
        assert!(normalize_site_url("   ").is_err());
        assert!(normalize_site_url("ftp://ns.example.com").is_err());
        assert!(normalize_site_url("https://").is_err());
    }

    #[test]
    fn insecure_only_for_remote_http() {
        let site = |url: &str| Site {
            id: String::new(),
            name: "default".into(),
            url: url.into(),
            token: "t".into(),
            write_token: None,
            timezone: None,
            alerts: None,
        };
        assert!(site("http://ns.example.com").is_insecure());
        assert!(site("http://192.168.1.5:1337").is_insecure());
        assert!(!site("https://ns.example.com").is_insecure());
        // Loopback never leaves the machine.
        assert!(!site("http://localhost:1337").is_insecure());
        assert!(!site("http://127.0.0.1:1337").is_insecure());
    }

    /// The exact failure C1 describes: the shipped example is mmol, the user
    /// switches `units` to mgdl and changes nothing else.
    #[test]
    fn a_unit_mismatch_cannot_disable_the_low_alarm() {
        let raw = AlertsConfig {
            urgent_low: Some(3.0),
            low: Some(3.9),
            high: Some(10.0),
            urgent_high: Some(13.9),
            ..Default::default()
        };
        let (a, warnings) = raw.resolve_checked(Units::Mgdl);

        // Before the fix these resolved verbatim, and a 40 mg/dL hypo — a
        // medical emergency — classified as UrgentHigh because it sat above
        // every threshold.
        assert_eq!(
            crate::alert::evaluate(40.0, 0, &a),
            crate::alert::Alert::UrgentLow
        );
        assert_eq!(
            crate::alert::evaluate(300.0, 0, &a),
            crate::alert::Alert::UrgentHigh
        );
        // All four were implausible as mg/dL, so all four are reported.
        assert_eq!(warnings.len(), 4, "{warnings:?}");
        assert!(warnings[0].contains("urgent_low"));
        assert!(warnings.iter().all(|w| w.contains("check `units`")));
    }

    #[test]
    fn the_mirror_mistake_is_caught_too() {
        // mg/dL numbers left in an mmol config: 70 mmol/L is ~1260 mg/dL.
        let raw = AlertsConfig {
            low: Some(70.0),
            urgent_low: Some(55.0),
            ..Default::default()
        };
        let (a, warnings) = raw.resolve_checked(Units::Mmol);
        assert_eq!(a.low, 70.0); // fell back to the mg/dL default
        assert_eq!(a.urgent_low, 55.0);
        assert_eq!(warnings.len(), 2);
        // And an in-range reading is not screaming urgent-low.
        assert_eq!(
            crate::alert::evaluate(100.0, 0, &a),
            crate::alert::Alert::InRange
        );
    }

    #[test]
    fn plausible_values_pass_through_untouched_and_silently() {
        let raw = AlertsConfig {
            urgent_low: Some(3.0),
            low: Some(3.9),
            high: Some(10.0),
            urgent_high: Some(13.9),
            ..Default::default()
        };
        let (a, warnings) = raw.resolve_checked(Units::Mmol);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert!((a.low - 70.2).abs() < 0.1);
        assert!((a.urgent_high - 250.2).abs() < 0.1);
    }

    #[test]
    fn crossed_thresholds_are_reordered_not_obeyed() {
        let raw = AlertsConfig {
            urgent_low: Some(200.0),
            low: Some(180.0),
            high: Some(70.0),
            urgent_high: Some(55.0),
            ..Default::default()
        };
        let (a, warnings) = raw.resolve_checked(Units::Mgdl);
        assert!(a.urgent_low <= a.low && a.low <= a.high && a.high <= a.urgent_high);
        assert!(warnings.iter().any(|w| w.contains("out of order")));
    }

    #[test]
    fn a_zero_stale_window_would_make_everything_stale() {
        let raw = AlertsConfig {
            stale_minutes: Some(0),
            ..Default::default()
        };
        let (a, warnings) = raw.resolve_checked(Units::Mgdl);
        assert_eq!(a.stale_minutes, 15);
        assert!(warnings.iter().any(|w| w.contains("stale_minutes")));
        // A fresh reading is not immediately Stale.
        assert_eq!(
            crate::alert::evaluate(100.0, 0, &a),
            crate::alert::Alert::InRange
        );
    }

    /// The shipped example must parse to the values it appears to set.
    /// `check-process.sh` greps for key *names*, which passed happily while
    /// `refresh_secs` sat inside `[minimap]` and was silently ignored.
    #[test]
    fn the_example_config_means_what_it_says() {
        let raw = include_str!("../config.example.toml");
        let cfg: Config = toml::from_str(raw).expect("config.example.toml must parse");

        // Keys a user is most likely to change, at the level they think.
        assert_eq!(cfg.refresh_secs, 30, "refresh_secs is not a root-level key");
        assert_eq!(cfg.units, Units::Mmol);
        assert_eq!(cfg.agp_days, 14);
        assert!(cfg.minimap.enabled);
        assert_eq!(cfg.minimap.span_hours, 24);

        // And the thresholds it ships resolve to something that can alarm.
        let (alerts, warnings) = cfg.alerts.resolve_checked(cfg.units);
        assert!(
            warnings.is_empty(),
            "the shipped example warns: {warnings:?}"
        );
        assert_eq!(
            crate::alert::evaluate(40.0, 0, &alerts),
            crate::alert::Alert::UrgentLow
        );
    }

    #[test]
    fn two_sites_cannot_share_a_name() {
        let cfg: Config = toml::from_str(
            r#"
units = "mmol"
[[sites]]
name = "kid"
url = "https://a.example.com"
token = "a"
[[sites]]
name = "kid"
url = "https://b.example.com"
token = "b"
"#,
        )
        .unwrap();
        // Names are still CLI selectors and human-facing labels, so ambiguity
        // is refused even though persisted state uses immutable IDs.
        let err = cfg.resolve_sites().unwrap_err().to_string();
        assert!(err.contains("both named 'kid'"), "{err}");
    }

    #[test]
    fn legacy_site_identity_survives_a_display_name_change() {
        let mut site = Site {
            id: String::new(),
            name: "Alice".into(),
            url: "https://alice.example".into(),
            token: "read".into(),
            write_token: None,
            timezone: None,
            alerts: None,
        };
        let identity = site.stable_id();
        site.name = "A.".into();
        assert_eq!(site.stable_id(), identity);
    }

    #[test]
    fn site_alerts_are_a_complete_override() {
        let cfg: Config = toml::from_str(
            r#"
units = "mmol"
[alerts]
low = 3.9
high = 11.0
desktop = true

[[sites]]
name = "alice"
url = "https://alice.example"
token = "read"
[sites.alerts]
low = 4.4
desktop = false
"#,
        )
        .unwrap();
        let site = &cfg.resolve_sites().unwrap()[0];
        let alerts = site.resolve_alerts(&cfg.alerts, cfg.units).0;
        assert!((alerts.low - Units::Mmol.to_mgdl(4.4)).abs() < 0.1);
        assert_eq!(alerts.high, Alerts::default().high);
        assert!(!alerts.desktop);
    }

    /// Every key the app can write must be documented in the example config.
    ///
    /// This replaces a `sed` in `scripts/check-process.sh` that only matched
    /// fields written as `key: Some(...)`, so `units`, `refresh_secs`,
    /// `graph_style`, `agp_days`, `sites` and the whole `[minimap]` table went
    /// unchecked — the gate reported success while covering about half of what
    /// it claimed. Serializing a Config is exhaustive by construction.
    #[test]
    fn a_setting_reads_back_as_it_was_written() {
        let mut cfg = Config::demo();
        cfg.set_key("alerts.low", "4.2").unwrap();
        cfg.set_key("sensor_days", "14").unwrap();
        cfg.set_key("alerts.sound", "off").unwrap();

        assert_eq!(cfg.get_key("alerts.low").unwrap().as_deref(), Some("4.2"));
        assert_eq!(cfg.get_key("sensor_days").unwrap().as_deref(), Some("14"));
        assert_eq!(
            cfg.get_key("alerts.sound").unwrap().as_deref(),
            Some("false")
        );
    }

    #[test]
    fn a_setting_nobody_has_touched_reads_as_unset() {
        let cfg = Config::demo();
        // Unset is not the same as zero: the default applies, and the file
        // says nothing.
        assert_eq!(cfg.get_key("alerts.escalate_minutes").unwrap(), None);
    }

    #[test]
    fn a_bad_key_or_value_is_refused_with_the_alternatives() {
        let mut cfg = Config::demo();

        let err = cfg.set_key("alerts.lo", "4.2").unwrap_err();
        assert!(err.contains("unknown setting"), "got {err}");
        assert!(
            err.contains("alerts.low"),
            "the message lists what is known: {err}"
        );

        let err = cfg.set_key("alerts.low", "quite low").unwrap_err();
        assert!(err.contains("needs a number"), "got {err}");

        let err = cfg.set_key("alerts.sound", "loud").unwrap_err();
        assert!(err.contains("on or off"), "got {err}");

        let err = cfg.set_key("units", "mmol/l/L").unwrap_err();
        assert!(err.contains("mmol or mgdl"), "got {err}");
    }

    #[test]
    fn changing_units_carries_the_thresholds_with_it() {
        // Thresholds live in the display unit, so switching the unit without
        // converting reinterprets every one of them: 3.9 mmol/L would become
        // 3.9 mg/dL, which is not a low but a reading no living person has.
        // The guard on the way out caught that and refused the write, which
        // made this key unusable.
        let mut cfg = Config::demo();
        cfg.units = Units::Mmol;
        cfg.alerts.urgent_low = Some(3.5);
        cfg.alerts.low = Some(4.8);
        cfg.alerts.high = Some(10.0);
        cfg.alerts.urgent_high = Some(13.9);

        cfg.set_key("units", "mgdl").unwrap();
        assert_eq!(cfg.alerts.urgent_low, Some(63.0));
        assert_eq!(cfg.alerts.low, Some(86.0));
        assert_eq!(cfg.alerts.high, Some(180.0));
        assert_eq!(cfg.alerts.urgent_high, Some(250.0));

        // And the change the app makes on load is now a no-op rather than a
        // repair: the numbers are already in range for the unit they claim.
        let (_, warnings) = cfg.alerts.resolve_checked(cfg.units);
        assert!(
            warnings.is_empty(),
            "converted thresholds were repaired: {warnings:?}"
        );

        // Back again, landing on the numbers it started with.
        cfg.set_key("units", "mmol").unwrap();
        assert_eq!(cfg.alerts.urgent_low, Some(3.5));
        assert_eq!(cfg.alerts.high, Some(10.0));
    }

    #[test]
    fn a_site_with_its_own_thresholds_is_converted_too() {
        // A follower's overrides are in the same display unit, and leaving
        // them behind would quietly give one site nonsense bounds.
        let mut cfg = Config::demo();
        cfg.units = Units::Mmol;
        cfg.sites = vec![Site {
            id: String::new(),
            name: "Sam".into(),
            url: "https://ns.example.com".into(),
            token: "t".into(),
            write_token: None,
            timezone: None,
            alerts: Some(AlertsConfig {
                low: Some(4.0),
                high: Some(9.0),
                ..AlertsConfig::default()
            }),
        }];

        cfg.set_key("units", "mgdl").unwrap();
        let site = cfg.sites[0].alerts.as_ref().unwrap();
        assert_eq!(site.low, Some(72.0));
        assert_eq!(site.high, Some(162.0));
    }

    #[test]
    fn every_settable_key_round_trips() {
        // A key that cannot be read back is a key the panel would show blank
        // after setting it.
        let mut cfg = Config::demo();
        for key in Config::KEYS {
            let value = match *key {
                "units" => "mmol",
                k if k.ends_with("desktop")
                    || k.ends_with("sound")
                    || k.ends_with("urgent_low") && k.starts_with("alerts.quiet") =>
                {
                    "on"
                }
                k if k.starts_with("bar.") => "off",
                "alerts.urgent_low" => "3.2",
                "alerts.low" => "4.1",
                "alerts.high" => "9.9",
                "alerts.urgent_high" => "14.2",
                _ => "7",
            };
            cfg.set_key(key, value)
                .unwrap_or_else(|e| panic!("{key} rejected {value}: {e}"));
            let read = cfg.get_key(key).unwrap();
            assert!(read.is_some(), "{key} does not read back");
            if value == "off" {
                assert_eq!(
                    read.as_deref(),
                    Some("false"),
                    "{key} did not keep what it was set to"
                );
            }
        }
    }

    #[test]
    fn every_persisted_key_is_documented() {
        // A config with every optional field populated, so nothing is skipped
        // by `skip_serializing_if`.
        let cfg = Config {
            allow_unattended_writes: false,
            url: Some("https://ns.example.com".into()),
            token: Some("t".into()),
            sites: Vec::new(),
            units: Units::Mmol,
            refresh_secs: 30,
            alerts: AlertsConfig {
                osd: Some(true),
                urgent_low: Some(3.0),
                low: Some(3.9),
                high: Some(10.0),
                urgent_high: Some(13.9),
                stale_minutes: Some(15),
                desktop: Some(true),
                sound: Some(true),
                snooze_minutes: Some(15),
                quiet_start: Some("23:00".into()),
                quiet_end: Some("07:00".into()),
                quiet_urgent_low: Some(true),
                escalate_minutes: Some(20),
                push_url: Some("https://ntfy.sh/topic".into()),
                push_enabled: Some(true),
                notify_content: Some(true),
                predict_horizon_minutes: Some(30),
            },
            theme: ThemeConfig::default(),
            graph_style: GraphStyle::Dots,
            agp_days: 14,
            sensor_days: 10,
            minimap: MinimapConfig::default(),
            history_cache: HistoryCacheConfig {
                enabled: true,
                retention_days: 14,
            },
            bar: BarConfig::default(),
        };
        let toml = toml::to_string_pretty(&cfg).unwrap();
        let example = include_str!("../config.example.toml");

        let mut missing = Vec::new();
        for line in toml.lines() {
            let Some(key) = line.split(['=', ' ']).next().filter(|k| !k.is_empty()) else {
                continue;
            };
            if key.starts_with('[') || key.starts_with('#') {
                continue;
            }
            if !example.contains(key) {
                missing.push(key.to_string());
            }
        }
        assert!(
            missing.is_empty(),
            "keys sugarrush writes but config.example.toml never mentions: {missing:?}"
        );
    }
}