sugarrush 2026.8.2

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
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
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
mod agp;
mod alert;
mod alertlog;
mod app;
mod bar;
mod bigfont;
mod config;
mod demo;
mod export;
mod follow;
mod health;
mod history_cache;
mod nightscout;
mod predict;
mod selftest;
mod service;
mod snapshot;
mod sound;
mod stats;
mod status;
mod theme;
mod treatment;
mod ui;
mod units;
mod view;
mod watch;
mod wizard;

use std::io::{self, IsTerminal, Stdout};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use crossterm::{
    event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind,
        KeyModifiers, MouseEvent, MouseEventKind,
    },
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use tokio::sync::mpsc;
use tokio::time::MissedTickBehavior;

use app::{App, Screen};
use config::Config;
use nightscout::Client;

/// How the binary was invoked.
#[derive(Debug)]
enum Mode {
    /// Run the interactive TUI, starting on the given screen; `demo` uses
    /// synthetic data with no config/network.
    Tui {
        screen: Screen,
        demo: bool,
    },
    /// Print one Waybar JSON line and exit.
    Waybar,
    /// Print one status-bar line in the given format and exit.
    Status {
        format: status::Format,
    },
    /// Print one JSON document describing the current state, and exit.
    Snapshot {
        hours: u32,
        days: u32,
        site: Option<String>,
        /// Synthetic data, so the document renders with no config and no
        /// network — the same escape hatch the dashboard has.
        demo: bool,
    },
    /// Print version/about info (and a desktop notification) and exit.
    About,
    /// Write a CSV + summary of the last `days` days and exit.
    Export {
        days: u32,
        dir: Option<String>,
        site: Option<String>,
        all: bool,
    },
    /// Run the headless alarm watcher until killed.
    Watch,
    /// Write a systemd user unit pointing at this binary, and explain how to
    /// enable it.
    Service(service::Action),
    /// Silence a running (or next-starting) alarm daemon.
    Snooze {
        minutes: Option<i64>,
        site: Option<String>,
        all: bool,
    },
    /// Walk every alarm channel and report which ones actually work.
    AlarmTest {
        quiet: bool,
    },
    /// Print what the alarm has actually done.
    Alerts {
        days: i64,
        site: Option<String>,
        format: alertlog::Format,
    },
    /// Print per-site watcher/data/channel health as JSON.
    Health {
        strict_delivery: bool,
    },
    Treatment(treatment::Request),
    Treatments {
        days: i64,
        site: Option<String>,
        format: treatment::Format,
    },
    Cache {
        action: history_cache::Action,
        site: Option<String>,
        all: bool,
        confirm: bool,
    },
    /// Print usage and exit.
    Help,
    /// Write the man page to stdout.
    Man,
    /// Print the version and exit.
    Version,
}

/// Parse a snooze duration into minutes: `15m`, `2h`, a bare `90`, or `off`
/// (which cancels, and is reported as zero).
fn parse_snooze(arg: &str) -> Option<i64> {
    let a = arg.trim().to_ascii_lowercase();
    if matches!(a.as_str(), "off" | "cancel" | "clear" | "0") {
        return Some(0);
    }
    let (digits, mult) = match a.strip_suffix('h') {
        Some(d) => (d, 60),
        None => (a.strip_suffix('m').unwrap_or(&a), 1),
    };
    let n: i64 = digits.trim().parse().ok()?;
    // A day is the ceiling: beyond that someone means "turn it off", and a
    // snooze that outlives the night it was set in is a trap.
    (1..=24 * 60).contains(&(n * mult)).then_some(n * mult)
}

fn parse_number_flag(args: &[String], i: usize, flag: &str) -> f64 {
    args.get(i)
        .and_then(|value| value.parse::<f64>().ok())
        .unwrap_or_else(|| {
            eprintln!("sugarrush: {flag} needs a number");
            std::process::exit(2)
        })
}

/// The subcommand `--demo` cannot honour, if this is one.
///
/// Demo mode means synthetic data and no network. `watch` starts the alarm
/// daemon against the configured site, and `export`/`status`/`waybar` all read
/// the real config — so `--demo` there did the opposite of what it says,
/// silently. `sugarrush watch --demo` in particular looked like a safe way to
/// try the alarm out.
fn subcommand_without_demo(mode: &Option<Mode>) -> Option<&'static str> {
    match mode {
        Some(Mode::Watch) => Some("watch"),
        Some(Mode::Export { .. }) => Some("export"),
        Some(Mode::Status { .. }) => Some("status"),
        Some(Mode::Waybar) => Some("waybar"),
        _ => None,
    }
}

fn parse_args() -> Mode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut screen = Screen::Dashboard;
    let mut demo = false;
    let mut mode: Option<Mode> = None;
    let mut export_days: Option<u32> = None;
    let mut status_format: Option<String> = None;
    let mut snapshot_hours: Option<u32> = None;
    let mut snapshot_days: Option<u32> = None;
    let mut export_dir: Option<String> = None;
    let mut snooze_site: Option<String> = None;
    let mut snooze_all = false;
    let mut treatment_site = None;
    let mut treatment_carbs = None;
    let mut treatment_insulin = None;
    let mut treatment_note = None;
    let mut treatment_at = None;
    let mut treatment_confirm = false;
    let mut treatment_non_interactive = false;
    let mut treatment_operation_id = None;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "waybar" => mode = Some(Mode::Waybar),
            "status" => {
                mode = Some(Mode::Status {
                    format: status::Format::Text,
                })
            }
            "--format" => {
                i += 1;
                status_format = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("sugarrush: --format needs a value");
                    std::process::exit(2)
                }));
            }
            "snapshot" => {
                mode = Some(Mode::Snapshot {
                    hours: 6,
                    days: 14,
                    site: None,
                    demo: false,
                })
            }
            "--hours" => {
                i += 1;
                snapshot_hours = args.get(i).and_then(|v| v.parse::<u32>().ok());
                if snapshot_hours.is_none() {
                    eprintln!("sugarrush: --hours needs a whole number of hours");
                    std::process::exit(2);
                }
            }
            "about" => mode = Some(Mode::About),
            "export" => {
                mode = Some(Mode::Export {
                    days: 0,
                    dir: None,
                    site: None,
                    all: false,
                })
            }
            "watch" => mode = Some(Mode::Watch),
            // `watch --test` reads as "test the watcher"; accept it either way.
            "--test" => mode = Some(Mode::AlarmTest { quiet: false }),
            "--quiet" => {
                if let Some(Mode::AlarmTest { quiet }) = mode.as_mut() {
                    *quiet = true;
                }
            }
            "alerts" => {
                mode = Some(Mode::Alerts {
                    days: 7,
                    site: None,
                    format: alertlog::Format::Text,
                })
            }
            "health" => {
                mode = Some(Mode::Health {
                    strict_delivery: false,
                })
            }
            "treatment" => {
                mode = Some(Mode::Treatment(treatment::Request {
                    site: String::new(),
                    carbs: None,
                    insulin: None,
                    note: None,
                    at: None,
                    confirm: false,
                    non_interactive: false,
                    operation_id: None,
                }))
            }
            "treatments" => {
                mode = Some(Mode::Treatments {
                    days: 30,
                    site: None,
                    format: treatment::Format::Text,
                })
            }
            "cache" => {
                i += 1;
                mode = Some(Mode::Cache {
                    action: match args.get(i).map(String::as_str) {
                        Some("status") => history_cache::Action::Status,
                        Some("clear") => history_cache::Action::Clear,
                        _ => {
                            eprintln!("sugarrush: cache needs 'status' or 'clear'");
                            std::process::exit(2)
                        }
                    },
                    site: None,
                    all: false,
                    confirm: false,
                });
            }
            "snooze" => {
                // An optional duration follows: `15m`, `2h`, a bare number of
                // minutes, or `off` to cancel. No argument means the configured
                // snooze length, which is what the dashboard's `a` key uses.
                let arg = args.get(i + 1).filter(|a| !a.starts_with('-'));
                let minutes = match arg {
                    Some(a) => {
                        i += 1;
                        match parse_snooze(a) {
                            Some(m) => Some(m),
                            None => {
                                eprintln!("sugarrush: can't read '{a}' as a duration");
                                eprintln!("Try: 15m, 2h, 90, or off.");
                                std::process::exit(2);
                            }
                        }
                    }
                    None => None,
                };
                mode = Some(Mode::Snooze {
                    minutes,
                    site: None,
                    all: false,
                });
            }
            "--site" => {
                i += 1;
                snooze_site = args.get(i).cloned();
                if snooze_site.is_none() {
                    eprintln!("sugarrush: --site needs a site name");
                    std::process::exit(2);
                }
                if matches!(mode, Some(Mode::Treatment(_))) {
                    treatment_site = snooze_site.clone();
                }
            }
            "--carbs" => {
                i += 1;
                treatment_carbs = Some(parse_number_flag(&args, i, "--carbs"));
            }
            "--insulin" => {
                i += 1;
                treatment_insulin = Some(parse_number_flag(&args, i, "--insulin"));
            }
            "--note" => {
                i += 1;
                treatment_note = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("sugarrush: --note needs text");
                    std::process::exit(2)
                }));
            }
            "--at" => {
                i += 1;
                treatment_at = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("sugarrush: --at needs an RFC3339 timestamp");
                    std::process::exit(2)
                }));
            }
            "--confirm" => treatment_confirm = true,
            "--non-interactive" => treatment_non_interactive = true,
            "--operation-id" => {
                i += 1;
                treatment_operation_id = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("sugarrush: --operation-id needs a UUID");
                    std::process::exit(2)
                }));
            }
            "--all" => snooze_all = true,
            "--json" if matches!(mode, Some(Mode::Health { .. })) => {}
            "--strict-delivery" => {
                if let Some(Mode::Health { strict_delivery }) = mode.as_mut() {
                    *strict_delivery = true;
                } else {
                    eprintln!("sugarrush: --strict-delivery only applies to health");
                    std::process::exit(2);
                }
            }
            "--install-unit" | "--install-service" => {
                mode = Some(Mode::Service(service::Action::Install))
            }
            "--service-status" => mode = Some(Mode::Service(service::Action::Status)),
            "--uninstall-service" => mode = Some(Mode::Service(service::Action::Uninstall)),
            "--man" => mode = Some(Mode::Man),
            "help" | "--help" | "-h" => mode = Some(Mode::Help),
            "--version" | "-V" => mode = Some(Mode::Version),
            "--days" if matches!(mode, Some(Mode::Snapshot { .. })) => {
                i += 1;
                snapshot_days = args.get(i).and_then(|v| v.parse::<u32>().ok());
                if snapshot_days.is_none() {
                    eprintln!("sugarrush: --days needs a whole number of days");
                    std::process::exit(2);
                }
            }
            "--days" => {
                i += 1;
                export_days = Some(
                    args.get(i)
                        .and_then(|value| value.parse().ok())
                        .unwrap_or_else(|| {
                            eprintln!("sugarrush: --days needs a positive whole number");
                            std::process::exit(2)
                        }),
                );
            }
            "--out" => {
                i += 1;
                export_dir = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("sugarrush: --out needs a directory");
                    std::process::exit(2)
                }));
            }
            "--demo" => demo = true,
            "--screen" => {
                i += 1;
                if args.get(i).map(String::as_str) == Some("settings") {
                    screen = Screen::Settings;
                }
            }
            // Silently ignoring an unrecognised argument meant `sugarrush
            // --help` opened the TUI — and on an unconfigured machine, the
            // first-run wizard, which then asked for a Nightscout token.
            other => {
                eprintln!("sugarrush: unknown argument '{other}'");
                eprintln!("Try 'sugarrush --help'.");
                std::process::exit(2);
            }
        }
        i += 1;
    }
    // A flag that a subcommand can't honour must be an error, not a shrug.
    // `sugarrush watch --demo` used to start the alarm daemon against the real
    // config and the real site — the exact opposite of what --demo means
    // everywhere else, and silent about it. The same held for export, status
    // and waybar.
    if demo {
        if let Some(name) = subcommand_without_demo(&mode) {
            eprintln!("sugarrush: --demo is not supported by '{name}'");
            eprintln!("It only applies to the dashboard: run 'sugarrush --demo'.");
            std::process::exit(2);
        }
    }
    let reject_flag = |invalid: bool, flag: &str| {
        if invalid {
            eprintln!("sugarrush: {flag} does not apply to this command");
            std::process::exit(2);
        }
    };
    reject_flag(
        export_days.is_some()
            && !matches!(
                mode,
                Some(Mode::Export { .. } | Mode::Alerts { .. } | Mode::Treatments { .. })
            ),
        "--days",
    );
    reject_flag(
        snapshot_hours.is_some() && !matches!(mode, Some(Mode::Snapshot { .. })),
        "--hours",
    );
    reject_flag(
        status_format.is_some()
            && !matches!(
                mode,
                Some(Mode::Status { .. } | Mode::Alerts { .. } | Mode::Treatments { .. })
            ),
        "--format",
    );
    reject_flag(
        export_dir.is_some() && !matches!(mode, Some(Mode::Export { .. })),
        "--out",
    );
    reject_flag(
        snooze_site.is_some()
            && !matches!(
                mode,
                Some(
                    Mode::Snooze { .. }
                        | Mode::Alerts { .. }
                        | Mode::Treatment(_)
                        | Mode::Treatments { .. }
                        | Mode::Cache { .. }
                        | Mode::Export { .. }
                        | Mode::Snapshot { .. }
                )
            ),
        "--site",
    );
    reject_flag(
        snooze_all
            && !matches!(
                mode,
                Some(Mode::Snooze { .. } | Mode::Cache { .. } | Mode::Export { .. })
            ),
        "--all",
    );
    let treatment_only = treatment_carbs.is_some()
        || treatment_insulin.is_some()
        || treatment_note.is_some()
        || treatment_at.is_some()
        || treatment_non_interactive
        || treatment_operation_id.is_some();
    reject_flag(
        treatment_only && !matches!(mode, Some(Mode::Treatment(_))),
        "treatment write options",
    );
    reject_flag(
        treatment_confirm && !matches!(mode, Some(Mode::Treatment(_) | Mode::Cache { .. })),
        "--confirm",
    );

    match mode {
        // `--days` / `--out` are only meaningful for export; fill them in here
        // so the flags can appear on either side of the subcommand.
        Some(Mode::Export { .. }) => Mode::Export {
            days: export_days.unwrap_or(0),
            dir: export_dir,
            site: snooze_site,
            all: snooze_all,
        },
        Some(Mode::Alerts { .. }) => Mode::Alerts {
            days: export_days.map(i64::from).unwrap_or(7),
            site: snooze_site,
            format: status_format
                .as_deref()
                .map(|name| {
                    alertlog::Format::parse(name).unwrap_or_else(|| {
                        eprintln!("unknown alerts format '{name}'; use text, json, or csv");
                        std::process::exit(2)
                    })
                })
                .unwrap_or(alertlog::Format::Text),
        },
        Some(Mode::Snapshot { .. }) => Mode::Snapshot {
            hours: snapshot_hours.unwrap_or(6).clamp(1, 72),
            days: snapshot_days.unwrap_or(14).clamp(0, 90),
            site: snooze_site,
            demo,
        },
        Some(Mode::Status { .. }) => Mode::Status {
            format: status_format
                .as_deref()
                .map(|name| {
                    status::Format::parse(name).unwrap_or_else(|| {
                        eprintln!(
                            "unknown --format '{name}'. Available: {}",
                            status::Format::NAMES
                        );
                        std::process::exit(2)
                    })
                })
                .unwrap_or(status::Format::Text),
        },
        Some(Mode::Snooze { minutes, .. }) => {
            if snooze_all && snooze_site.is_some() {
                eprintln!("sugarrush: choose either --site NAME or --all");
                std::process::exit(2);
            }
            Mode::Snooze {
                minutes,
                site: snooze_site,
                all: snooze_all,
            }
        }
        Some(Mode::Treatment(_)) => Mode::Treatment(treatment::Request {
            site: treatment_site.or(snooze_site).unwrap_or_else(|| {
                eprintln!("sugarrush: treatment requires --site NAME");
                std::process::exit(2)
            }),
            carbs: treatment_carbs,
            insulin: treatment_insulin,
            note: treatment_note,
            at: treatment_at,
            confirm: treatment_confirm,
            non_interactive: treatment_non_interactive,
            operation_id: treatment_operation_id,
        }),
        Some(Mode::Treatments { .. }) => Mode::Treatments {
            days: export_days.map(i64::from).unwrap_or(30),
            site: snooze_site,
            format: status_format
                .as_deref()
                .map(|name| {
                    treatment::Format::parse(name).unwrap_or_else(|| {
                        eprintln!("unknown treatments format '{name}'; use text, json, or csv");
                        std::process::exit(2)
                    })
                })
                .unwrap_or(treatment::Format::Text),
        },
        Some(Mode::Cache { action, .. }) => Mode::Cache {
            action,
            site: snooze_site,
            all: snooze_all,
            confirm: treatment_confirm,
        },
        Some(m) => m,
        None => Mode::Tui { screen, demo },
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    match parse_args() {
        Mode::About => {
            print_about();
            Ok(())
        }
        Mode::Waybar => {
            let cfg = Config::load()?;
            // Bars read stdout and ignore stderr, so the warning reaches a
            // human running it by hand without corrupting the bar's input.
            let sites = cfg.resolve_sites()?;
            warn_about_config(&sites[0].resolve_alerts(&cfg.alerts, cfg.units).1);
            println!("{}", bar::line(&cfg).await);
            Ok(())
        }
        Mode::Snapshot {
            hours,
            days,
            demo: true,
            ..
        } => {
            // A demo run must work with no config file at all, so the three
            // settings fall back to their own defaults rather than to a
            // Config that cannot be constructed without one.
            let (units, alerts, theme) = match Config::load() {
                Ok(cfg) => (
                    cfg.units,
                    cfg.alerts.resolve_checked(cfg.units).0,
                    cfg.theme.resolve(),
                ),
                Err(_) => (
                    units::Units::Mmol,
                    config::Alerts::default(),
                    theme::Theme::default(),
                ),
            };
            println!(
                "{}",
                serde_json::to_string(&snapshot::demo(
                    units,
                    alerts,
                    theme,
                    hours,
                    days,
                    chrono::Utc::now().timestamp_millis(),
                ))?
            );
            Ok(())
        }
        Mode::Snapshot {
            hours, days, site, ..
        } => {
            let cfg = Config::load()?;
            let sites = cfg.resolve_sites()?;
            let chosen = match snapshot_site(&sites, site.as_deref()) {
                Ok(site) => site,
                Err(message) => {
                    // A panel can render a message; it cannot render a
                    // non-zero exit with nothing on stdout.
                    println!(
                        "{}",
                        serde_json::to_string(&snapshot::error_doc(
                            chrono::Utc::now().timestamp_millis(),
                            &message,
                        ))?
                    );
                    return Ok(());
                }
            };
            println!(
                "{}",
                serde_json::to_string(&snapshot::fetch(&cfg, chosen, hours, days).await)?
            );
            Ok(())
        }
        Mode::Status { format } => {
            let cfg = Config::load()?;
            let sites = cfg.resolve_sites()?;
            warn_about_config(&sites[0].resolve_alerts(&cfg.alerts, cfg.units).1);
            println!("{}", status::status(&cfg).await.render(format));
            Ok(())
        }
        Mode::Export {
            days,
            dir,
            site,
            all,
        } => run_export(days, dir, site.as_deref(), all).await,
        Mode::Watch => watch::run().await,
        Mode::Snooze { minutes, site, all } => run_snooze(minutes, site.as_deref(), all),
        Mode::AlarmTest { quiet } => selftest::run(quiet).await,
        Mode::Alerts { days, site, format } => {
            let cfg = Config::load()?;
            print!(
                "{}",
                alertlog::render(days, cfg.units, site.as_deref(), format)?
            );
            Ok(())
        }
        Mode::Health { strict_delivery } => {
            let cfg = Config::load()?;
            let report = health::inspect(&cfg).await?;
            let healthy = report.healthy;
            println!("{}", serde_json::to_string_pretty(&report)?);
            if !healthy || (strict_delivery && report.degraded) {
                std::process::exit(1);
            }
            Ok(())
        }
        Mode::Treatment(request) => treatment::run(request).await,
        Mode::Treatments { days, site, format } => {
            print!("{}", treatment::render(days, site.as_deref(), format)?);
            Ok(())
        }
        Mode::Cache {
            action,
            site,
            all,
            confirm,
        } => run_cache(action, site.as_deref(), all, confirm),
        Mode::Service(action) => service::run(action),
        Mode::Help => {
            print_help();
            Ok(())
        }
        Mode::Man => {
            print_man();
            Ok(())
        }
        Mode::Version => {
            println!("sugarrush {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        Mode::Tui { screen, demo } => run_tui(screen, demo).await,
    }
}

/// Headless export: fetch the clinical window and write both files, printing
/// the paths. Useful in a cron job or right before an appointment.
/// The site a snapshot describes: the only one, or the named one. Returns the
/// message to print rather than an error, because the caller turns it into a
/// document rather than a failure.
fn snapshot_site<'a>(
    sites: &'a [config::Site],
    selected: Option<&str>,
) -> Result<&'a config::Site, String> {
    match selected {
        Some(name) => sites
            .iter()
            .find(|site| site.name == name)
            .ok_or_else(|| format!("no site named '{name}'")),
        None => sites
            .first()
            .ok_or_else(|| "no site configured".to_string()),
    }
}

async fn run_export(
    days: u32,
    dir: Option<String>,
    selected: Option<&str>,
    all: bool,
) -> Result<()> {
    let cfg = Config::load()?;
    let days = if days == 0 { cfg.agp_days } else { days }.clamp(1, 90);
    let sites = cfg.resolve_sites()?;
    if all && selected.is_some() {
        anyhow::bail!("choose either --site NAME or --all");
    }
    if sites.len() > 1 && selected.is_none() && !all {
        anyhow::bail!("multiple people are configured; choose --site NAME or explicitly use --all");
    }
    let selected_sites: Vec<_> = if all {
        sites.iter().collect()
    } else if let Some(name) = selected {
        vec![sites.iter().find(|site| site.name == name).ok_or_else(|| {
            anyhow::anyhow!(
                "no site named '{name}'; available: {}",
                sites
                    .iter()
                    .map(|site| site.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        })?]
    } else {
        vec![&sites[0]]
    };
    for site in selected_sites {
        run_export_site(&cfg, site, days, dir.as_deref()).await?;
    }
    Ok(())
}

async fn run_export_site(
    cfg: &Config,
    site: &config::Site,
    days: u32,
    dir: Option<&str>,
) -> Result<()> {
    let (alerts, warnings) = site.resolve_alerts(&cfg.alerts, cfg.units);
    warn_about_config(&warnings);
    let client = Client::for_site(site)?;

    let now = now_ms();
    let start = now - days as i64 * 24 * 3_600_000;
    let entries = match client
        .entries_range(start, now, days as usize * 24 * 12 + 200)
        .await
    {
        Ok(entries) => {
            if cfg.history_cache.enabled {
                if let Err(error) = history_cache::merge(
                    &site.stable_id(),
                    &entries,
                    now,
                    cfg.history_cache.retention_days,
                ) {
                    eprintln!("sugarrush export: cache update failed: {error}");
                }
            }
            entries
        }
        Err(error) if cfg.history_cache.enabled => {
            let cached = history_cache::load(&site.stable_id(), start, now);
            if cached.is_empty() {
                return Err(error.into());
            }
            eprintln!("sugarrush export: offline — exporting private cached history");
            cached
        }
        Err(error) => return Err(error.into()),
    };

    let dir = dir.map(std::path::PathBuf::from).unwrap_or_default();
    let dir = if dir.as_os_str().is_empty() {
        std::path::PathBuf::from(".")
    } else {
        dir
    };
    for path in export::write_pair(
        &dir,
        &entries,
        &alerts,
        cfg.units,
        days,
        now,
        export::Context {
            timezone: site.timezone.as_deref(),
            subject: Some(&site.name),
        },
    )? {
        println!("{}: {}", site.name, path.display());
    }
    Ok(())
}

async fn run_tui(screen: Screen, demo: bool) -> Result<()> {
    let cfg = if demo {
        Config::demo()
    } else {
        // No config yet: guide the user through setup on a terminal, or point
        // them at the file when running non-interactively.
        let path = Config::path()?;
        if !path.exists() {
            if std::io::stdin().is_terminal() {
                wizard::run().await?;
            } else {
                anyhow::bail!(
                    "no config at {}. Copy config.example.toml there (set url + token), \
                     or run sugarrush in a terminal for guided setup.",
                    path.display()
                );
            }
        }
        Config::load()?
    };
    let sites = cfg.resolve_sites()?;
    let (alerts, mut warnings) = cfg.alerts.resolve_checked(cfg.units);
    for site in &sites {
        let (_, site_warnings) = site.resolve_alerts(&cfg.alerts, cfg.units);
        warnings.extend(
            site_warnings
                .into_iter()
                .map(|w| format!("{}: {w}", site.name)),
        );
    }
    // Also to stderr: a misconfigured threshold is worth seeing even if the
    // terminal is about to be taken over by the alternate screen.
    warn_about_config(&warnings);
    let mut app = App::new(&cfg, alerts, sites);
    app.config_warnings = warnings;
    app.screen = screen;
    app.demo = demo;
    if demo {
        for name in ["Sam", "River"] {
            app.add_site();
            app.sites.last_mut().unwrap().name = name.into();
            app.sites.last_mut().unwrap().token = "demo".into();
        }
        app.sites[0].name = "Alex".into();
        app.site_idx = 0;
        app.settings_dirty = false;
        app.site_dirty = false;
        app.status = None;
    }
    app.perm_warning = !demo && Config::perms_too_open();

    install_panic_hook();
    let mut terminal = setup_terminal(app.minimap_enabled)?;
    sync_tui_alarm_claim(app.demo, app.sites.len(), now_ms());
    let res = run(&mut terminal, &mut app).await;
    restore_terminal(&mut terminal)?;
    // Hand the alarm back to the watcher immediately on exit, rather than
    // leaving it deferring until the heartbeat goes stale.
    if !demo {
        watch::clear_heartbeat(watch::Role::Tui);
    }
    res
}

fn tui_claims_alarm(demo: bool, site_count: usize) -> bool {
    !demo && site_count == 1
}

/// Keep the TUI/watch handoff aligned with what this window actually covers.
/// A multi-site TUI alarms for only its active site, so it must never claim
/// responsibility for a watcher that protects every configured person.
fn sync_tui_alarm_claim(demo: bool, site_count: usize, now_ms: i64) {
    if tui_claims_alarm(demo, site_count) {
        watch::heartbeat(watch::Role::Tui, now_ms);
    } else if !demo {
        // Clear a claim left by startup or by adding/removing sites. Waiting
        // for its 30-second expiry would be a real multi-site alarm gap.
        watch::clear_heartbeat(watch::Role::Tui);
    }
}

/// Usage. Kept in one place so the README, the man page and this can't drift.
/// The command reference, in one place.
///
/// `--help`, the man page and the README table are all rendered from this. They
/// used to be three hand-maintained lists, which is three chances to document a
/// command that no longer exists — or, worse, to ship one that nothing
/// documents. `sugarrush --man` writes the roff.
const COMMANDS: &[(&str, &str)] = &[
    ("sugarrush [--demo] [--screen settings]", "the dashboard"),
    (
        "sugarrush watch",
        "headless alarm watcher (no terminal needed)",
    ),
    (
        "sugarrush watch --test [--quiet]",
        "check that every alarm channel actually works",
    ),
    (
        "sugarrush watch --install-service|--service-status|--uninstall-service",
        "manage the native always-on user service",
    ),
    (
        "sugarrush snooze [15m|2h|off] [--site NAME|--all]",
        "silence the alarm daemon without stopping it",
    ),
    (
        "sugarrush alerts [--days N] [--site NAME] [--format text|json|csv]",
        "filter or export what the alarm has done",
    ),
    (
        "sugarrush health --json [--strict-delivery]",
        "machine-readable watcher, data and delivery health",
    ),
    (
        "sugarrush treatment --site NAME [--carbs G] [--insulin U] [--note TEXT] [--at RFC3339]",
        "review and write a durable CarePortal treatment",
    ),
    (
        "sugarrush treatments [--days N] [--site NAME] [--format text|json|csv]",
        "review the local treatment submission audit",
    ),
    (
        "sugarrush cache status|clear [--site NAME|--all] [--confirm]",
        "inspect or deliberately erase private cached history",
    ),
    (
        "sugarrush export [--days N] [--out DIR] [--site NAME|--all]",
        "CSV + a clinical summary",
    ),
    (
        "sugarrush status [--format FORMAT]",
        "one line for a status bar",
    ),
    (
        "sugarrush snapshot [--hours N] [--days N]",
        "one JSON document: reading, series, stats, insights",
    ),
    ("sugarrush waybar", "alias for --format json"),
    ("sugarrush about", "version, config and a health check"),
];

/// Flags, likewise shared between `--help` and the man page.
const OPTIONS: &[(&str, &str)] = &[
    (
        "--demo",
        "synthetic data, no config and no network (dashboard and snapshot)",
    ),
    ("--screen settings", "open straight to the settings screen"),
    (
        "--days N",
        "window in days (export: the AGP days setting; alerts: 7)",
    ),
    (
        "--out DIR",
        "where to write exports (default: the current directory)",
    ),
    ("--format FORMAT", "status-bar syntax"),
    ("--hours N", "snapshot chart window (default 6)"),
    (
        "--days N",
        "snapshot history for patterns (default 14, 0 = none)",
    ),
    ("--test", "run the alarm self-test"),
    ("--quiet", "with --test: check without making a noise"),
    ("--site NAME", "target one site for snooze or alert history"),
    (
        "--all",
        "with snooze: explicitly target every configured site",
    ),
    ("--json", "with health: emit the stable JSON report"),
    (
        "--strict-delivery",
        "health exits nonzero for alarm or delivery degradation",
    ),
    (
        "--non-interactive --confirm --operation-id UUID",
        "automation-only treatment confirmation with a stable retry identity",
    ),
    (
        "--install-service",
        "install and start the native watcher service",
    ),
    ("--service-status", "show native watcher service status"),
    (
        "--uninstall-service",
        "stop and remove the native watcher service",
    ),
    (
        "--install-unit",
        "compatibility alias for --install-service",
    ),
    ("--man", "write the man page to stdout"),
    ("-h, --help", "this"),
    ("-V, --version", "print the version"),
];

/// Column widths for `--help`. A signature wider than its pad gets its
/// description on the next line rather than pushing it off the screen.
const USAGE_PAD: usize = 40;
const OPTION_PAD: usize = 22;

/// Print one `left  right` row, wrapping to a second line when `left` is too
/// wide for the column.
///
/// The command signatures outgrew a fixed pad — `sugarrush treatment --site
/// NAME [--carbs G] …` alone is 86 characters — so every row past the pad ran
/// to 138 columns and the description column stopped existing. In a tool whose
/// entire audience is in a terminal, `--help` is the last place that should
/// wrap badly.
fn two_column(left: &str, right: &str, pad: usize) {
    if left.chars().count() <= pad {
        println!("    {left:<pad$} {right}");
    } else {
        println!("    {left}");
        println!("    {:<pad$} {right}", "");
    }
}

fn print_help() {
    println!(
        "sugarrush {} — your Nightscout CGM data, in the terminal\n",
        env!("CARGO_PKG_VERSION")
    );
    println!("USAGE:");
    for (usage, what) in COMMANDS {
        two_column(usage, what, USAGE_PAD);
    }
    println!("\nOPTIONS:");
    for (flag, what) in OPTIONS {
        let what = if *flag == "--format FORMAT" {
            status::Format::NAMES
        } else {
            what
        };
        two_column(flag, what, OPTION_PAD);
    }
    println!("\nConfig lives at ~/.config/sugarrush/config.toml; the first run sets it up.");
    println!("sugarrush is not a medical device — don't use it for treatment decisions.");
}

/// Write a roff man page to stdout, from the same table as `--help`.
///
/// Packagers had nothing to install as `sugarrush.1`, so `man sugarrush` said
/// "No manual entry" on every distro that ships one.
fn print_man() {
    let version = env!("CARGO_PKG_VERSION");
    println!(".TH SUGARRUSH 1 \"\" \"sugarrush {version}\" \"User Commands\"");
    println!(".SH NAME");
    println!("sugarrush \\- your Nightscout CGM data, in the terminal");
    println!(".SH SYNOPSIS");
    println!(".B sugarrush");
    println!("[\\fICOMMAND\\fR] [\\fIOPTIONS\\fR]");
    println!(".SH DESCRIPTION");
    println!(
        "A terminal dashboard, alarm daemon and status-bar source for a \
         self-hosted Nightscout site: live glucose, trend, history, forecasts, \
         alerts and stats."
    );
    println!(".PP");
    println!("sugarrush is not a medical device. Do not use it for treatment decisions.");
    println!(".SH COMMANDS");
    for (usage, what) in COMMANDS {
        println!(".TP");
        println!(".B {}", roff(usage));
        println!("{}", roff(what));
    }
    println!(".SH OPTIONS");
    for (flag, what) in OPTIONS {
        println!(".TP");
        println!(".B {}", roff(flag));
        if *flag == "--format FORMAT" {
            println!("{}", roff(status::Format::NAMES));
        } else {
            println!("{}", roff(what));
        }
    }
    println!(".SH FILES");
    println!(".TP");
    println!(".B ~/.config/sugarrush/config.toml");
    println!("Configuration. Written by the first-run wizard; keep it mode 600.");
    println!(".TP");
    println!(".B $XDG_STATE_HOME/sugarrush/watch.json");
    println!("Alert episode state, so a restart does not re-announce an ongoing low.");
    println!(".TP");
    println!(".B $XDG_STATE_HOME/sugarrush/alerts.jsonl");
    println!("Alert history, 90 days, read by \\fBsugarrush alerts\\fR.");
    println!(".SH SEE ALSO");
    println!("Project page: https://github.com/ronaldlokers/sugarrush");
}

/// Escape the two characters roff treats specially at the start of a line.
fn roff(s: &str) -> String {
    s.replace('\\', "\\e").replace('-', "\\-")
}

/// `sugarrush snooze [15m|2h|90|off]` — silence the alarm daemon.
///
/// Before this, the only way to stop a 3am alarm from `watch` was
/// `systemctl --user stop`, which also disarms the *next* one. The episode
/// state already persisted a snooze and honoured it on restore; there was
/// simply no way in.
fn run_snooze(minutes: Option<i64>, site: Option<&str>, all: bool) -> Result<()> {
    let cfg = Config::load()?;
    let sites = cfg.resolve_sites()?;
    let target = match (site, all, sites.len()) {
        (Some(name), false, _) => watch::SnoozeTarget::Site(name),
        (None, true, _) | (None, false, 1) => watch::SnoozeTarget::All,
        (None, false, _) => {
            anyhow::bail!("multiple sites are configured; choose --site NAME or explicit --all")
        }
        (Some(_), true, _) => unreachable!("parser rejects conflicting targets"),
    };
    let alerts = sites[0].resolve_alerts(&cfg.alerts, cfg.units).0;
    let minutes = minutes.unwrap_or(alerts.snooze_minutes.max(1));

    if minutes == 0 {
        let sites = watch::set_snooze(None, target)?;
        println!("snooze cancelled on {sites} site(s) — the alarm is armed");
        return Ok(());
    }

    let until = now_ms() + minutes * 60_000;
    let sites = watch::set_snooze(Some(until), target)?;
    use chrono::TimeZone;
    let clock = chrono::Local
        .timestamp_millis_opt(until)
        .single()
        .map(|t| t.format("%H:%M").to_string())
        .unwrap_or_else(|| format!("{minutes}m from now"));
    println!("snoozed until {clock} ({minutes}m) on {sites} site(s)");
    // Say how long it takes to land, rather than leaving someone at 3am
    // wondering whether it worked.
    if watch::is_alive(watch::Role::Watch, now_ms()) {
        println!("a running watcher picks this up on its next poll");
    } else {
        println!("no watcher running — this arms the next one");
    }
    Ok(())
}

fn run_cache(
    action: history_cache::Action,
    selected: Option<&str>,
    all: bool,
    confirm: bool,
) -> Result<()> {
    let cfg = Config::load()?;
    let sites = cfg.resolve_sites()?;
    match action {
        history_cache::Action::Status => {
            println!(
                "private history cache: {} · retention {} days",
                if cfg.history_cache.enabled {
                    "enabled"
                } else {
                    "disabled"
                },
                cfg.history_cache.retention_days
            );
            for site in &sites {
                let (count, oldest, newest, bytes) = history_cache::describe(&site.stable_id())?;
                println!(
                    "{}: {count} readings · {bytes} bytes · {} to {}",
                    site.name,
                    oldest
                        .map(format_timestamp)
                        .unwrap_or_else(|| "empty".into()),
                    newest
                        .map(format_timestamp)
                        .unwrap_or_else(|| "empty".into())
                );
            }
        }
        history_cache::Action::Clear => {
            if !confirm {
                anyhow::bail!("cache deletion requires --confirm");
            }
            if all {
                history_cache::purge_all()?;
                println!("cleared private cached history for every configured person");
            } else {
                let name = selected
                    .context("multi-person cache deletion requires --site NAME or --all")?;
                let site = sites
                    .iter()
                    .find(|site| site.name == name)
                    .with_context(|| format!("unknown site '{name}'"))?;
                history_cache::clear_site(&site.stable_id())?;
                println!("cleared private cached history for {}", site.name);
            }
        }
    }
    Ok(())
}

fn format_timestamp(ms: i64) -> String {
    chrono::DateTime::from_timestamp_millis(ms)
        .map(|at| at.to_rfc3339())
        .unwrap_or_else(|| "invalid time".into())
}

/// Print name/version/repo and a not-a-medical-device note, and also fire a
/// desktop notification (used by the Waybar About menu).
/// `sugarrush about` — the diagnostic the bug template asks for.
///
/// It used to print three lines: version, repo, and the safety note. The issue
/// template requires its output, so every bug report arrived with a version
/// number and nothing else — and the questions that actually matter for a CGM
/// alarm (which config, is the site reachable, is a watcher running, can this
/// machine make a sound) had to be asked one at a time in the comments.
///
/// Nothing here leaks a secret: the token is reported as present or absent, and
/// the site URL is reported as its host, since a self-hosted Nightscout URL can
/// itself identify someone.
fn print_about() {
    let version = env!("CARGO_PKG_VERSION");
    let repo = "https://github.com/ronaldlokers/sugarrush";
    println!("sugarrush v{version}");
    println!("{repo}");
    println!("Not a medical device — do not use for treatment decisions.");
    println!();

    println!("build");
    println!("  target          {}", env!("SUGARRUSH_TARGET"));
    println!("  rustc           {}", env!("SUGARRUSH_RUSTC"));
    if let Ok(exe) = std::env::current_exe() {
        println!("  binary          {}", exe.display());
    }

    println!("environment");
    println!("  os              {}", std::env::consts::OS);
    for var in ["TERM", "COLORTERM", "XDG_SESSION_TYPE", "WAYLAND_DISPLAY"] {
        if let Some(v) = std::env::var_os(var) {
            println!("  {var:<15} {}", v.to_string_lossy());
        }
    }

    println!("config");
    match Config::path() {
        Ok(p) => {
            println!("  path            {}", p.display());
            println!("  exists          {}", p.exists());
        }
        Err(e) => println!("  path            unresolved: {e}"),
    }
    match Config::load() {
        Ok(cfg) => {
            let (alerts, warnings) = cfg.alerts.resolve_checked(cfg.units);
            println!("  units           {}", cfg.units.label());
            println!("  refresh         {}s", cfg.refresh_secs);
            match cfg.resolve_sites() {
                // Hosts, not URLs with credentials — and a self-hosted
                // Nightscout host is identifying enough on its own that it is
                // worth someone deciding to paste it, rather than us printing
                // the whole URL by default.
                Ok(sites) => {
                    println!("  sites           {}", sites.len());
                    for site in &sites {
                        let host = site
                            .url
                            .split("://")
                            .nth(1)
                            .and_then(|r| r.split('/').next())
                            .unwrap_or("?");
                        // The write token's *presence* is reported, never its
                        // value. Whether an install can write to someone's
                        // health record is the most consequential thing about
                        // it, and it was the one capability `about` didn't
                        // mention.
                        println!(
                            "                {} · {host} · token {} · write {} · alerts {}",
                            site.name,
                            if site.token.is_empty() {
                                "not set"
                            } else {
                                "set"
                            },
                            match site.write_token.as_deref() {
                                Some(token) if !token.trim().is_empty() => "SET",
                                _ => "not set",
                            },
                            if site.alerts.is_some() {
                                "custom"
                            } else {
                                "global"
                            }
                        );
                    }
                }
                Err(e) => println!("  sites           invalid: {e}"),
            }
            println!(
                "  thresholds    {} / {} / {} / {} mg/dL",
                alerts.urgent_low, alerts.low, alerts.high, alerts.urgent_high
            );
            println!(
                "  alarm         sound {} · desktop {} · push {}",
                onoff(alerts.sound),
                onoff(alerts.desktop),
                match (&alerts.push_url, alerts.push_enabled) {
                    (Some(_), true) => "configured",
                    (Some(_), false) => "configured but off",
                    (None, _) => "not configured",
                }
            );
            for w in warnings {
                println!("  warning         {w}");
            }
        }
        Err(e) => println!("  load          failed: {e}"),
    }

    if let Ok(cfg) = Config::load() {
        println!(
            "  unattended      {}",
            if cfg.allow_unattended_writes {
                "ENABLED — treatment --non-interactive may write without a human"
            } else {
                "off"
            }
        );
    }

    println!("state");
    let now = now_ms();
    println!(
        "  watcher       {}",
        if watch::is_alive(watch::Role::Watch, now) {
            "running"
        } else {
            "not running"
        }
    );
    println!(
        "  dashboard     {}",
        if watch::is_alive(watch::Role::Tui, now) {
            "running"
        } else {
            "not running"
        }
    );
    match watch::snoozed_until() {
        Some(t) if t > now => println!("  snooze          active for {}m", (t - now) / 60_000),
        _ => println!("  snooze          none"),
    }
    println!(
        "  alert log       {} record(s) in 7d",
        alertlog::read(now - 7 * 86_400_000).len()
    );

    println!();
    println!("For the alarm channels specifically: sugarrush watch --test");
}

fn onoff(b: bool) -> &'static str {
    if b {
        "on"
    } else {
        "off"
    }
}

/// One input event forwarded from the reader thread.
enum Input {
    Key(KeyEvent),
    Mouse(MouseEvent),
    /// Terminal was resized — triggers a redraw.
    Resize,
}

async fn run(terminal: &mut Terminal<CrosstermBackend<Stdout>>, app: &mut App) -> Result<()> {
    let mut client = Client::for_site(app.active_site())?;
    // Input on a blocking thread, forwarded over a channel.
    let (tx, mut rx) = mpsc::unbounded_channel::<Input>();
    std::thread::spawn(move || loop {
        if event::poll(Duration::from_millis(200)).unwrap_or(false) {
            let forwarded = match event::read() {
                Ok(Event::Key(k)) if k.kind == KeyEventKind::Press => tx.send(Input::Key(k)),
                Ok(Event::Mouse(m)) => tx.send(Input::Mouse(m)),
                Ok(Event::Resize(_, _)) => tx.send(Input::Resize),
                _ => continue,
            };
            if forwarded.is_err() {
                break;
            }
        }
    });

    // The first fetch is awaited: there is nothing to show until it lands.
    refresh(app, &client).await;
    terminal.draw(|f| ui::draw(f, app))?;

    let (fetch_tx, mut fetch_rx) = mpsc::unbounded_channel::<(Plan, Gathered)>();
    let (err_tx, mut err_rx) = mpsc::unbounded_channel::<String>();
    let mut fetch = Fetcher::new(client.clone(), fetch_tx, err_tx);

    let mut ticker = tokio::time::interval(Duration::from_secs(app.refresh_secs.max(5)));
    // Delay, not the default Burst: after a stall (a suspended laptop, a slow
    // fetch) Burst fires every missed tick back-to-back. On the 3-second alarm
    // ticker that is a machine-gun of alarm sounds the moment the machine wakes.
    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    ticker.tick().await; // consume the immediate first tick
                         // A fast ticker to loop the audible alarm while an urgent state persists.
    let mut alarm_ticker = tokio::time::interval(Duration::from_secs(3));
    alarm_ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    alarm_ticker.tick().await;

    loop {
        tokio::select! {
            maybe_input = rx.recv() => {
                match maybe_input {
                    Some(Input::Key(key)) => handle_key(app, &fetch, key),
                    Some(Input::Mouse(m)) => handle_mouse(app, &fetch, m),
                    Some(Input::Resize) => {} // fall through to the redraw below
                    None => break,
                }
            }
            _ = ticker.tick() => {
                // Only auto-refetch when following the live edge; a fixed
                // history window doesn't change on its own (and never while
                // fetching is paused on a bad token / URL).
                if app.should_auto_refresh() {
                    fetch.request(app);
                }
            }
            Some((p, g)) = fetch_rx.recv() => {
                fetch.deliver(app, p, g);
            }
            Some(e) = err_rx.recv() => {
                app.set_last_error(e);
            }
            _ = alarm_ticker.tick() => {
                let now = now_ms();
                // Tell a running `sugarrush watch` that the dashboard is up, so
                // it stays quiet instead of alarming alongside us.
                // Only claim the alarm when this window actually covers
                // everything the daemon would. The TUI alerts on the active
                // site alone, so with several configured it must not silence a
                // watcher that is handling all of them — that hole meant a
                // caregiver's other sites went unalarmed while the dashboard
                // was open.
                sync_tui_alarm_claim(app.demo, app.sites.len(), now);
                if !app.demo {
                    // Read the other side of the handshake too: until now
                    // nothing ever did, so a dead watcher and a quiet night
                    // looked identical from in here.
                    app.watcher_alive = watch::is_alive(watch::Role::Watch, now);
                    app.watcher_seen |= app.watcher_alive;
                }
                // Re-classify locally every few seconds (no network) so a sensor
                // gap escalates to a Stale alarm promptly instead of waiting for
                // the next full refresh.
                // The full reaction, not a partial copy of it: this used to
                // classify and sound but never consume a notification or a
                // push, so a transition between refreshes waited out the whole
                // refresh interval before it was announced.
                let r = app.react(now);
                deliver(app, r, &fetch);
                // Retry the connection sooner than the normal interval when down.
                if app.should_retry(now) {
                    fetch.request(app);
                }
            }
        }

        if app.should_quit {
            break;
        }
        // Rebuild the client and reload when the active site changed.
        if app.site_dirty {
            match Client::for_site(app.active_site()) {
                Ok(c) => {
                    client = c;
                    fetch.client = client.clone();
                    // New credentials/URL — a previous pause no longer applies.
                    app.resume_fetching();
                    fetch.request(app);
                }
                Err(e) => app.set_last_error(e.to_string()),
            }
            app.site_dirty = false;
        }
        // Rebuild the ticker if the refresh interval was changed in settings.
        if app.refresh_dirty {
            ticker = tokio::time::interval(Duration::from_secs(app.refresh_secs.max(5)));
            ticker.tick().await;
            app.refresh_dirty = false;
        }
        terminal.draw(|f| ui::draw(f, app))?;
    }
    Ok(())
}

/// Dispatch a keypress, either into the date-jump prompt or the dashboard.
fn handle_key(app: &mut App, fetch: &Fetcher, key: KeyEvent) {
    // Ctrl+C / Ctrl+D always quit — raw mode delivers these as keys, not signals.
    if key.modifiers.contains(KeyModifiers::CONTROL)
        && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d'))
    {
        app.should_quit = true;
        return;
    }

    if app.date_input.is_some() {
        handle_date_input(app, fetch, key.code);
        return;
    }

    // The overlay is up: any key dismisses it, on whatever screen it was opened
    // from. This used to sit inside the dashboard branch, so a `?` pressed on
    // the followers screen could only be cleared by leaving that screen.
    if app.show_help {
        app.show_help = false;
        return;
    }

    if app.screen == Screen::Followers {
        match key.code {
            KeyCode::Char('q') => app.should_quit = true,
            KeyCode::Char('m') | KeyCode::Esc => app.toggle_followers(),
            KeyCode::Char('s') => app.toggle_settings(),
            KeyCode::Char('r') => fetch.request(app),
            KeyCode::Char('?') => app.show_help = true,
            KeyCode::Down | KeyCode::Char('j') => app.scroll_followers(1),
            KeyCode::Up | KeyCode::Char('k') => app.scroll_followers(-1),
            KeyCode::PageDown => app.scroll_followers(5),
            KeyCode::PageUp => app.scroll_followers(-5),
            KeyCode::Home => app.select_follower_edge(false),
            KeyCode::End => app.select_follower_edge(true),
            KeyCode::Enter => {
                if let Some(name) = app.selected_follower().map(str::to_owned) {
                    if app.activate_site(&name) {
                        app.screen = Screen::Dashboard;
                        fetch.request(app);
                    }
                }
            }
            KeyCode::Char('a') => {
                if let Some(name) = app.selected_follower().map(str::to_owned) {
                    let until = now_ms()
                        + app
                            .alerts_for_site(
                                app.sites
                                    .iter()
                                    .position(|site| site.name == name)
                                    .unwrap_or(0),
                            )
                            .snooze_minutes
                            .max(1)
                            * 60_000;
                    if app.demo {
                        app.status = Some(format!("demo: snoozed {name}"));
                    } else {
                        match watch::set_snooze(Some(until), watch::SnoozeTarget::Site(&name)) {
                            Ok(_) => app.status = Some(format!("snoozed {name}")),
                            Err(e) => app.status = Some(format!("snooze failed: {e}")),
                        }
                    }
                }
            }
            _ => {}
        }
        return;
    }
    if app.screen == Screen::Settings {
        handle_settings_key(app, fetch, key.code);
        return;
    }

    match key.code {
        KeyCode::Char('q') => app.should_quit = true,
        // Esc backs out, everywhere: it closes the help overlay and cancels a
        // prompt (handled above), and here it returns to the live edge. It used
        // to quit the app outright, which is a lot to trigger by reflex.
        KeyCode::Esc => {
            if app.view.is_live() {
                app.status = Some("press q to quit".to_string());
            } else {
                app.view.follow();
                fetch.request(app);
            }
        }
        KeyCode::Char('?') => app.show_help = true,
        KeyCode::Char('s') => app.toggle_settings(),
        KeyCode::Char('u') => app.toggle_units(),
        // An explicit refresh is also how the user retries after a bad
        // token/URL paused automatic fetching.
        KeyCode::Char('r') => {
            app.resume_fetching();
            fetch.request(app);
        }
        KeyCode::Tab => {
            app.cycle_graph_view(1);
            fetch.request(app);
        }
        KeyCode::BackTab => {
            app.cycle_graph_view(-1);
            fetch.request(app);
        }
        // Pan / zoom / jump operate on the timeline, not the AGP profile.
        KeyCode::Char('h') | KeyCode::Left if !app.is_agp() => {
            app.view.pan_back(now_ms());
            fetch.request(app);
        }
        KeyCode::Char('l') | KeyCode::Right if !app.is_agp() => {
            app.view.pan_forward(now_ms());
            fetch.request(app);
        }
        // Whole-window paging and a jump to the far edge of the overview: the
        // keyboard equivalents of dragging and clicking the minimap, which was
        // otherwise mouse-only.
        KeyCode::Char('H') | KeyCode::PageUp if !app.is_agp() => {
            app.view.page_back(now_ms());
            fetch.request(app);
        }
        KeyCode::Char('L') | KeyCode::PageDown if !app.is_agp() => {
            app.view.page_forward(now_ms());
            fetch.request(app);
        }
        KeyCode::End if !app.is_agp() => {
            app.view.jump_to_oldest(now_ms(), app.minimap_span_ms);
            fetch.request(app);
        }
        KeyCode::Char('+') | KeyCode::Char('=') if !app.is_agp() => {
            app.view.zoom_in();
            fetch.request(app);
        }
        KeyCode::Char('-') | KeyCode::Char('_') if !app.is_agp() => {
            app.view.zoom_out();
            fetch.request(app);
        }
        KeyCode::Char('f') | KeyCode::Home if !app.is_agp() => {
            app.view.follow();
            fetch.request(app);
        }
        KeyCode::Char('g') if !app.is_agp() => app.begin_date_input(),
        // Walk day by day without typing a date each time — "how was last
        // night?" is the common case, and `g` makes you spell it out.
        KeyCode::Char('[') if !app.is_agp() => {
            app.view.shift_day(-1, now_ms());
            fetch.request(app);
        }
        KeyCode::Char(']') if !app.is_agp() => {
            app.view.shift_day(1, now_ms());
            fetch.request(app);
        }
        KeyCode::Char('n') => app.next_site(),
        KeyCode::Char('m') => {
            app.toggle_followers();
            // Fetch on entry: the list is the whole point of the screen, and
            // waiting out the refresh interval to see it reads as broken.
            if app.screen == Screen::Followers {
                fetch.request(app);
            }
        }
        KeyCode::Char('a') => {
            app.snooze_alarm(now_ms());
            // Hand the snooze to the daemon as well, or closing the dashboard
            // un-silences an alarm someone deliberately silenced: the watcher
            // stops deferring the moment the TUI's heartbeat goes stale.
            // Best-effort — a dashboard with no daemon configured still snoozes
            // itself.
            if !app.demo {
                let _ = watch::set_snooze(
                    app.snooze_until(),
                    watch::SnoozeTarget::Site(&app.active_site().name),
                );
            }
        }
        KeyCode::Char('e') => app.export_window(now_ms()),
        _ => {}
    }
}

/// Handle a mouse event: a press or drag over the minimap seeks the main
/// window to that time.
fn handle_mouse(app: &mut App, fetch: &Fetcher, m: MouseEvent) {
    if !app.minimap_enabled || app.screen != Screen::Dashboard {
        return;
    }
    let seeking = matches!(m.kind, MouseEventKind::Down(_) | MouseEventKind::Drag(_));
    if seeking && app.minimap_seek(m.column, m.row, now_ms()) {
        fetch.request(app);
    }
}

/// Handle keys on the settings screen. All edits apply live; `w` persists.
fn handle_settings_key(app: &mut App, fetch: &Fetcher, code: KeyCode) {
    if let Some(action) = app.settings_exit {
        match code {
            KeyCode::Char('w') => {
                if app.save_config() {
                    app.finish_settings_exit(action);
                }
            }
            KeyCode::Char('d') => {
                app.discard_settings();
                app.finish_settings_exit(action);
            }
            KeyCode::Esc => app.cancel_settings_exit(),
            _ => {}
        }
        return;
    }
    // A row being edited as text swallows the keys — otherwise typing a URL
    // would trigger the single-letter shortcuts underneath it.
    if app.field_edit.is_some() {
        match code {
            KeyCode::Esc => app.cancel_field_edit(),
            KeyCode::Enter => app.commit_field_edit(),
            KeyCode::Backspace => app.field_edit_backspace(),
            KeyCode::Char(c) => app.field_edit_push(c),
            _ => {}
        }
        return;
    }
    match code {
        KeyCode::Char('q') => app.request_settings_exit(app::SettingsExit::Quit),
        KeyCode::Char('s') | KeyCode::Esc => app.request_settings_exit(app::SettingsExit::Back),
        KeyCode::Char('j') | KeyCode::Down => app.settings_move(1),
        KeyCode::Char('k') | KeyCode::Up => app.settings_move(-1),
        KeyCode::Char('h') | KeyCode::Left | KeyCode::Char('-') => app.settings_adjust(-1),
        KeyCode::Char('l') | KeyCode::Right | KeyCode::Char('+') | KeyCode::Char('=') => {
            app.settings_adjust(1)
        }
        KeyCode::Enter => match app.selected_field() {
            app::Field::TestAlarm => app.run_alarm_test(),
            app::Field::TestSite => {
                app.view.follow();
                app.status = Some("testing site for a fresh reading…".into());
                fetch.request(app);
            }
            app::Field::AddSite => app.add_site(),
            app::Field::RemoveSite => app.remove_site(),
            _ => {
                app.begin_field_edit();
            }
        },
        KeyCode::Char('?') => app.show_help = true,
        KeyCode::Char('w') => {
            app.save_config();
        }
        _ => {}
    }
}

/// Handle keys while the date-jump prompt is open.
fn handle_date_input(app: &mut App, fetch: &Fetcher, code: KeyCode) {
    match code {
        KeyCode::Esc => app.cancel_date_input(),
        KeyCode::Backspace => {
            if let Some(buf) = app.date_input.as_mut() {
                buf.pop();
            }
        }
        KeyCode::Char(c) if c.is_ascii_digit() || c == '-' => {
            if let Some(buf) = app.date_input.as_mut() {
                buf.push(c);
            }
        }
        KeyCode::Enter => {
            let buf = app.date_input.take().unwrap_or_default();
            match view::parse_date(&buf) {
                Some(date) => {
                    app.view.jump_to(date, now_ms());
                    fetch.request(app);
                }
                None => app.set_last_error(format!("invalid date '{buf}', use YYYY-MM-DD")),
            }
        }
        _ => {}
    }
}

/// What a refresh should fetch, snapshotted from `App` *before* the fetch
/// starts.
///
/// The run loop used to `await` the whole fetch chain inside its `select!`,
/// which meant a slow Nightscout froze keyboard input, the redraw and — worst
/// of all — the 3-second alarm ticker. Five sequential requests at a 12s
/// timeout is a minute of a dashboard that looks alive and answers nothing.
/// Splitting the work in three (plan / gather / apply) lets the gather half run
/// on its own task while the loop keeps drawing and sounding the alarm.
struct Plan {
    now: i64,
    start: i64,
    end: i64,
    count: usize,
    live: bool,
    demo: bool,
    /// Whether the sensor-start lookup is due this cycle.
    sensor: bool,
    minimap_span_ms: i64,
    minimap: bool,
    /// `Some((start, end, count))` when the heavy history buffer is due.
    agp: Option<(i64, i64, usize)>,
    followers: Option<Vec<(config::Site, config::Alerts)>>,
    cache_key: String,
    cache_enabled: bool,
    cache_days: u32,
}

/// Whatever the network returned. Every field is best-effort except `entries`,
/// whose failure is what marks the app offline.
#[derive(Default)]
struct Gathered {
    entries: Option<nightscout::Result<Vec<nightscout::Entry>>>,
    treatments: Option<nightscout::Result<Vec<nightscout::Treatment>>>,
    device: Option<
        nightscout::Result<(
            nightscout::DeviceStatus,
            Option<Vec<nightscout::Prediction>>,
        )>,
    >,
    sensor_start: Option<nightscout::Result<Option<i64>>>,
    agp: Option<nightscout::Result<Vec<nightscout::Entry>>>,
    minimap: Option<nightscout::Result<Vec<nightscout::Entry>>>,
    live_edge: Option<Vec<nightscout::Entry>>,
    followers: Option<Vec<follow::SiteStatus>>,
}

fn plan(app: &mut App, now: i64) -> Plan {
    let (start, end) = app.view.bounds(now);
    app.view_start = start;
    app.view_end = end;
    // The history buffer is heavy (up to 90 days), so outside the AGP view it
    // only refreshes when empty or older than 15 minutes.
    let agp_stale = now - app.agp_fetched_ms > 15 * 60 * 1000;
    let agp = (app.is_agp() || app.agp_entries.is_empty() || agp_stale)
        .then(|| (now - app.agp_span_ms(), now, app.agp_fetch_count()));
    Plan {
        now,
        start,
        end,
        count: app.view.span.fetch_count(),
        live: app.view.is_live(),
        demo: app.demo,
        // A sensor session lasts ten to fourteen days; refreshing this every
        // cycle spent a second `/treatments` request on a number that changes
        // twice a month.
        sensor: app.view.is_live()
            && (app.sensor_start_ms.is_none() || now - app.sensor_fetched_ms > 30 * 60 * 1000),
        minimap_span_ms: app.minimap_span_ms,
        minimap: app.minimap_enabled && (app.view.is_live() || app.minimap_entries.is_empty()),
        agp,
        followers: (app.sites.len() > 1 && app.screen == Screen::Followers).then(|| {
            app.sites
                .iter()
                .cloned()
                .enumerate()
                .map(|(i, site)| (site, app.alerts_for_site(i)))
                .collect()
        }),
        cache_key: app.active_site().stable_id(),
        cache_enabled: app.cache_enabled,
        cache_days: app.cache_days,
    }
}

/// The network half. Touches no `App`, so it can run on its own task.
async fn gather(client: &Client, p: &Plan) -> Gathered {
    let mut g = Gathered::default();
    if p.demo {
        return g;
    }
    let entries = client.entries_range(p.start, p.end, p.count).await;
    let online = entries.is_ok();
    g.entries = Some(entries);

    // Supplementary reads only happen when the primary one succeeded — on an
    // outage we skip them, so a stalled network can't pile up doomed requests.
    //
    // They are independent of each other, so they go out together. Awaited in
    // sequence they cost the sum of five round trips against a distant
    // Nightscout; concurrently they cost the slowest one. Nothing here shares
    // state — each writes its own field of `Gathered`.
    if online {
        let treatments = client.treatments(p.start, p.end);
        let device = async {
            if p.live {
                Some(client.device_status().await)
            } else {
                None
            }
        };
        let sensor = async {
            if p.sensor {
                Some(client.sensor_start().await)
            } else {
                None
            }
        };
        let agp = async {
            match p.agp {
                Some((s, e, n)) => Some(client.entries_range(s, e, n).await),
                None => None,
            }
        };
        let minimap = async {
            if p.minimap {
                Some(
                    client
                        .entries_range(
                            p.now - p.minimap_span_ms,
                            p.now,
                            2 * p.minimap_span_ms as usize / 60_000,
                        )
                        .await,
                )
            } else {
                None
            }
        };
        // While browsing history the primary fetch is a historical window, so
        // the live edge has to be fetched separately — the alarm must not go
        // quiet just because someone is looking at last night.
        let live_edge = async {
            if p.live {
                None
            } else {
                client
                    .entries_range(p.now - 3_600_000, p.now, 24)
                    .await
                    .ok()
            }
        };

        let (treatments, device, sensor, agp, minimap, live_edge) =
            tokio::join!(treatments, device, sensor, agp, minimap, live_edge);
        g.treatments = Some(treatments);
        g.device = device;
        g.sensor_start = sensor;
        g.agp = agp;
        g.minimap = minimap;
        g.live_edge = live_edge;
    }
    if let Some(sites) = &p.followers {
        g.followers = Some(follow::poll(sites, p.now).await);
    }
    g
}

/// The mutation half: fold a finished `Gathered` back into `App`, then run the
/// alert machine. Synchronous, so the run loop can never block in here.
///
/// Returns the `Reaction` the alarm machine produced, for the caller to
/// deliver — the announcements involve network and D-Bus, which do not belong
/// on the run loop.
#[must_use]
fn apply(app: &mut App, p: &Plan, g: Gathered) -> app::Reaction {
    let now = p.now;

    // Demo mode: synthesize everything locally, no network.
    if p.demo {
        app.entries = demo::entries(p.start, p.end);
        app.mark_online(now);
        if p.live {
            app.predictions = predict::ar2(&app.entries);
            app.device = demo::device();
            app.treatments = demo::treatments(now);
        } else {
            app.predictions.clear();
        }
        if app.minimap_enabled {
            app.minimap_entries = demo::entries(now - app.minimap_span_ms, now);
        }
        // Always synthesized: the stats panel reads this clinical-window
        // buffer even outside the AGP view.
        app.agp_entries = demo::entries(now - app.agp_span_ms(), now);
        if app.screen == Screen::Followers {
            let profiles: Vec<_> = (0..app.sites.len())
                .map(|idx| app.alerts_for_site(idx))
                .collect();
            app.followers = follow::demo(now, &profiles);
        }
        return app.react(now);
    }

    match g.entries {
        Some(Ok(entries)) => {
            if p.cache_enabled {
                if let Err(error) = history_cache::merge(&p.cache_key, &entries, now, p.cache_days)
                {
                    app.status = Some(format!("live · private cache update failed: {error}"));
                }
            }
            if p.live {
                let fresh = entries
                    .first()
                    .is_some_and(|entry| now - entry.date <= 3_600_000);
                if app.screen == Screen::Settings {
                    app.site_validated[app.site_idx] = fresh;
                    app.status = Some(if fresh {
                        "site test passed · fresh reading received".into()
                    } else {
                        "site test failed · no reading from the last hour".into()
                    });
                }
                app.live_edge = entries.first().cloned();
            }
            app.entries = entries;
            app.mark_online(now);
        }
        // Keep the last-known readings on screen; just flag the outage. A
        // config-level failure (bad token / URL) is not a transient outage —
        // App pauses retries after a few of them.
        Some(Err(e)) => {
            let permanent = e.is_permanent();
            app.mark_offline(now, e.to_string(), permanent);
            if p.cache_enabled {
                let cached = history_cache::load(&p.cache_key, p.start, p.end);
                if !cached.is_empty() {
                    if p.live {
                        app.live_edge = cached.first().cloned();
                    }
                    app.entries = cached;
                    app.status = Some("offline · showing private cached history".into());
                }
            }
        }
        None => {}
    }

    if app.online() {
        // Which supplementary reads failed. They're best-effort — the glucose
        // trace is what matters — but silently showing a stale IOB or a missing
        // carb marker as if it were current is its own kind of wrong, so the
        // dashboard says which part is missing.
        let mut missing: Vec<&str> = Vec::new();
        match g.treatments {
            Some(Ok(t)) => app.treatments = t,
            Some(Err(_)) => missing.push("treatments"),
            None => {}
        }
        if p.live {
            // One devicestatus fetch feeds both the uploader panel and the
            // forecast; falling back to the local AR2 projection when the
            // uploader publishes none (or the fetch failed).
            let published = match g.device {
                Some(Ok((status, predicted))) => {
                    app.device = status;
                    predicted
                }
                _ => {
                    missing.push("device");
                    None
                }
            };
            app.predictions = published.unwrap_or_else(|| predict::ar2(&app.entries));
            match g.sensor_start {
                Some(Ok(started)) => {
                    app.sensor_start_ms = started;
                    app.sensor_fetched_ms = now;
                }
                Some(Err(_)) => missing.push("sensor age"),
                // Not due this cycle — the cached value stands.
                None => {}
            }
        } else {
            app.predictions.clear();
        }
        match g.agp {
            Some(Ok(entries)) => {
                if p.cache_enabled {
                    if let Err(error) =
                        history_cache::merge(&p.cache_key, &entries, now, p.cache_days)
                    {
                        app.status = Some(format!("live · private cache update failed: {error}"));
                    }
                }
                app.agp_entries = entries;
                app.agp_fetched_ms = now;
            }
            Some(Err(_)) => missing.push("history"),
            None => {}
        }
        match g.minimap {
            Some(Ok(entries)) => app.minimap_entries = entries,
            Some(Err(_)) => missing.push("overview"),
            None => {}
        }
        if let Some(live) = g.live_edge {
            app.live_edge = live.first().cloned();
        }
        app.set_partial(&missing);
    } else if !p.live {
        app.predictions.clear();
    }

    if let Some(f) = g.followers {
        app.followers = f;
        if app
            .follower_selected
            .as_ref()
            .is_none_or(|name| !app.followers.iter().any(|site| &site.name == name))
        {
            app.follower_selected = app.followers.first().map(|site| site.name.clone());
        }
        if let Some(index) = app
            .follower_selected
            .as_ref()
            .and_then(|name| app.followers.iter().position(|site| &site.name == name))
        {
            app.follower_scroll = index;
        }
        app.follower_scroll = app
            .follower_scroll
            .min(app.followers.len().saturating_sub(1));
    }

    // Alert evaluation and notifications run every refresh, online or not, so a
    // sensor gap still escalates to a Stale alarm.
    app.react(now)
}

/// Deliver what the alarm machine decided: desktop toast, webhook, sound.
///
/// The one place that turns a `Reaction` into side effects for the dashboard.
/// Announcements that can't be delivered are dropped, never re-queued — a
/// notification held back because desktop notifications were off used to fire
/// the moment they were switched on, for an episode long finished.
fn deliver(app: &mut App, r: app::Reaction, fetch: &Fetcher) {
    // Record what the alarm did before delivering it: "did it go off last
    // night, and for how long" is a question the journal could only answer if
    // the daemon happened to be running under systemd, and never for alarms the
    // dashboard handled.
    if !app.demo {
        let site = app.active_site().name.clone();
        if let Some(a) = r.notification {
            alertlog::record(&site, "alert", a, app.live_latest().map(|e| e.sgv));
        }
        if r.recovered {
            alertlog::record(
                &site,
                "recovered",
                r.state,
                app.live_latest().map(|e| e.sgv),
            );
        }
    }
    if let Some(a) = r.notification {
        if app.alerts.desktop {
            // A discarded result meant "Desktop: on" could be a lie: with no
            // notification daemon running the D-Bus call fails and nothing is
            // shown, which — paired with a failing audio player — is two dead
            // channels reported as healthy.
            let accepted = notify(
                a,
                app.live_latest().map(|e| e.sgv),
                app.units,
                app.alerts.notify_content,
            );
            app.notify_failed = !accepted;
            if !app.demo {
                alertlog::record_delivery(
                    &app.active_site().name,
                    Some(&app.active_site().stable_id()),
                    "desktop",
                    if accepted { "accepted" } else { "rejected" },
                    a,
                );
            }
        }
    }
    if let Some(msg) = r.predictive {
        if app.alerts.desktop {
            if app.alerts.notify_content {
                let _ = notify_text(&msg);
            } else {
                let _ = notify_text("alert — open sugarrush");
            }
        }
    }
    if let Some((url, msg)) = r.push {
        // The push webhook is a safety channel (unacknowledged-urgent
        // escalation); a dead URL must not fail silently.
        let errors = fetch.errors.clone();
        let site = app.active_site().name.clone();
        let site_id = app.active_site().stable_id();
        let state = r.state;
        tokio::spawn(async move {
            let accepted = push(&url, &msg).await;
            alertlog::record_delivery(
                &site,
                Some(&site_id),
                "webhook",
                if accepted { "accepted" } else { "rejected" },
                state,
            );
            if !accepted {
                let _ = errors.send("push notification failed — check push_url".to_string());
            }
        });
    }
    if r.sound {
        sound::alarm(app.alarm_tone());
    }
}

/// Hands refreshes to background tasks so the run loop never awaits the
/// network.
///
/// Two properties matter for safety. It never blocks: `request` returns
/// immediately, so keys, the redraw and the 3-second alarm ticker keep running
/// through a Nightscout that has stopped answering. And it never queues: while
/// a fetch is out, further requests set `pending` instead of spawning, so
/// holding down `h` to pan can't stack a task per keypress behind a 12-second
/// timeout.
#[derive(Clone)]
struct Fetcher {
    client: Client,
    tx: mpsc::UnboundedSender<(Plan, Gathered)>,
    /// Background failures that need to reach `app.last_error` — the push
    /// webhook is fired off-loop, and a dead URL must not fail silently.
    errors: mpsc::UnboundedSender<String>,
    in_flight: Arc<AtomicBool>,
    pending: Arc<AtomicBool>,
}

impl Fetcher {
    fn new(
        client: Client,
        tx: mpsc::UnboundedSender<(Plan, Gathered)>,
        errors: mpsc::UnboundedSender<String>,
    ) -> Self {
        Self {
            client,
            tx,
            errors,
            in_flight: Arc::new(AtomicBool::new(false)),
            pending: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Snapshot what to fetch and start it. Returns at once.
    fn request(&self, app: &mut App) {
        // Planning is synchronous and updates the visible window, so the
        // redraw that follows this keypress is already correct — only the data
        // arrives late.
        let p = plan(app, now_ms());
        if self.in_flight.swap(true, Ordering::SeqCst) {
            self.pending.store(true, Ordering::SeqCst);
            return;
        }
        let (client, tx, in_flight) =
            (self.client.clone(), self.tx.clone(), self.in_flight.clone());
        tokio::spawn(async move {
            let g = gather(&client, &p).await;
            in_flight.store(false, Ordering::SeqCst);
            let _ = tx.send((p, g));
        });
    }

    /// Fold a finished fetch into `App`, and start the next one if the view
    /// moved while this was in flight.
    fn deliver(&self, app: &mut App, p: Plan, g: Gathered) {
        let reaction = apply(app, &p, g);
        deliver(app, reaction, self);
        if self.pending.swap(false, Ordering::SeqCst) {
            self.request(app);
        }
    }
}

/// Fetch and apply in one go. Used on the paths that genuinely have nothing
/// else to do while waiting — startup, a site switch, an explicit `r`.
async fn refresh(app: &mut App, client: &Client) {
    let p = plan(app, now_ms());
    let g = gather(client, &p).await;
    let r = apply(app, &p, g);
    if let Some((url, msg)) = r.push.clone() {
        // The push webhook is a safety channel (unacknowledged-urgent
        // escalation); a dead URL must not fail silently.
        if !push(&url, &msg).await {
            app.set_last_error("push notification failed — check push_url".to_string());
        }
    }
    // The rest of the reaction still has to be delivered; only the push is
    // awaited here, on the startup path that has nothing else to do.
    if let Some(a) = r.notification {
        if app.alerts.desktop {
            app.notify_failed = !notify(
                a,
                app.live_latest().map(|e| e.sgv),
                app.units,
                app.alerts.notify_content,
            );
        }
    }
    if r.sound {
        sound::alarm(app.alarm_tone());
    }
}

/// Fire a best-effort desktop notification for an alert.
pub(crate) fn notify(
    alert: alert::Alert,
    sgv: Option<f64>,
    units: units::Units,
    content: bool,
) -> bool {
    // Content-free mode still fires — and still as critical, so it breaks
    // through Do Not Disturb — but says nothing a lock screen shouldn't show.
    if !content {
        return desktop_notify("alert — open sugarrush", alert.urgency() == "critical");
    }
    let body = match sgv {
        Some(v) => format!("{} · {} {}", alert.label(), units.format(v), units.label()),
        None => alert.label().to_string(),
    };
    desktop_notify(&body, alert.urgency() == "critical")
}

/// Fire a plain desktop notification (used for predictive alerts).
pub(crate) fn notify_text(body: &str) -> bool {
    desktop_notify(body, false)
}

/// Cross-platform desktop notification (Linux / macOS / Windows) via
/// notify-rust. Best-effort — errors are ignored.
fn desktop_notify(body: &str, critical: bool) -> bool {
    let mut n = notify_rust::Notification::new();
    n.summary("sugarrush").body(body).appname("sugarrush");
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        n.urgency(if critical {
            notify_rust::Urgency::Critical
        } else {
            notify_rust::Urgency::Normal
        });
    }
    #[cfg(not(all(unix, not(target_os = "macos"))))]
    {
        let _ = critical;
    }
    n.show().is_ok()
}

/// POST an alert message to a webhook / ntfy topic. Returns whether the request
/// was accepted (2xx), so the caller can surface a dead push URL.
pub(crate) async fn push(url: &str, message: &str) -> bool {
    let Ok(client) = reqwest::Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
    else {
        return false;
    };
    client
        .post(url)
        .body(message.to_string())
        .send()
        .await
        .map(|r| r.status().is_success())
        .unwrap_or(false)
}

/// Current time in epoch milliseconds.
/// Report coerced config values on stderr. Silence here would just be a
/// quieter version of the bug: the user believes the thresholds they wrote are
/// the thresholds in force.
pub(crate) fn warn_about_config(warnings: &[String]) {
    for w in warnings {
        eprintln!("sugarrush: config: {w}");
    }
    // The person running the daemon is the one least likely to open the TUI,
    // and so the one who never learned their token file went group-readable.
    if Config::perms_too_open() {
        eprintln!(
            "sugarrush: config.toml is readable by others — run: chmod 600 ~/.config/sugarrush/config.toml"
        );
    }
}

pub(crate) fn now_ms() -> i64 {
    chrono::Utc::now().timestamp_millis()
}

fn setup_terminal(mouse: bool) -> Result<Terminal<CrosstermBackend<Stdout>>> {
    enable_raw_mode().context("failed to enable raw mode")?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen).context("failed to enter alternate screen")?;
    if mouse {
        execute!(stdout, EnableMouseCapture).context("failed to enable mouse capture")?;
    }
    Terminal::new(CrosstermBackend::new(stdout)).context("failed to create terminal")
}

fn restore_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
    restore();
    terminal.show_cursor().ok();
    Ok(())
}

/// Undo the terminal setup. Safe to call from anywhere, including a panic hook,
/// as it operates on `stdout` directly rather than the `Terminal`.
fn restore() {
    disable_raw_mode().ok();
    // DisableMouseCapture is harmless if capture was never enabled.
    execute!(io::stdout(), DisableMouseCapture, LeaveAlternateScreen).ok();
}

/// Restore the terminal before the default panic handler prints, so a panic
/// leaves a usable shell and a readable message instead of a garbled screen.
fn install_panic_hook() {
    let original = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore();
        original(info);
    }));
}

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

    fn app() -> App {
        let cfg = Config::demo();
        let alerts = cfg.alerts.resolve(cfg.units);
        let sites = cfg.resolve_sites().unwrap();
        let mut a = App::new(&cfg, alerts, sites);
        a.demo = false;
        a
    }

    #[test]
    fn only_a_single_site_tui_claims_the_alarm_handoff() {
        assert!(tui_claims_alarm(false, 1));
        assert!(!tui_claims_alarm(false, 2));
        assert!(!tui_claims_alarm(false, 3));
        assert!(!tui_claims_alarm(true, 1));
    }

    /// `--demo` means synthetic data and no network. On `watch` it used to be
    /// ignored, so the alarm daemon started against the real site and the real
    /// config — the opposite of what the flag says, with nothing printed.
    #[test]
    fn demo_is_rejected_by_the_subcommands_that_cannot_honour_it() {
        for (mode, expected) in [
            (Some(Mode::Watch), Some("watch")),
            (
                Some(Mode::Export {
                    days: 0,
                    dir: None,
                    site: None,
                    all: false,
                }),
                Some("export"),
            ),
            (
                Some(Mode::Status {
                    format: status::Format::Text,
                }),
                Some("status"),
            ),
            (Some(Mode::Waybar), Some("waybar")),
            // The dashboard is what --demo is for.
            (None, None),
            (
                Some(Mode::Tui {
                    screen: Screen::Dashboard,
                    demo: true,
                }),
                None,
            ),
            // Neither of these reads config or the network at all.
            (Some(Mode::About), None),
            (Some(Mode::Version), None),
        ] {
            assert_eq!(subcommand_without_demo(&mode), expected, "for {mode:?}");
        }
    }

    /// The supplementary reads are independent, so they must go out together.
    /// Awaited in sequence they cost the sum of five round trips against a
    /// distant Nightscout — the whole point of moving the fetch off the run
    /// loop was that those seconds add up.
    #[tokio::test]
    async fn the_supplementary_reads_run_concurrently() {
        let site = nightscout::fake::serve_slow(120).await;
        let client = Client::for_site(&site).unwrap();
        let mut app = app();
        app.minimap_enabled = true;
        let p = plan(&mut app, now_ms());

        let started = std::time::Instant::now();
        let g = gather(&client, &p).await;
        let elapsed = started.elapsed();

        assert!(g.entries.is_some());
        // The primary read plus one concurrent round of the rest: about two
        // delays, not the six a sequential chain would cost.
        assert!(
            elapsed < Duration::from_millis(120 * 4),
            "the supplementary reads look sequential: {elapsed:?}"
        );
    }

    /// A sensor session lasts ten to fourteen days. Asking every cycle spent a
    /// second `/treatments` request on a number that changes twice a month.
    #[test]
    fn the_sensor_lookup_is_not_repeated_every_cycle() {
        let mut app = app();
        let now = now_ms();

        // Nothing cached yet: it has to be asked for.
        assert!(plan(&mut app, now).sensor);

        // Once answered, it stands for a while.
        app.sensor_start_ms = Some(now - 3 * 86_400_000);
        app.sensor_fetched_ms = now;
        assert!(!plan(&mut app, now + 60_000).sensor);
        assert!(!plan(&mut app, now + 29 * 60_000).sensor);

        // …but not forever, or a sensor change would never show up.
        assert!(plan(&mut app, now + 31 * 60_000).sensor);
    }

    /// `sugarrush snooze 15m` at 3am has to be unambiguous, and must not
    /// silently accept something that means a different thing than intended.
    #[test]
    fn snooze_durations_parse_the_way_people_write_them() {
        for (input, expected) in [
            ("15m", Some(15)),
            ("15", Some(15)),
            ("2h", Some(120)),
            ("1h", Some(60)),
            (" 45M ", Some(45)),
            ("off", Some(0)),
            ("cancel", Some(0)),
            ("0", Some(0)),
            // A snooze that outlives the night it was set in is a trap.
            ("25h", None),
            ("2000", None),
            ("bogus", None),
            ("-5", None),
            ("", None),
        ] {
            assert_eq!(parse_snooze(input), expected, "for {input:?}");
        }
    }

    #[test]
    fn snapshot_is_documented_in_help() {
        let row = COMMANDS
            .iter()
            .find(|(usage, _)| usage.starts_with("sugarrush snapshot"))
            .expect("snapshot has a help row");
        assert_eq!(row.0, "sugarrush snapshot [--hours N] [--days N]");
        assert!(row.1.contains("JSON"));
    }

    /// `--help`, the man page and the README table are three places one
    /// command list can rot. They render from `COMMANDS`; this keeps the
    /// README honest, since it is the only one not generated at runtime.
    #[test]
    fn the_readme_lists_exactly_the_commands_we_ship() {
        let readme = include_str!("../README.md");
        let table = readme
            .split("## Commands")
            .nth(1)
            .and_then(|s| s.split("## ").next())
            .expect("no Commands section in README.md");

        for (usage, what) in COMMANDS {
            // The README escapes the pipes in `[15m|2h|off]` for the table.
            let usage_md = usage.replace('|', "\\|");
            assert!(
                table.contains(&format!("`{usage_md}`")),
                "README's command table is missing {usage:?}"
            );
            assert!(
                table.contains(what),
                "README's entry for {usage:?} doesn't say {what:?}"
            );
        }

        // …and nothing extra: a row for a command that no longer exists is the
        // same bug in the other direction.
        let rows = table
            .lines()
            .filter(|l| l.starts_with("| `sugarrush"))
            .count();
        assert_eq!(
            rows,
            COMMANDS.len(),
            "README lists {rows} commands, we ship {}",
            COMMANDS.len()
        );
    }

    /// The man page has to be valid roff, and carry every command.
    #[test]
    fn the_man_page_documents_every_command() {
        // `roff` escapes the leading-dash problem; without it `.B --demo`
        // starts a line with a control character man interprets.
        assert_eq!(roff("--demo"), "\\-\\-demo");
        for (usage, _) in COMMANDS {
            assert!(!roff(usage).contains(" -"), "unescaped dash in {usage:?}");
        }
    }

    /// `--help` is read in a terminal, so it has to fit one. The command
    /// signatures outgrew the fixed pad and every row past it ran to 138
    /// columns, which is past the wrap point of any normal terminal.
    #[test]
    fn help_rows_fit_a_terminal() {
        // The widest thing we render, without capturing stdout: same inputs,
        // same rule as `two_column`.
        let widest = COMMANDS
            .iter()
            .map(|(usage, what)| row_width(usage, what, USAGE_PAD))
            .chain(
                OPTIONS
                    .iter()
                    .map(|(flag, what)| row_width(flag, what, OPTION_PAD)),
            )
            .max()
            .unwrap_or(0);
        assert!(
            widest <= 100,
            "the widest --help row is {widest} columns; wrap it or shorten the description"
        );
    }

    /// What `two_column` will print, in columns.
    fn row_width(left: &str, right: &str, pad: usize) -> usize {
        let left_len = left.chars().count();
        let indent = 4;
        if left_len <= pad {
            indent + pad + 1 + right.chars().count()
        } else {
            // Two lines; the wider is the description row.
            (indent + left_len).max(indent + pad + 1 + right.chars().count())
        }
    }

    fn fetcher(site: &config::Site) -> (Fetcher, mpsc::UnboundedReceiver<(Plan, Gathered)>) {
        let (tx, rx) = mpsc::unbounded_channel();
        let (etx, _) = mpsc::unbounded_channel();
        (Fetcher::new(Client::for_site(site).unwrap(), tx, etx), rx)
    }

    /// The run loop used to `await` the whole fetch chain inside its `select!`,
    /// so a Nightscout that accepted the connection and then went quiet froze
    /// keyboard input, the redraw and the 3-second alarm ticker for as long as
    /// the request timeouts took — up to a minute across five sequential reads.
    ///
    /// `request` must return immediately against exactly that server.
    #[tokio::test]
    async fn a_stalled_site_does_not_block_the_caller() {
        let site = nightscout::fake::serve_stalled().await;
        let (fetch, _rx) = fetcher(&site);
        let mut app = app();

        let t = std::time::Instant::now();
        fetch.request(&mut app);
        let elapsed = t.elapsed();

        assert!(
            elapsed < Duration::from_secs(1),
            "request() blocked for {elapsed:?} on a stalled site — the run loop \
             would have been frozen for that long, alarm included"
        );
        assert!(
            fetch.in_flight.load(Ordering::SeqCst),
            "the fetch should be out on its own task"
        );
    }

    /// Holding `h` to pan fires a refresh per keypress. Each one used to be
    /// awaited in turn; spawning them instead would just move the pile-up onto
    /// the task queue, with a 12-second timeout apiece. At most one is in
    /// flight, and the rest collapse into a single follow-up.
    #[tokio::test]
    async fn requests_made_while_a_fetch_is_out_collapse_into_one() {
        let site = nightscout::fake::serve_stalled().await;
        let (fetch, mut rx) = fetcher(&site);
        let mut app = app();

        for _ in 0..10 {
            fetch.request(&mut app);
        }

        assert!(fetch.in_flight.load(Ordering::SeqCst));
        assert!(
            fetch.pending.load(Ordering::SeqCst),
            "the later requests should be remembered, not dropped"
        );
        assert!(
            rx.try_recv().is_err(),
            "nothing can have been delivered — the site never answered"
        );
    }

    /// Planning is synchronous and moves the visible window, so the redraw that
    /// follows a keypress is correct even though the data arrives later.
    #[tokio::test]
    async fn planning_moves_the_window_before_the_fetch_returns() {
        let site = nightscout::fake::serve_stalled().await;
        let (fetch, _rx) = fetcher(&site);
        let mut app = app();
        app.view_start = 0;
        app.view_end = 0;

        fetch.request(&mut app);

        assert!(
            app.view_end > app.view_start,
            "the window should already be set when request() returns"
        );
    }
}