cmd-usage 0.7.25

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

/// Gauge width for the window bars when neither config nor `--bar-width` says
/// otherwise — cmduse's own default.
pub const DEFAULT_BAR_WIDTH: usize = 20;

/// ANSI styles — cmduse's palette, or empty strings when colour is off, so a
/// piped run never leaks SGR escapes.
pub struct Ink {
    pub colour: bool,
    /// Gauge width for the window bars (config / `--bar-width`).
    pub bar_width: usize,
    pub bold: &'static str,
    pub dim: &'static str,
    pub reset: &'static str,
    pub cyan: &'static str,
    pub green: &'static str,
    pub yellow: &'static str,
    pub red: &'static str,
}

impl Ink {
    pub fn new(colour: bool) -> Self {
        if colour {
            Self {
                colour,
                bar_width: DEFAULT_BAR_WIDTH,
                bold: crate::render::BOLD,
                dim: crate::render::DIM,
                reset: crate::render::RESET,
                cyan: crate::render::CYAN,
                green: crate::render::GREEN,
                yellow: crate::render::YELLOW,
                red: crate::render::RED,
            }
        } else {
            Self {
                colour,
                bar_width: DEFAULT_BAR_WIDTH,
                bold: "",
                dim: "",
                reset: "",
                cyan: "",
                green: "",
                yellow: "",
                red: "",
            }
        }
    }

    /// Override the gauge width (config / `--bar-width`); chains after `new`.
    pub fn width(mut self, width: usize) -> Self {
        self.bar_width = width;
        self
    }

    /// Colour a value without disturbing the caller's column padding: pad the
    /// text first, then wrap it.
    fn cyan_on(&self, text: String) -> String {
        format!("{}{text}{}", self.cyan, self.reset)
    }

    /// Secondary information — cmduse's `DIM`.
    fn dim_on(&self, text: String) -> String {
        format!("{}{text}{}", self.dim, self.reset)
    }

    fn bold_on(&self, text: String) -> String {
        format!("{}{text}{}", self.bold, self.reset)
    }

    /// Severity for a used/limit percentage — cmduse's thresholds.
    fn for_pct(&self, pct_used: f64) -> &'static str {
        if !self.colour {
            ""
        } else if pct_used >= 90.0 {
            self.red
        } else if pct_used >= 70.0 {
            self.yellow
        } else {
            self.green
        }
    }

    /// The share plus cmduse's gauge, and the row's only percentage in colour
    /// mode — the body drops its own `x% of limit` so the figure is not printed
    /// twice. The label is passed in because the endpoint's own percentage is
    /// printed verbatim (`53`, never `53.0`). Empty when colour is off, so the
    /// plain frame keeps its script-friendly layout and its own share.
    fn bar_label(&self, pct_used: f64, label: &str) -> String {
        if !self.colour {
            return String::new();
        }
        format!(
            "{}{label:>5}%{} {}",
            self.for_pct(pct_used),
            self.reset,
            crate::render::gauge(pct_used, 100.0, self.bar_width),
        )
    }
}

#[allow(clippy::too_many_arguments)]
/// One window row's inputs. The account's own meters and the local estimate both
/// go through this one builder, so the two branches cannot drift apart in which
/// fields a window row carries or in the order it carries them.
///
/// There is deliberately no cap *field* here: Go grants limits per model, so no
/// account-wide pool exists to divide by, and summing the per-model limits into
/// one ceiling read as a budget the console does not have (it meters each window
/// on its own basis) — that is where `$215` came from. The money pair comes back
/// the honest way instead: the server's own share back-solves the ceiling it is
/// metering against, so `used / implied` divides to exactly the share beside it.
struct RowSpec<'a> {
    label: &'a str,
    /// This store's own totals for the window.
    used: &'a Totals,
    /// The window's reset instant and its length in seconds. `None` on the local
    /// estimate's rolling 5h/weekly windows: those are cut at `now - window`, so
    /// they have no boundary to measure an elapsed share against.
    reset: Option<(i64, u64)>,
    /// The account's own share of the limit, when it answered — the console's
    /// figure, and the reason the endpoint is read at all. `None` on the local
    /// estimate, whose rows then show spend alone.
    share_pct: Option<f64>,
    /// The account's own verdict: a status it does not call `ok` rides beside
    /// the limit flag.
    status: Option<&'a str>,
    /// Whether an even-burn figure belongs on this row. True for the monthly
    /// window alone: that one is a budget, so "what even burn would have spent by
    /// now" is a fair comparison, where the 5-hour and weekly throttles would
    /// read the same number as a spend target.
    pro_rata: bool,
}

fn window_line(ink: &Ink, spec: &RowSpec<'_>, now_ms: i64) -> String {
    let reset = spec
        .reset
        .map(|(at, _)| duration(((at - now_ms) / 1000).max(0) as u64))
        .unwrap_or_default();
    let reset_text = if reset.is_empty() {
        String::new()
    } else if ink.colour {
        format!(" · resets in {reset}")
    } else {
        format!(" · resets {reset}")
    };
    // cmduse's field order is importance order, so a clipped watch frame keeps
    // the actionable parts: limit flag, pace warning, elapsed share, then the
    // informational pro-rata figure. Percentages come from core (one decimal);
    // duration (never rel_time) formats the ETA.
    let now_secs = (now_ms / 1000).max(0) as u64;
    let reset_at = spec.reset.map(|(at, _)| at as f64);
    let dur_secs = spec.reset.map(|(_, dur)| dur);
    let elapsed = dur_secs.and_then(|d| cmduse_core::elapsed_pct(reset_at, d, Some(now_secs)));
    let share = spec.share_pct.map(|p| p.max(0.0));
    // The ceiling the server's own share implies, in this store's dollars. No
    // pool is invented here: the console's percentage *is* the fraction of the
    // ceiling it meters against, so `spend / share` is the ceiling, and the pair
    // below divides to exactly the percentage printed beside it.
    let cap = share.and_then(|p| implied_cap(spec.used.cost, p));
    let pace = cap
        .and_then(|cap| {
            dur_secs.and_then(|d| {
                cmduse_core::pace_eta(reset_at, d, spec.used.cost, cap, now_secs)
                    .map(|secs| duration(secs as u64))
            })
        })
        .map(|eta| format!(" · {}on pace to hit cap in {eta}{}", ink.yellow, ink.reset))
        .unwrap_or_default();
    let thru = elapsed
        .map(|p| format!(" · {}window {p:.1}% elapsed{}", ink.dim, ink.reset))
        .unwrap_or_default();
    let by_now = match (spec.pro_rata, elapsed, cap) {
        (true, Some(p), Some(cap)) => format!(
            " · {}{} by now{}",
            ink.dim,
            money(cap * p / 100.0),
            ink.reset
        ),
        _ => String::new(),
    };
    let label = spec.label;
    // The account's own share is labelled, because the money beside it is this
    // store's spend and the two need not divide to each other (the server
    // meters higher). Same placement cmduse uses for the flag: on the window
    // it belongs to.
    let flag = if share.is_some_and(|p| p >= 100.0) {
        format!(" {}{}LIMIT EXCEEDED{}", ink.red, ink.bold, ink.reset)
    } else if spec.status.is_some_and(|s| !s.eq_ignore_ascii_case("ok")) {
        format!(
            " {}{}{}{}",
            ink.red,
            spec.status.unwrap_or_default(),
            ink.reset,
            ""
        )
    } else {
        String::new()
    };
    // No denominator is printed. `cap` is spent ÷ share, so printing it offered
    // a ceiling of ~$40 beside a documented $80 monthly limit and read as "my
    // limit is $40" — the console meters at roughly twice the cost this store
    // records, so the two bases never meet. It stays a local value for the pace
    // and the even-burn figure, both of which are ratios in this store's dollars.
    let paren = match (share, ink.colour) {
        // The gauge carries the share in colour mode; repeating it here read as
        // `5% ━━━━━ 12.34 · 5% of limit`. The plain frame has no gauge, so it
        // keeps the figure.
        (Some(_), true) => String::new(),
        (Some(p), false) => format!(" · {}% of limit", given_pct(p)),
        (None, _) => String::new(),
    };
    // Composed in pieces: the pair and the pro-rata figure are conditional, and
    // one format string for both branches is a placeholder count waiting to drift.
    let body = format!(
        "{}{paren}{reset_text}{flag}{pace}{thru}{by_now}",
        money(spec.used.cost)
    );
    if ink.colour {
        // The gauge bar belongs to the share that gates: the account's own
        // when it answered. The local estimate has no share, so its rows
        // carry no bar — spend alone, never a gauge against a pool.
        let bar = match share {
            Some(p) => format!("{} ", ink.bar_label(p, &given_pct(p))),
            None => String::new(),
        };
        format!(
            " {}{label:<8}{} {}{}{body}{}\n",
            ink.bold, ink.reset, bar, ink.dim, ink.reset,
        )
    } else {
        // The plain frame is the script-facing one: same field order,
        // no SGR (the Ink helpers are empty strings when colour is off).
        format!("  {label:<8} {body}\n")
    }
}

/// A percentage exactly as the endpoint published it.
///
/// The server sends integers (`"percent":53`), so `{:.1}` invented a decimal the
/// console never reports — and a tenth implies a precision its rounding does not
/// have. Local, computed percentages keep `pct`'s one decimal; this is only for
/// the values we are handed.
fn given_pct(value: f64) -> String {
    if (value - value.round()).abs() < f64::EPSILON {
        format!("{}", value.round() as i64)
    } else {
        format!("{:.1}", value)
    }
}

/// The ceiling a share implies, in this store's dollars: `spend / share`.
///
/// Kept for the pace and even-burn figures only — never printed, because it
/// contradicts the documented allowance. `None` on a zero share, which would
/// divide by it.
fn implied_cap(spend: f64, share_pct: f64) -> Option<f64> {
    (share_pct >= 0.05).then(|| spend * 100.0 / share_pct)
}

/// The account meter's own window boundary, when the endpoint gave one: its
/// reset instant together with the window's length, so the row can measure an
/// elapsed share and a pace against the server's clock rather than a guess.
fn meter_reset(meter: &crate::ocuse::api::Meter, dur_secs: Option<u64>) -> Option<(i64, u64)> {
    match (meter.reset_ms(), dur_secs) {
        (Some(at), Some(dur)) if dur > 0 => Some((at, dur)),
        _ => None,
    }
}

/// Is any of this model's windows over its share of the limit? Go meters per
/// model *and* per window, so being over the 5-hour cap counts like being over
/// the month. One verdict, shared with the watch loop's cap notification.
fn exceeded(model: &ModelUsage) -> bool {
    crate::ocuse::window::over_window(model).is_some()
}

fn model_row(ink: &Ink, model: &ModelUsage, total_cost: f64) -> String {
    let limit = match model.limit {
        Some(limit) => money(limit),
        None => ink.dim_on("—".into()),
    };
    let use_fraction = model.month_use();
    let use_text = use_fraction
        .map(|fraction| pct(fraction * 100.0, 100.0))
        .unwrap_or_else(|| "—".into());
    // Pad before colouring: SGR escapes would otherwise count as columns.
    let spent = ink.cyan_on(format!("{:>10}", money(model.month.cost)));
    let use_cell = match use_fraction {
        Some(fraction) => {
            let tone = ink.for_pct(fraction * 100.0);
            if tone.is_empty() {
                format!("{use_text:>7}")
            } else {
                format!("{tone}{use_text:>7}{}", ink.reset)
            }
        }
        None => ink.dim_on(format!("{use_text:>7}")),
    };
    // Actionable before informational (cmduse's ordering): the flag sits beside
    // the model so a clipped frame keeps it; the share is the first thing to go.
    let flag = if exceeded(model) {
        format!(" {}{}LIMIT EXCEEDED{}", ink.red, ink.bold, ink.reset)
    } else {
        String::new()
    };
    let share = if total_cost > 0.0 {
        ink.dim_on(format!(" {:>5.1}%", model.month.cost / total_cost * 100.0))
    } else {
        String::new()
    };
    format!(
        "{:<28}{flag} {:>7} {spent} {use_cell} {} {} {:>7}{share}\n",
        model.id,
        limit,
        // Go windows are per model too: 5h = 20% of the limit, weekly = 50%.
        window_cell(ink, model, model.five_hour.cost, 0.20),
        window_cell(ink, model, model.weekly.cost, 0.50),
        compact(model.month.requests),
    )
}

/// One rolling-window column, coloured against that model's own share of the
/// limit; models with no limit (free, or Zen-only) are dimmed instead.
fn window_cell(ink: &Ink, model: &ModelUsage, cost: f64, share: f64) -> String {
    let text = format!("{:>8}", money(cost));
    match model.limit.filter(|limit| *limit > 0.0) {
        Some(limit) => {
            let tone = ink.for_pct(cost / (limit * share) * 100.0);
            if tone.is_empty() {
                text
            } else {
                format!("{tone}{text}{}", ink.reset)
            }
        }
        None => ink.dim_on(text),
    }
}

/// `limit` rows to show; `usize::MAX` for all.
pub fn render_text(
    report: &Report,
    db_path: &str,
    rows: usize,
    colour: bool,
    bar_width: usize,
) -> String {
    let ink = Ink::new(colour).width(bar_width);
    let c = |text: String| ink.cyan_on(text);
    let mut out = String::new();
    out.push_str(&format!(
        "{}OpenCode usage{} — go + zen, from {}{}{}\n",
        ink.bold,
        ink.reset,
        ink.dim,
        shorten(db_path),
        ink.reset,
    ));
    // cmduse prints `Success N%` from its account API; opencode's own store
    // records no per-request success/error signal, so there is no rate to read
    // here — omitted rather than synthesised (source-forced).
    let end = report
        .period_end_ms
        .map(|ms| format!(" · ends {}", date_of(ms / 86_400_000)))
        .unwrap_or_default();
    out.push_str(&format!(
        "period: {}{end} · {} requests · {} · {} in / {} out tokens\n",
        report.period_label,
        c(compact(report.month.requests)),
        c(money(report.month.cost)),
        c(compact(report.month.input)),
        c(compact(report.month.output)),
    ));

    // The three window rows. When the account answered, they are its own meters
    // — the only view that agrees with opencode.ai/console, and the reason this
    // endpoint is read at all: the store cannot reproduce the server's window
    // anchors or its price basis (see `ocuse::api`).
    match &report.account {
        Some(account) => {
            out.push_str(&format!(
                "\n{}GO{} {}\n",
                ink.bold,
                ink.reset,
                ink.dim_on(
                    "(account meters — what opencode.ai/console reports; the $ is this store's spend priced on the documented peak/off-peak schedule)"
                        .into()
                ),
            ));
            // Every field that is true stays on the row: this store's money, the
            // ceiling the server's own share implies, the share labelled beside
            // it, its reset instant, and the elapsed share measured against the
            // server's clock. No account-wide pool is invented here — summing the
            // per-model limits into one ceiling is where the old `$215` came from.
            let monthly_dur = report
                .period_end_ms
                .map(|end| ((end - report.since_ms) / 1000).max(0) as u64);
            let rows = [
                (
                    "5-hour",
                    &account.rolling,
                    &report.five_hour,
                    Some(crate::ocuse::window::FIVE_HOUR_SECS as u64),
                ),
                (
                    "Weekly",
                    &account.weekly,
                    &report.weekly,
                    Some(crate::ocuse::window::WEEKLY_SECS as u64),
                ),
                ("Monthly", &account.monthly, &report.month, monthly_dur),
            ];
            for (label, meter, used, dur_secs) in rows {
                out.push_str(&window_line(
                    &ink,
                    &RowSpec {
                        label,
                        used,
                        reset: meter_reset(meter, dur_secs),
                        share_pct: Some(meter.percent),
                        status: Some(meter.status.as_str()),
                        // The monthly window is the budget; the two throttles
                        // above it would read a pro-rata figure as a target.
                        pro_rata: label == "Monthly",
                    },
                    report.now_ms,
                ));
            }
        }
        // No Go key, no network, or a key without the subscription: the store's
        // own spend, which says so. Limits are per model, so the rows carry
        // no pool to divide by -- spend alone, with the Monthly row's real
        // reset and elapsed share. They can disagree with the account.
        None if report.month.requests > 0 => {
            // Only the monthly period has a boundary of its own (`period_end_ms`).
            // The rolling 5h/weekly windows are cut at `now - window`, so they get
            // no reset, no elapsed share and no pace — the fabricated `now + window`
            // countdown that used to sit here moved on every frame.
            let monthly_dur = report
                .period_end_ms
                .map(|end| ((end - report.since_ms) / 1000).max(0) as u64);
            out.push_str(&format!(
                "\n{}GO{} {}\n",
                ink.bold,
                ink.reset,
                ink.dim_on(
                    "(estimated locally: limits are per model, so no pool: spend alone)".into()
                ),
            ));
            // Why the console's own numbers are missing, when there is a reason:
            // "estimated locally" alone cannot tell a missing key from an expired
            // one, and only the second is something a person can act on.
            if let Some(why) = &report.account_error {
                out.push_str(&format!("{}   usage API: {why}{}\n", ink.dim, ink.reset));
            }
            out.push_str(&window_line(
                &ink,
                &RowSpec {
                    label: "5-hour",
                    used: &report.five_hour,
                    reset: None,
                    share_pct: None,
                    status: None,
                    pro_rata: false,
                },
                report.now_ms,
            ));
            out.push_str(&window_line(
                &ink,
                &RowSpec {
                    label: "Weekly",
                    used: &report.weekly,
                    reset: None,
                    share_pct: None,
                    status: None,
                    pro_rata: false,
                },
                report.now_ms,
            ));
            out.push_str(&window_line(
                &ink,
                &RowSpec {
                    label: "Monthly",
                    used: &report.month,
                    reset: report.period_end_ms.zip(monthly_dur),
                    share_pct: None,
                    status: None,
                    // No account share, so no ceiling to pro-rate: this row keeps
                    // its real reset and elapsed share and nothing invented.
                    pro_rata: false,
                },
                report.now_ms,
            ));
        }
        None => {}
    }

    out.push_str(&format!(
        "\n{}MODEL                            LIMIT      SPENT     USE       5H       WK     REQ{}\n",
        ink.bold, ink.reset
    ));
    let total_cost = report.month.cost;
    for model in report.models.iter().take(rows) {
        out.push_str(&model_row(&ink, model, total_cost));
    }
    if report.models.len() > rows {
        out.push_str(&format!(
            "{}\n",
            ink.dim_on(format!("… {} more", report.models.len() - rows))
        ));
    }
    out.push_str(&format!(
        "\n{}\n",
        ink.dim_on(
            "ZEN is pay-as-you-go: the same rows carry its spend, but the docs give no limit."
                .into()
        )
    ));
    // The GO block above is the account's own metering. These two columns are
    // per model, so say whose they are: with an account answer they are cut at
    // the server's own window bounds (the same block and Monday-anchored week its
    // percentages describe), and only without one do they fall back to this
    // machine's rolling cuts.
    if report.account.is_some() {
        out.push_str(&format!(
            "{}\n",
            ink.dim_on(
                "5H/WK columns: this model's own spend inside the account's windows (the same cuts its percentages use)."
                    .into()
            )
        ));
    } else {
        out.push_str(&format!(
            "{}\n",
            ink.dim_on(
                "5H/WK columns: this model's own spend over the last 5h / 7 days (local, not the account's windows)."
                    .into()
            )
        ));
    }
    out
}

/// One watch frame: the dashboard, then a burst sparkline when the 5-hour spend
/// has moved since the previous refresh. No trailing newline — the caller
/// appends its own status line and `redraw_frame` (cmduse's) parks the cursor
/// there, which is what lets the countdown rewrite a single line per second.
pub fn watch_frame(
    report: &Report,
    db_path: &str,
    rows: usize,
    colour: bool,
    history: &[f64],
    interval_secs: u64,
    bar_width: usize,
) -> String {
    let ink = Ink::new(colour);
    let mut out = render_text(report, db_path, rows, colour, bar_width);
    if history.len() >= 2 && history.iter().any(|v| *v > 0.0) {
        out.push_str(&format!(
            "{}spend bursts ({}s samples){} {}\n",
            ink.dim,
            interval_secs,
            ink.reset,
            crate::render::sparkline(history),
        ));
    }
    out.trim_end_matches('\n').to_string()
}

/// Minimal one-line dashboard for terminals too small for the full frame:
/// period spend, rolling windows, and the burst sparkline inlined when active.
/// No trailing newline — the caller appends its own status line, exactly like
/// `watch_frame`.
pub fn compact_line(report: &Report, history: &[f64], colour: bool) -> String {
    let ink = Ink::new(colour);
    let spark = if history.len() >= 2 && history.iter().any(|v| *v > 0.0) {
        format!(
            " {}{}{}",
            ink.dim,
            crate::render::sparkline(history),
            ink.reset
        )
    } else {
        String::new()
    };
    // The 5-hour figure is the one a narrow terminal shows, and the store's
    // rolling 5h is not the server's block: prefer the account's own share
    // whenever the endpoint answered (see `ocuse::api`). The month spend stays
    // money — it is a budget, not a throttle.
    let window_share = match &report.account {
        Some(account) => format!(
            " · 5h {} · wk {}",
            ink.cyan_on(pct(account.rolling.percent, 100.0)),
            ink.cyan_on(pct(account.weekly.percent, 100.0)),
        ),
        None => format!(" · 5h {}", ink.cyan_on(money(report.five_hour.cost))),
    };
    format!(
        "{}oc{} {} month{window_share}{spark}",
        ink.bold,
        ink.reset,
        ink.cyan_on(money(report.month.cost)),
    )
}

/// ocuse's statusline: cmduse's `{key}` template engine (`report_render::
/// render_template`) resolved against this report's own placeholders, so both
/// binaries are driven by `statusline_template` in their config.
///
/// Placeholders (case-insensitive):
///   {plan} {period}                plan id / period label
///   {month} {month_pct} {month_bar}
///   {five_hour} {five_hour_pct} {five_hour_bar}   (aliases {5h} {5h_pct} {5h_bar})
///   {weekly} {weekly_pct} {weekly_bar}            (aliases {wk} {wk_pct} {wk_bar})
///   {models}                       top model by period spend
///   | or newline                    literal separators
/// Unknown placeholders are dropped. Percentages are one decimal; money reuses
/// `cmduse_core::money`; bars reuse `report_render::bar` (ascii/colour aware).
pub fn statusline_template(
    report: &Report,
    plan_id: &str,
    tpl: &str,
    colours: bool,
    ascii: bool,
    bar_width: usize,
) -> String {
    let ink = Ink::new(colours);
    let cash = |v: f64| ink.cyan_on(money(v));
    // The account's own share outranks the local one wherever both exist: it is
    // what opencode.ai/console shows. Money tokens stay local either way — the
    // endpoint publishes shares and instants, not dollars. Without an account
    // there is no pool to divide by (Go grants limits per model), so the share
    // placeholders degrade to the money-less dash instead of a ratio against a
    // summed ceiling that reads as a budget the console does not have.
    let account = report.account.as_ref();
    let share_of = |meter: Option<&crate::ocuse::api::Meter>| match meter {
        Some(meter) => pct(meter.percent, 100.0),
        None => "—".into(),
    };
    let share_bar = |meter: Option<&crate::ocuse::api::Meter>| match meter {
        Some(meter) => crate::report_render::bar(meter.percent, bar_width, ascii, colours),
        None => String::new(),
    };
    let top_model = || {
        report
            .models
            .first()
            .map(|m| m.id.clone())
            .unwrap_or_else(|| "—".into())
    };
    crate::report_render::render_template(tpl, |key| match key {
        "plan" => plan_id.to_string(),
        "period" => report.period_label.clone(),
        "month" => cash(report.month.cost),
        "month_pct" => share_of(account.map(|a| &a.monthly)),
        "month_bar" => share_bar(account.map(|a| &a.monthly)),
        "five_hour" | "5h" => cash(report.five_hour.cost),
        "five_hour_pct" | "5h_pct" => share_of(account.map(|a| &a.rolling)),
        "five_hour_bar" | "5h_bar" => share_bar(account.map(|a| &a.rolling)),
        "weekly" | "wk" => cash(report.weekly.cost),
        "weekly_pct" | "wk_pct" => share_of(account.map(|a| &a.weekly)),
        "weekly_bar" | "wk_bar" => share_bar(account.map(|a| &a.weekly)),
        "models" => top_model(),
        _ => String::new(),
    })
}

/// `ocuse statusline --json`: the same numbers the template resolves, in one
/// object — plan and period label, period/month spend, the two rolling windows,
/// and the top model. The `*Cap` keys are retired (always null): Go grants
/// limits per model, so no account-wide pool exists, and the summed ceiling
/// they carried read as a budget the console does not have.
pub fn statusline_json(report: &Report, plan_id: &str) -> String {
    serde_json::json!({
        "plan": plan_id,
        "period": report.period_label,
        "monthSpent": report.month.cost,
        "monthCap": serde_json::Value::Null,
        "fiveHourSpent": report.five_hour.cost,
        "fiveHourCap": serde_json::Value::Null,
        "weeklySpent": report.weekly.cost,
        "weeklyCap": serde_json::Value::Null,
        "model": report.models.first().map(|m| m.id.clone()),
    })
    .to_string()
}

/// Machine-readable projection: totals plus the per-model breakdown.
pub fn render_json(report: &Report) -> String {
    let totals = |t: &Totals| serde_json::json!({ "cost": t.cost, "requests": t.requests, "tokens": t.tokens() });
    let model = |m: &ModelUsage| {
        serde_json::json!({
            "id": m.id,
            "provider": m.provider,
            "limit": m.limit,
            "month": totals(&m.month),
            "fiveHour": totals(&m.five_hour),
            "weekly": totals(&m.weekly),
        })
    };
    // The account's own meters, when the Go usage endpoint answered. Consumers
    // (the sidebar's Go block among them) should prefer these over the local
    // `totals`, which cannot reproduce the server's anchors or price basis.
    let meter = |m: &crate::ocuse::api::Meter| {
        serde_json::json!({
            "status": m.status,
            "percent": m.percent,
            "resetsAt": m.reset_ms(),
        })
    };
    serde_json::to_string_pretty(&serde_json::json!({
        "source": "opencode.db",
        "generatedAt": report.now_ms,
        "periodStart": report.since_ms,
        // Period bounds in epoch ms, the same units as cmduse's `-1 --json`
        // (`periodStartAt`/`periodEndAt`) — `periodStart` stays for the plugin's
        // existing read. `periodEndAt` is null when the period has no boundary
        // (`--window all`).
        "periodStartAt": report.since_ms,
        "periodEndAt": report.period_end_ms,
        "periodInferred": report.month_inferred,
        "totals": {
            "month": totals(&report.month),
            "fiveHour": totals(&report.five_hour),
            "weekly": totals(&report.weekly),
        },
        // `null` when no Go key, no network, or a key without the subscription:
        // the caller then has only `totals`, which is the local estimate.
        "account": report.account.as_ref().map(|a| serde_json::json!({
            "rolling": meter(&a.rolling),
            "weekly": meter(&a.weekly),
            "monthly": meter(&a.monthly),
        })),
        // Why `account` is null, when that is worth saying — `HTTP 401
        // api_key_expired`, `no Go key`, a transport fault. `null` when the
        // endpoint answered, and for `--no-api`. Consumers otherwise show the
        // local estimate without being able to tell the three apart.
        "accountError": report.account_error,
        "models": report.models.iter().map(model).collect::<Vec<_>>(),
    }))
    .expect("json")
}

fn shorten(path: &str) -> String {
    match std::env::var("HOME") {
        Ok(home) if !home.is_empty() => path.replacen(&home, "~", 1),
        _ => path.to_string(),
    }
}

// ---- catalogues and history tables (shared with the MCP server) -------------

/// The catalogue: what each product costs and (for Go) what each plan allows.
///
/// Both Go plans are listed because the docs define two — Go and Go Plus — that
/// share one token price list but grant each model a different monthly limit.
pub fn plans_text(colour: bool) -> String {
    let ink = Ink::new(colour);
    let catalog = crate::ocuse::zen::catalog();
    let mut out = format!(
        "{}OpenCode plans{} {}\n",
        ink.bold,
        ink.reset,
        ink.dim_on(format!("(docs, extracted {})", catalog.extracted_at)),
    );
    out.push_str(&format!(
        "{}windows (both plans): 5h {} · weekly {} · monthly {}{}\n",
        ink.dim,
        ink.cyan_on(format!("{:.1}%", catalog.go.window_share.five_hour * 100.0)),
        ink.cyan_on(format!("{:.1}%", catalog.go.window_share.weekly * 100.0)),
        ink.cyan_on(format!("{:.1}%", catalog.go.window_share.monthly * 100.0)),
        ink.reset,
    ));
    for plan in catalog.go.plans.values() {
        out.push_str(&format!(
            "\n{}{}{} — {}/month\n",
            ink.bold,
            plan.label,
            ink.reset,
            ink.cyan_on(format!("${:.2}", plan.price_usd)),
        ));
        out.push_str(&format!(
            "{}MODEL                            LIMIT    IN     OUT    CACHE{}\n",
            ink.bold, ink.reset
        ));
        for model in &catalog.go.models {
            let rate = model.variants.first();
            let limit = plan
                .allowance_by_model
                .get(&model.id)
                .map(|limit| cmduse_core::money(*limit))
                .unwrap_or_else(|| "—".into());
            out.push_str(&format!(
                "{:<28} {} {} {} {}\n",
                model.id,
                ink.cyan_on(format!("{limit:>7}")),
                ink.cyan_on(format!(
                    "{:>6}",
                    rate.map(|r| format!("${}", r.input)).unwrap_or_default()
                )),
                ink.cyan_on(format!(
                    "{:>6}",
                    rate.map(|r| format!("${}", r.output)).unwrap_or_default()
                )),
                ink.cyan_on(format!(
                    "{:>8}",
                    rate.map(|r| format!("${}", r.cache_read))
                        .unwrap_or_default()
                )),
            ));
        }
    }
    out.push_str(&format!(
        "\n{}\n",
        ink.dim_on(format!(
            "ZEN — pay-as-you-go, {} models priced per 1M tokens",
            catalog.zen.models.len()
        ))
    ));
    out
}

/// The Go/Zen catalogue as one JSON object — the machine twin of `plans_text`:
/// both plans (label, price, per-model monthly allowances), the shared window
/// shares, and the Go and Zen rate tables.
pub fn plans_json() -> String {
    let catalog = crate::ocuse::zen::catalog();
    let plans: Vec<serde_json::Value> = catalog
        .go
        .plans
        .iter()
        .map(|(id, plan)| {
            serde_json::json!({
                "id": id,
                "label": plan.label,
                "priceUsd": plan.price_usd,
                "allowanceByModel": &plan.allowance_by_model,
            })
        })
        .collect();
    serde_json::json!({
        "extractedAt": catalog.extracted_at,
        "windows": {
            "fiveHour": catalog.go.window_share.five_hour,
            "weekly": catalog.go.window_share.weekly,
            "monthly": catalog.go.window_share.monthly,
        },
        "plans": plans,
        "models": catalog.go.models.iter().map(rate_json).collect::<Vec<_>>(),
        "zen": catalog.zen.models.iter().map(rate_json).collect::<Vec<_>>(),
    })
    .to_string()
}

/// One catalogue row's shared `$`/1M rates, taken from its base (first) variant.
fn rate_json(model: &zen::Model) -> serde_json::Value {
    let rate = model.variants.first();
    serde_json::json!({
        "id": model.id,
        "name": model.name,
        "input": rate.map(|r| r.input),
        "output": rate.map(|r| r.output),
        "cacheRead": rate.map(|r| r.cache_read),
        "cacheWrite": rate.map(|r| r.cache_write),
    })
}

/// One `ocuse models` row: a catalogued Go model, its rates, and the selected
/// plan's monthly limit (`None` = the plan does not grant it).
struct ModelRow {
    id: String,
    name: String,
    input: Option<f64>,
    output: Option<f64>,
    cache_read: Option<f64>,
    limit: Option<f64>,
}

/// The Go catalogue joined with the plan's allowances; `gated` keeps only the
/// models the plan grants (present in `allowanceByModel`).
fn model_rows(plan_id: &str, gated: bool) -> Vec<ModelRow> {
    let catalog = crate::ocuse::zen::catalog();
    let plan = catalog.plan(plan_id);
    let mut rows: Vec<ModelRow> = catalog
        .go
        .models
        .iter()
        .map(|m| {
            let rate = m.variants.first();
            ModelRow {
                id: m.id.clone(),
                name: m.name.clone(),
                input: rate.map(|r| r.input),
                output: rate.map(|r| r.output),
                cache_read: rate.map(|r| r.cache_read),
                limit: plan.and_then(|p| p.allowance_by_model.get(&m.id).copied()),
            }
        })
        .collect();
    if gated {
        rows.retain(|r| r.limit.is_some());
    }
    rows
}

/// `ocuse models`: the Go catalogue for one plan — name, id, `$`/1M in / out /
/// cache-read, and that plan's monthly limit. Without `gated`, every catalogued
/// model is listed and the `GRANTED` column marks which the plan allows.
pub fn models_text(plan_id: &str, gated: bool, colour: bool) -> String {
    let ink = Ink::new(colour);
    let catalog = crate::ocuse::zen::catalog();
    let label = catalog
        .plan(plan_id)
        .map(|p| p.label.clone())
        .unwrap_or_else(|| plan_id.to_string());
    let granted = catalog
        .plan(plan_id)
        .map(|p| p.allowance_by_model.len())
        .unwrap_or(0);
    let rows = model_rows(plan_id, gated);
    let mut out = format!(
        "{}{label} models{} {}\n",
        ink.bold,
        ink.reset,
        ink.dim_on(format!(
            "(plan {plan_id} · {granted}/{} granted)",
            catalog.go.models.len()
        )),
    );
    out.push_str(&format!(
        "{}{:<30} {:<28} {:>7} {:>7} {:>7} {:>8} {:>7}{}\n",
        ink.bold, "MODEL", "ID", "IN", "OUT", "CACHE", "LIMIT", "GRANTED", ink.reset
    ));
    let rate_cell = |v: Option<f64>| match v {
        Some(v) => ink.cyan_on(format!("{:>7}", format!("${v}"))),
        None => ink.dim_on(format!("{:>7}", "—")),
    };
    for r in &rows {
        let limit = match r.limit {
            Some(l) => ink.cyan_on(format!("{:>8}", cmduse_core::money(l))),
            None => ink.dim_on(format!("{:>8}", "—")),
        };
        let granted = if r.limit.is_some() { "yes" } else { "no" };
        out.push_str(&format!(
            "{:<30} {:<28} {} {} {} {} {:>7}\n",
            r.name,
            r.id,
            rate_cell(r.input),
            rate_cell(r.output),
            rate_cell(r.cache_read),
            limit,
            granted,
        ));
    }
    out
}

/// `ocuse models --json`: one JSON object per line (matching cmduse's
/// `models --json`), each model's id, name, `$`/1M rates, plan limit (null
/// when not granted) and the `granted` verdict.
pub fn models_json(plan_id: &str, gated: bool) -> String {
    let mut out = String::new();
    for r in model_rows(plan_id, gated) {
        out.push_str(
            &serde_json::json!({
                "id": r.id,
                "name": r.name,
                "input": r.input,
                "output": r.output,
                "cacheRead": r.cache_read,
                "limit": r.limit,
                "granted": r.limit.is_some(),
            })
            .to_string(),
        );
        out.push('\n');
    }
    out
}

pub fn model_text(report: &Report, id: &str, colour: bool) -> String {
    let ink = Ink::new(colour);
    let Some(model) = report.models.iter().find(|m| m.id == id) else {
        return format!("{id}: no usage in the period\n");
    };
    let limit = model
        .limit
        .map(cmduse_core::money)
        .unwrap_or_else(|| "—".into());
    let row =
        |label: &str, value: String| format!("  {}{value}\n", ink.dim_on(format!("{label:<10}")));
    let mut out = format!(
        "{} {}\n",
        ink.bold_on(model.id.clone()),
        ink.dim_on(format!("({})", model.provider)),
    );
    out.push_str(&row("limit", ink.cyan_on(limit)));
    out.push_str(&row(
        "month",
        ink.cyan_on(format!(
            "{} · {} requests",
            cmduse_core::money(model.month.cost),
            model.month.requests
        )),
    ));
    out.push_str(&row(
        "5-hour",
        ink.cyan_on(cmduse_core::money(model.five_hour.cost)),
    ));
    out.push_str(&row(
        "weekly",
        ink.cyan_on(cmduse_core::money(model.weekly.cost)),
    ));
    // The dashboard's share column needs the period total; here it is the same
    // fact spelled out. Absent when the period has no spend to divide by.
    if report.month.cost > 0.0 {
        out.push_str(&row(
            "share",
            ink.dim_on(format!(
                "{:.1}% of period spend",
                model.month.cost / report.month.cost * 100.0
            )),
        ));
    }
    out
}

/// Per-key JSON totals — the same field vocabulary cmduse's
/// `report_render::totals_json` uses. `cacheWrite` is deliberately absent:
/// ocuse's `window::Totals` carries no cache-write (the store's rows do, but
/// nothing aggregates them into a report), so no column is invented for it.
fn totals_json(
    cost: f64,
    requests: u64,
    input: u64,
    output: u64,
    cache_read: u64,
) -> serde_json::Value {
    serde_json::json!({
        "requests": requests,
        "tokensIn": input,
        "tokensOut": output,
        "cacheRead": cache_read,
        "costUsd": cost,
    })
}

/// One day/hour bucket's totals, kept apart per column so the CSV/JSON forms do
/// not have to re-derive them from a packed tuple.
#[derive(Default, Clone, Copy)]
struct Bucket {
    cost: f64,
    requests: u64,
    input: u64,
    output: u64,
    cache_read: u64,
}

impl Bucket {
    fn add(&mut self, row: &crate::ocuse::db::Row) {
        self.cost += row.cost_usd;
        self.requests += 1;
        self.input += row.input;
        self.output += row.output;
        self.cache_read += row.cache_read;
    }

    fn json(&self) -> serde_json::Value {
        totals_json(
            self.cost,
            self.requests,
            self.input,
            self.output,
            self.cache_read,
        )
    }
}

/// Per-model report — `ocuse model` on the whole period (or one id). The
/// machine formats project the report's models: `Json` mirrors cmduse's
/// `model --json` envelope (`{source, sinceMs, models:{id: totals}}`, with the
/// Go limit added), `Csv` is one row per model
/// (`model,requests,tokens_in,tokens_out,cache_read,cost_usd`). The `Table` form
/// is the caller's — the dashboard (no id) or the single-model detail (with an
/// id) — which needs the db path and row cap, so it is rendered there.
pub fn model_report(report: &Report, id: Option<&str>, fmt: Fmt) -> String {
    let models: Vec<&ModelUsage> = report
        .models
        .iter()
        .filter(|m| id.is_none_or(|want| m.id == want))
        .collect();
    match fmt {
        Fmt::Json => {
            let map: serde_json::Map<String, serde_json::Value> = models
                .iter()
                .map(|m| {
                    let mut body = totals_json(
                        m.month.cost,
                        m.month.requests,
                        m.month.input,
                        m.month.output,
                        m.month.cache_read,
                    );
                    body["limit"] = serde_json::json!(m.limit);
                    (m.id.clone(), body)
                })
                .collect();
            serde_json::json!({
                "scope": "local",
                "source": "opencode",
                "sinceMs": report.since_ms,
                "models": map,
            })
            .to_string()
        }
        Fmt::Csv => {
            let mut out = String::from("model,requests,tokens_in,tokens_out,cache_read,cost_usd\n");
            for m in models {
                out.push_str(&format!(
                    "{},{},{},{},{},{:.2}\n",
                    crate::report_render::csv_field(&m.id),
                    m.month.requests,
                    m.month.input,
                    m.month.output,
                    m.month.cache_read,
                    m.month.cost,
                ));
            }
            out
        }
        Fmt::Table => String::new(), // the caller renders the table form
    }
}

/// Spend per bucket (day or hour), oldest first — `cmduse daily`/`hourly`.
/// `lookback_ms` is the read window and `size_ms` the bucket width (which also
/// names the first CSV/JSON column: `day` for a ≥24h bucket, else `hour`). The
/// `Csv` columns are that key plus the store's numeric fields
/// (`…,requests,tokens_in,tokens_out,cache_read,cost_usd`; no cache-write), the
/// `Json` form `{scope,source,total,days|hours}`, and `Table` is the original
/// framing but for `Ink`'s colour. `Json`/`Csv` are never coloured.
pub fn bucket_text(
    rows: &[crate::ocuse::db::Row],
    now_ms: i64,
    lookback_ms: i64,
    size_ms: i64,
    tz_secs: i64,
    colour: bool,
    fmt: Fmt,
) -> String {
    // Buckets are cut in the display timezone: shift, bucket, then label.
    let shift = tz_secs * 1000;
    let mut buckets: std::collections::BTreeMap<i64, Bucket> = Default::default();
    for row in rows {
        let bucket = (row.at_ms + shift).div_euclid(size_ms);
        buckets.entry(bucket).or_default().add(row);
    }
    let start = (now_ms + shift - lookback_ms).div_euclid(size_ms);
    let daily = size_ms >= 86_400_000;
    let label = if daily { "day" } else { "hour" };
    let stamp = |bucket: i64| {
        if daily {
            date_of(bucket)
        } else {
            format!(
                "{} {:02}h",
                date_of(bucket.div_euclid(24)),
                bucket.rem_euclid(24)
            )
        }
    };
    let window: Vec<(i64, Bucket)> = buckets
        .range(start..)
        .map(|(bucket, b)| (*bucket, *b))
        .collect();

    match fmt {
        Fmt::Json => {
            let mut keyed = serde_json::Map::new();
            let mut total = Bucket::default();
            for (bucket, b) in &window {
                keyed.insert(stamp(*bucket), b.json());
                total.add_bucket(b);
            }
            let key = if daily { "days" } else { "hours" };
            serde_json::json!({
                "scope": "local",
                "source": "opencode",
                "total": total.json(),
                key: keyed,
            })
            .to_string()
        }
        Fmt::Csv => {
            let head = if daily { "day" } else { "hour" };
            let mut out = format!("{head},requests,tokens_in,tokens_out,cache_read,cost_usd\n");
            let mut total = Bucket::default();
            for (bucket, b) in &window {
                out.push_str(&format!(
                    "{},{},{},{},{},{:.2}\n",
                    crate::report_render::csv_field(&stamp(*bucket)),
                    b.requests,
                    b.input,
                    b.output,
                    b.cache_read,
                    b.cost,
                ));
                total.add_bucket(b);
            }
            out.push_str(&format!(
                "total,{},{},{},{},{:.2}\n",
                total.requests, total.input, total.output, total.cache_read, total.cost,
            ));
            out
        }
        Fmt::Table => {
            let ink = Ink::new(colour);
            let mut out = format!(
                "{}{label:<12} spend     requests   tokens{}\n",
                ink.bold, ink.reset
            );
            for (bucket, b) in &window {
                out.push_str(&format!(
                    "{:<12} {} {} {}\n",
                    stamp(*bucket),
                    ink.cyan_on(format!("{:>9}", cmduse_core::money(b.cost))),
                    ink.cyan_on(format!("{:>12}", cmduse_core::compact(b.requests))),
                    ink.cyan_on(format!(
                        "{:>9}",
                        cmduse_core::compact(b.input + b.output + b.cache_read)
                    )),
                ));
            }
            if out.lines().count() == 1 {
                out.push_str(&format!(
                    "{}\n",
                    ink.dim_on("(no OpenCode usage in the window)".into())
                ));
            }
            out
        }
    }
}

/// One session's accumulating totals: `(cost, requests, tokens_in, tokens_out,
/// cache_read, last_ms, distinct models)`.
type SessionTotals<'a> = (
    f64,
    u64,
    u64,
    u64,
    u64,
    i64,
    std::collections::BTreeSet<&'a str>,
);

/// Spend per session, newest first. The `Csv` form is one row per session
/// (`session,requests,tokens_in,tokens_out,cache_read,cost_usd`), `Json` a
/// `{scope,source,sessions}` object whose entries add the last-used instant and
/// the distinct-model count; `Table` keeps its own (last, models) columns.
pub fn session_text(
    rows: &[crate::ocuse::db::Row],
    limit: usize,
    colour: bool,
    fmt: Fmt,
) -> String {
    let mut by_session: std::collections::BTreeMap<&str, SessionTotals> = Default::default();
    for row in rows {
        let entry = by_session
            .entry(row.session.as_str())
            .or_insert_with(|| (0.0, 0, 0, 0, 0, 0, Default::default()));
        entry.0 += row.cost_usd;
        entry.1 += 1;
        entry.2 += row.input;
        entry.3 += row.output;
        entry.4 += row.cache_read;
        entry.5 = entry.5.max(row.at_ms);
        entry.6.insert(row.model.as_str());
    }
    let mut sessions: Vec<_> = by_session.into_iter().collect();
    sessions.sort_by_key(|(_, (_, _, _, _, _, last, _))| std::cmp::Reverse(*last));

    match fmt {
        Fmt::Json => {
            let mut keyed = serde_json::Map::new();
            for (id, (cost, requests, input, output, cache_read, last, models)) in &sessions {
                let mut body = totals_json(*cost, *requests, *input, *output, *cache_read);
                body["lastMs"] = serde_json::json!(*last);
                body["models"] = serde_json::json!(models.len());
                keyed.insert((*id).to_string(), body);
            }
            serde_json::json!({
                "scope": "local",
                "source": "opencode",
                "sessions": keyed,
            })
            .to_string()
        }
        Fmt::Csv => {
            let mut out =
                String::from("session,requests,tokens_in,tokens_out,cache_read,cost_usd\n");
            for (id, (cost, requests, input, output, cache_read, _, _)) in &sessions {
                out.push_str(&format!(
                    "{},{},{},{},{},{:.2}\n",
                    crate::report_render::csv_field(id),
                    requests,
                    input,
                    output,
                    cache_read,
                    cost,
                ));
            }
            out
        }
        Fmt::Table => {
            let ink = Ink::new(colour);
            let mut out = format!(
                "{}session                          last        models   spend     req{}\n",
                ink.bold, ink.reset
            );
            for (id, (cost, requests, _, _, _, last, models)) in sessions.iter().take(limit) {
                let short = id.rsplit('_').next().unwrap_or(*id);
                out.push_str(&format!(
                    "{:<32} {:<11} {:>6} {} {:>6}\n",
                    short,
                    ink.dim_on(format!("{:<11}", date_of(last.div_euclid(86_400_000)))),
                    models.len(),
                    ink.cyan_on(format!("{:>9}", cmduse_core::money(*cost))),
                    requests,
                ));
            }
            if sessions.len() > limit {
                out.push_str(&format!(
                    "{}\n",
                    ink.dim_on(format!("… {} more", sessions.len() - limit))
                ));
            }
            if out.lines().count() == 1 {
                out.push_str(&format!(
                    "{}\n",
                    ink.dim_on("(no sessions in the window)".into())
                ));
            }
            out
        }
    }
}

impl Bucket {
    /// Fold another bucket's totals in (for the report's `total` row/entry).
    fn add_bucket(&mut self, other: &Bucket) {
        self.cost += other.cost;
        self.requests += other.requests;
        self.input += other.input;
        self.output += other.output;
        self.cache_read += other.cache_read;
    }
}

/// `YYYY-MM-DD` for a Unix day number (civil-from-days, same helper family as
/// the window module's).
pub fn date_of(day: i64) -> String {
    let z = day + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };
    format!("{year:04}-{m:02}-{d:02}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ocuse::db::Row;

    fn report() -> Report {
        let now = 1_800_000_000_000;
        let rows = vec![Row {
            at_ms: now - 60_000,
            provider: "opencode-go".into(),
            model: "glm-5.3-flash".into(),
            cost_usd: 30.0,
            ..Default::default()
        }];
        crate::ocuse::window::build(&rows, &zen::catalog(), zen::DEFAULT_PLAN, now, None, None)
    }

    #[test]
    fn text_shows_the_model_against_its_limit() {
        let text = render_text(&report(), "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        assert!(text.contains("glm-5.3-flash"), "{text}");
        assert!(text.contains("$60"), "the model's monthly limit: {text}");
        assert!(
            text.contains("50.0%"),
            "the model table keeps its own USE: {text}"
        );
    }

    fn meter(status: &str, percent: f64, resets_at: &str) -> crate::ocuse::api::Meter {
        crate::ocuse::api::Meter {
            status: status.into(),
            percent,
            resets_at: Some(resets_at.into()),
        }
    }

    /// The same report with the account's own meters attached — the shape a Go
    /// key produces. Reset instants sit after `now` (2027-01-15T08:00:00Z), so
    /// the countdowns render rather than clamp to zero. The period bounds mirror
    /// what `cli.rs` derives from the monthly reset (`prev_month`), so the
    /// Monthly row carries the same elapsed share and pro-rata figure a live
    /// dashboard shows.
    fn report_with_account() -> Report {
        let mut report = report();
        report.account = Some(crate::ocuse::api::Usage {
            rolling: meter("ok", 5.0, "2027-01-15T12:31:00.000Z"),
            weekly: meter("ok", 59.0, "2027-01-18T00:00:00.000Z"),
            monthly: meter("ok", 29.0, "2027-02-15T08:00:00.000Z"),
        });
        report.period_end_ms = Some(1_802_678_400_000); // 2027-02-15T08:00:00Z
        report.since_ms = crate::ocuse::window::prev_month(1_802_678_400_000);
        report
    }

    #[test]
    fn the_window_rows_come_from_the_account_when_it_answered() {
        let text = render_text(
            &report_with_account(),
            "/tmp/opencode.db",
            10,
            false,
            DEFAULT_BAR_WIDTH,
        );
        // The console's three shares, and its reset instants. Whole percents, as
        // the endpoint publishes them: `"percent":53`, never `53.0`.
        assert!(text.contains("· 5% of limit"), "{text}");
        assert!(text.contains("· 59% of limit"), "{text}");
        assert!(text.contains("· 29% of limit"), "{text}");
        assert!(text.contains("account meters"), "{text}");
        assert!(
            text.contains("resets 4h 31m"),
            "the 5h block's own end: {text}"
        );
        // Every field that is true stays on the row: this store's own money and
        // the server's share labelled beside it. No denominator is printed — it
        // would have to be `spend / share`, which contradicted the documented
        // allowance ($40 next to an $80 limit) because the console meters at
        // roughly twice the cost this store records.
        assert!(text.contains(".00 · 5% of limit"), "{text}");
        assert!(text.contains(".00 · 29% of limit"), "{text}");
        assert!(text.contains("of limit"), "{text}");
        // The monthly window measures against the period bounds, like cmduse's:
        // an elapsed share, the server's reset, and the even-burn figure — which
        // only the budget window gets, because the two throttles above it would
        // read it as a spend target.
        assert!(text.contains("elapsed"), "{text}");
        assert_eq!(text.matches("by now").count(), 1, "{text}");
        // …and the per-model columns are named as the same cuts, not a second
        // measurement of a different window.
        assert!(text.contains("the same cuts its percentages use"), "{text}");
    }

    /// The denominator is the server's own percentage read backwards: whatever
    /// this store spent, divided by the share the console prints, is the ceiling
    /// that share is metering against. A share too small to imply one (the
    /// endpoint rounds to one decimal, and sends 0.0 for a window it meters on
    /// another basis) leaves the row with the share alone, never a division by
    /// it.
    #[test]
    fn the_pair_is_the_ceiling_the_share_implies() {
        // The $30 fixture spend at each of the fixture's shares.
        assert_eq!(implied_cap(30.0, 5.0), Some(600.0));
        assert_eq!(implied_cap(30.0, 59.0), Some(50.847457627118644));
        // Under the display's precision there is no ceiling to print.
        assert_eq!(implied_cap(20.45, 0.0), None);
        assert_eq!(implied_cap(20.45, 0.04), None);
        assert_eq!(implied_cap(20.45, 0.1), Some(20450.0));
        assert_eq!(implied_cap(0.0, 1.0), Some(0.0));
    }

    /// The colour frame prints the share once. It used to read
    /// `5% ━━━━━━ $30.00 · 5% of limit`: the gauge and the body each printed the
    /// same percentage, and the gauge's own `{:.1}` also turned the endpoint's
    /// whole `5` into `5.0`. The plain frame has no gauge, so it keeps the figure.
    #[test]
    fn the_gauge_carries_the_share_and_the_body_does_not_repeat_it() {
        let colour = render_text(
            &report_with_account(),
            "/tmp/opencode.db",
            10,
            true,
            DEFAULT_BAR_WIDTH,
        );
        let five = colour
            .lines()
            .find(|line| line.contains("5-hour"))
            .expect("a 5-hour row");
        assert!(!five.contains("of limit"), "no repeated share: {five}");
        assert!(
            five.contains("    5%"),
            "the endpoint's whole figure: {five}"
        );
        let plain = render_text(
            &report_with_account(),
            "/tmp/opencode.db",
            10,
            false,
            DEFAULT_BAR_WIDTH,
        );
        assert!(plain.contains("· 5% of limit"), "{plain}");
    }

    /// A pace line needs a cap the burn can actually reach before the reset.
    #[test]
    fn a_reachable_cap_gets_the_pace_line() {
        let mut report = report_with_account();
        if let Some(account) = &mut report.account {
            // 90% of the ceiling this store's $30 implies ($33.33), one hour into
            // a 5-hour window with four left: the burn reaches it well inside.
            account.rolling = meter("ok", 90.0, "2027-01-15T12:00:00.000Z");
        }
        let text = render_text(&report, "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        assert!(text.contains("on pace to hit cap in"), "{text}");
    }

    #[test]
    fn without_an_account_the_rows_say_they_are_local() {
        let text = render_text(&report(), "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        assert!(text.contains("estimated locally"), "{text}");
        assert!(text.contains("no pool"), "no aggregate ceiling: {text}");
        // Spend alone: no pair, no share, no countdown without a boundary.
        assert!(!text.contains("of limit"), "{text}");
        assert!(!text.contains("resets"), "{text}");
        assert!(!text.contains("elapsed"), "{text}");
        // Nothing claims to be the account's own view.
        assert!(!text.contains("account meters"), "{text}");
        assert!(
            !text.contains("the same cuts its percentages use"),
            "{text}"
        );
        // Without an answer the columns keep saying they are this machine's own
        // rolling cuts, since there is no server window to align them to.
        assert!(text.contains("local, not the account's windows"), "{text}");
    }

    #[test]
    fn an_over_limit_meter_says_so_before_its_countdown() {
        let mut report = report_with_account();
        if let Some(account) = &mut report.account {
            account.rolling = meter("rate_limited", 100.0, "2027-01-15T12:31:00.000Z");
        }
        let text = render_text(&report, "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        assert!(text.contains("LIMIT EXCEEDED"), "{text}");
    }

    #[test]
    fn json_carries_the_account_meters_and_null_without_them() {
        let parsed: serde_json::Value =
            serde_json::from_str(&render_json(&report_with_account())).unwrap();
        assert_eq!(parsed["account"]["rolling"]["percent"], 5.0);
        assert_eq!(parsed["account"]["weekly"]["percent"], 59.0);
        assert_eq!(parsed["account"]["monthly"]["status"], "ok");
        // `resetsAt` in epoch ms (the same units as `periodEndAt`), not the ISO
        // string the endpoint sent; `api::tests` pins the literal itself.
        let monthly = cmduse_core::dates::parse_iso_utc("2027-02-15T08:00:00.000Z").unwrap();
        assert_eq!(parsed["account"]["monthly"]["resetsAt"], monthly as i64);

        // No account: the key is present and null, so a consumer can tell the
        // difference between "no key" and "zero".
        let parsed: serde_json::Value = serde_json::from_str(&render_json(&report())).unwrap();
        assert_eq!(parsed["account"], serde_json::Value::Null);
    }

    #[test]
    fn statusline_prefers_the_accounts_share_over_the_local_estimate() {
        let tpl = "{five_hour_pct} {weekly_pct} {month_pct} {five_hour}";
        let account = statusline_template(
            &report_with_account(),
            "go",
            tpl,
            false,
            false,
            DEFAULT_BAR_WIDTH,
        );
        assert!(account.starts_with("5.0% 59.0% 29.0%"), "{account}");
        // Money stays local either way: the endpoint publishes shares, not dollars.
        assert!(account.contains("$30.00"), "{account}");

        // Without an account the same tokens resolve against the store, which is
        // what makes the fallback worth having.
        let local = statusline_template(&report(), "go", tpl, false, false, DEFAULT_BAR_WIDTH);
        assert!(!local.starts_with("5.0%"), "{local}");
    }

    #[test]
    fn json_and_statusline_carry_the_totals() {
        let json = render_json(&report());
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["totals"]["month"]["cost"], 30.0);
        assert_eq!(parsed["models"][0]["id"], "glm-5.3-flash");
        let line = statusline_template(&report(), "go", "{plan} {models}", false, false, 20);
        assert_eq!(line, "go glm-5.3-flash");
    }

    #[test]
    fn json_carries_the_period_bounds() {
        // The default/month report has an end resolved from its own start, and
        // `periodStartAt` is the alias of the existing `periodStart`.
        let mut r = report();
        r.period_end_ms = Some(crate::ocuse::window::next_month(r.since_ms));
        let parsed: serde_json::Value = serde_json::from_str(&render_json(&r)).unwrap();
        assert_eq!(parsed["periodStart"], r.since_ms);
        assert_eq!(parsed["periodStartAt"], r.since_ms);
        assert_eq!(parsed["periodEndAt"], r.period_end_ms.unwrap());

        // `--window all` resolves no end: the key is present and null, and the
        // old keys are unchanged.
        let mut all = report();
        all.period_end_ms = None;
        let parsed: serde_json::Value = serde_json::from_str(&render_json(&all)).unwrap();
        assert_eq!(parsed["periodEndAt"], serde_json::Value::Null);
        assert_eq!(parsed["periodStart"], all.since_ms);
        assert!(parsed.get("periodInferred").is_some());
    }

    /// Every renderer, both ways round: piped/non-tty output must stay free of
    /// SGR escapes, and every one of them must colour when colour is on. This is
    /// the guard for the bug where only `render_text` ever got a colour flag, so
    /// `daily` / `hourly` / `session` / `plans` / `model` / `statusline` printed
    /// plain regardless of the terminal.
    #[test]
    fn every_renderer_respects_the_colour_flag() {
        let mut report = report();
        // Exercise the monthly row's real period (reset, elapsed, by-now) both
        // ways round, so a colour leak into the new plain fields fails here too.
        report.period_end_ms = Some(crate::ocuse::window::next_month(report.since_ms));
        let rows = vec![Row {
            at_ms: report.now_ms - 60_000,
            session: "ses_fixture".into(),
            provider: "opencode-go".into(),
            model: "glm-5.3-flash".into(),
            cost_usd: 30.0,
            ..Default::default()
        }];
        let now = report.now_ms;

        let cases: Vec<(&str, String, String)> = vec![
            (
                "render_text",
                render_text(&report, "/tmp/oc.db", 10, false, DEFAULT_BAR_WIDTH),
                render_text(&report, "/tmp/oc.db", 10, true, DEFAULT_BAR_WIDTH),
            ),
            (
                "statusline_template",
                statusline_template(
                    &report,
                    "go",
                    "{period} {month} {month_pct}",
                    false,
                    false,
                    20,
                ),
                statusline_template(
                    &report,
                    "go",
                    "{period} {month} {month_pct}",
                    true,
                    false,
                    20,
                ),
            ),
            (
                "compact_line",
                compact_line(&report, &[], false),
                compact_line(&report, &[], true),
            ),
            ("plans_text", plans_text(false), plans_text(true)),
            (
                "model_text",
                model_text(&report, "glm-5.3-flash", false),
                model_text(&report, "glm-5.3-flash", true),
            ),
            (
                "bucket_text/day",
                bucket_text(&rows, now, 7 * 86_400_000, 86_400_000, 0, false, Fmt::Table),
                bucket_text(&rows, now, 7 * 86_400_000, 86_400_000, 0, true, Fmt::Table),
            ),
            (
                "bucket_text/hour",
                bucket_text(&rows, now, 3_600_000, 3_600_000, 0, false, Fmt::Table),
                bucket_text(&rows, now, 3_600_000, 3_600_000, 0, true, Fmt::Table),
            ),
            (
                "session_text",
                session_text(&rows, 20, false, Fmt::Table),
                session_text(&rows, 20, true, Fmt::Table),
            ),
            (
                "models_text",
                models_text("go", false, false),
                models_text("go", false, true),
            ),
        ];
        for (name, plain, coloured) in cases {
            assert!(
                !plain.contains('\x1b'),
                "{name} leaked escapes when off: {plain}"
            );
            assert!(
                coloured.contains('\x1b'),
                "{name} rendered nothing coloured when on: {coloured}"
            );
        }

        // Machine formats must ignore the colour flag entirely: no escapes
        // whether it is off or on.
        let flagged: Vec<(&str, String, String)> = vec![
            (
                "bucket_text/day csv",
                bucket_text(&rows, now, 7 * 86_400_000, 86_400_000, 0, false, Fmt::Csv),
                bucket_text(&rows, now, 7 * 86_400_000, 86_400_000, 0, true, Fmt::Csv),
            ),
            (
                "bucket_text/hour json",
                bucket_text(&rows, now, 3_600_000, 3_600_000, 0, false, Fmt::Json),
                bucket_text(&rows, now, 3_600_000, 3_600_000, 0, true, Fmt::Json),
            ),
            (
                "session_text csv",
                session_text(&rows, 20, false, Fmt::Csv),
                session_text(&rows, 20, true, Fmt::Csv),
            ),
            (
                "session_text json",
                session_text(&rows, 20, false, Fmt::Json),
                session_text(&rows, 20, true, Fmt::Json),
            ),
        ];
        for (name, off, on) in flagged {
            assert!(
                !off.contains('\x1b'),
                "{name} leaked escapes with colour off: {off}"
            );
            assert!(
                !on.contains('\x1b'),
                "{name} must stay uncoloured with colour on: {on}"
            );
        }
        for (name, out) in [
            ("model_report json", model_report(&report, None, Fmt::Json)),
            ("model_report csv", model_report(&report, None, Fmt::Csv)),
            ("plans_json", plans_json()),
            ("statusline_json", statusline_json(&report, "go")),
            ("models_json", models_json("go", false)),
        ] {
            assert!(
                !out.contains('\x1b'),
                "{name} must never be coloured: {out}"
            );
        }
    }

    #[test]
    fn session_rows_cap_the_table_and_never_the_machine_formats() {
        // `--rows` is a display cap (the CLI passes it straight in). JSON/CSV
        // must keep every session: a consumer that reads a short report as the
        // whole window is worse than a long table.
        let now = 1_800_000_000_000;
        let rows: Vec<Row> = (0..25)
            .map(|i| Row {
                at_ms: now - i as i64 * 60_000,
                provider: "opencode-go".into(),
                model: "glm-5.3-flash".into(),
                session: format!("ses_{i:02}"),
                cost_usd: 0.1,
                ..Default::default()
            })
            .collect();
        let table = session_text(&rows, 2, false, Fmt::Table);
        assert!(table.contains("… 23 more"), "{table}");
        assert_eq!(
            table.lines().count(),
            4,
            "header + 2 rows + the tail: {table}"
        );
        let json: serde_json::Value =
            serde_json::from_str(&session_text(&rows, 2, false, Fmt::Json)).unwrap();
        assert_eq!(json["sessions"].as_object().unwrap().len(), 25);
        let csv = session_text(&rows, 2, false, Fmt::Csv);
        assert_eq!(csv.lines().count(), 26, "header + every session: {csv}");
    }

    #[test]
    fn bucket_reports_carry_the_documented_columns() {
        let now = 1_800_000_000_000;
        let rows = vec![Row {
            at_ms: now - 60_000,
            provider: "opencode-go".into(),
            model: "glm-5.3-flash".into(),
            cost_usd: 1.5,
            input: 10,
            output: 20,
            cache_read: 30,
            cache_write: 40,
            ..Default::default()
        }];
        let csv = bucket_text(&rows, now, 7 * 86_400_000, 86_400_000, 0, false, Fmt::Csv);
        assert!(
            csv.starts_with("day,requests,tokens_in,tokens_out,cache_read,cost_usd\n"),
            "{csv}"
        );
        // cache-write is absent from the columns by design; the total row closes.
        assert!(!csv.contains("cache_write"), "{csv}");
        assert!(csv.contains(",10,20,30,1.50\n"), "{csv}");
        assert!(csv.trim_end().ends_with("total,1,10,20,30,1.50"), "{csv}");

        let json: serde_json::Value = serde_json::from_str(&bucket_text(
            &rows,
            now,
            7 * 86_400_000,
            86_400_000,
            0,
            false,
            Fmt::Json,
        ))
        .unwrap();
        assert_eq!(json["total"]["requests"], 1);
        assert_eq!(json["total"]["cacheRead"], 30);
        assert_eq!(json["days"].as_object().unwrap().len(), 1);
    }

    #[test]
    fn session_report_json_and_csv_agree_with_the_store() {
        let now = 1_800_000_000_000;
        let rows = vec![
            Row {
                at_ms: now - 60_000,
                session: "ses_first".into(),
                model: "glm-5.3-flash".into(),
                cost_usd: 2.0,
                input: 5,
                output: 6,
                cache_read: 7,
                ..Default::default()
            },
            Row {
                at_ms: now - 30_000,
                session: "ses_second".into(),
                model: "kimi-k3".into(),
                cost_usd: 1.0,
                ..Default::default()
            },
        ];
        let json: serde_json::Value =
            serde_json::from_str(&session_text(&rows, 20, false, Fmt::Json)).unwrap();
        assert_eq!(json["sessions"]["ses_first"]["tokensIn"], 5);
        assert_eq!(json["sessions"]["ses_first"]["models"], 1);
        assert_eq!(json["sessions"]["ses_second"]["costUsd"], 1.0);
        let csv = session_text(&rows, 20, false, Fmt::Csv);
        assert!(
            csv.starts_with("session,requests,tokens_in,tokens_out,cache_read,cost_usd\n"),
            "{csv}"
        );
        assert!(csv.contains("ses_second,1,0,0,0,1.00\n"), "{csv}");
    }

    #[test]
    fn model_report_projects_the_report_models() {
        let json: serde_json::Value =
            serde_json::from_str(&model_report(&report(), None, Fmt::Json)).unwrap();
        assert_eq!(json["source"], "opencode");
        assert_eq!(json["models"]["glm-5.3-flash"]["costUsd"], 30.0);
        assert_eq!(json["models"]["glm-5.3-flash"]["limit"], 60.0);
        let csv = model_report(&report(), None, Fmt::Csv);
        assert!(csv.contains("glm-5.3-flash,1,0,0,0,30.00\n"), "{csv}");
        // An id that never ran yields just the header, not a stray row.
        assert_eq!(
            model_report(&report(), Some("nope"), Fmt::Csv),
            "model,requests,tokens_in,tokens_out,cache_read,cost_usd\n"
        );
    }

    #[test]
    fn catalogue_json_carries_both_plans_and_windows() {
        let json: serde_json::Value = serde_json::from_str(&plans_json()).unwrap();
        assert_eq!(json["windows"]["fiveHour"], 0.2);
        assert_eq!(json["windows"]["monthly"], 1.0);
        assert_eq!(json["plans"][0]["id"], "go");
        assert_eq!(json["plans"][0]["allowanceByModel"]["glm-5.3-flash"], 60.0);
        assert_eq!(json["plans"][1]["priceUsd"], 40.0);
        assert!(!json["models"].as_array().unwrap().is_empty());
        assert!(!json["zen"].as_array().unwrap().is_empty());
    }

    #[test]
    fn models_lists_the_plan_and_marks_granted() {
        // The ungated table lists every catalogued model and marks the granted.
        let all = models_text("go", false, false);
        assert!(all.contains("glm-5.3-flash"), "{all}");
        assert!(all.contains("GRANTED"), "{all}");
        // The gated list keeps only what the plan grants.
        let gated = models_text("go", true, false);
        for line in gated.lines().skip(2) {
            assert!(
                line.trim_end().ends_with("yes"),
                "ungranted row kept: {line}"
            );
        }
        // JSON: one object per line, and gated drops the ungranted.
        let every: Vec<serde_json::Value> = models_json("go", false)
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert!(every.iter().any(|m| m["granted"] == false));
        assert!(every
            .iter()
            .any(|m| m["id"] == "glm-5.3-flash" && m["limit"] == 60.0));
        let only: Vec<serde_json::Value> = models_json("go", true)
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert!(!only.is_empty());
        assert!(only.iter().all(|m| m["granted"] == true));
    }

    #[test]
    fn statusline_json_mirrors_the_template_numbers() {
        let json: serde_json::Value =
            serde_json::from_str(&statusline_json(&report(), "go")).unwrap();
        assert_eq!(json["plan"], "go");
        assert_eq!(json["period"], "calendar month");
        assert_eq!(json["monthSpent"], 30.0);
        // No account-wide pool exists (limits are per model), so the cap keys
        // stay null; the per-model limits live on the models array.
        assert_eq!(json["monthCap"], serde_json::Value::Null);
        assert_eq!(json["fiveHourCap"], serde_json::Value::Null);
        assert_eq!(json["weeklyCap"], serde_json::Value::Null);
        assert_eq!(json["model"], "glm-5.3-flash");
    }

    #[test]
    fn plain_frames_carry_no_escapes() {
        let text = render_text(&report(), "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        assert!(
            !text.contains('\x1b'),
            "piped output must stay plain: {text}"
        );
        // The header rows carry no gauge and no share without an account; the
        // plain frame keeps the money the colour frame shows.
        assert!(text.contains("$30.00"), "{text}");
    }

    /// The monthly row is the only one with a real period end, so it alone gains
    /// the reset and the elapsed share; the rolling windows have no boundary
    /// and must not invent one. Nothing divides by a pool: limits are per model.
    #[test]
    fn monthly_row_carries_the_real_period_metrics() {
        let mut r = report();
        r.period_end_ms = Some(crate::ocuse::window::next_month(r.since_ms));
        let text = render_text(&r, "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);

        let monthly = text
            .lines()
            .find(|line| line.trim_start().starts_with("Monthly"))
            .expect("the monthly row");
        assert!(monthly.contains("resets"), "{monthly}");
        assert!(
            monthly.contains("window") && monthly.contains("% elapsed"),
            "the real period gives an elapsed share: {monthly}"
        );

        for label in ["5-hour", "Weekly"] {
            let row = text
                .lines()
                .find(|line| line.trim_start().starts_with(label))
                .unwrap_or_else(|| panic!("the {label} row"));
            assert!(!row.contains("elapsed"), "{label} has no boundary: {row}");
            assert!(!row.contains("resets"), "{label} has no boundary: {row}");
        }
    }

    /// The period header splits tokens like cmduse and names the resolved end
    /// date when the period has one (`--window all` has none).
    #[test]
    fn period_line_splits_tokens_and_shows_the_end_date() {
        let mut r = report();
        r.period_end_ms = Some(crate::ocuse::window::next_month(r.since_ms));
        let text = render_text(&r, "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        let header = text
            .lines()
            .find(|line| line.starts_with("period:"))
            .expect("the period line");
        assert!(
            header.contains(" in / "),
            "token split like cmduse: {header}"
        );
        assert!(header.contains(" out tokens"), "{header}");
        assert!(
            header.contains(&date_of(r.period_end_ms.unwrap() / 86_400_000)),
            "the resolved end date: {header}"
        );

        // No end resolved: no date is invented.
        let no_end = render_text(&report(), "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        let header = no_end
            .lines()
            .find(|line| line.starts_with("period:"))
            .expect("the period line");
        assert!(!header.contains("ends"), "{header}");
    }

    #[test]
    fn an_over_cap_window_is_flagged_in_both_modes() {
        // 30 spent against a 5-hour cap of 20% of the $60 limit = $12.
        let plain = render_text(&report(), "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        assert!(plain.contains("LIMIT EXCEEDED"), "{plain}");
        let coloured = render_text(&report(), "/tmp/opencode.db", 10, true, DEFAULT_BAR_WIDTH);
        assert!(coloured.contains("LIMIT EXCEEDED"), "{coloured}");
        assert!(
            coloured.contains(crate::render::RED),
            "the flag and the gauge are red: {coloured}"
        );
    }

    #[test]
    fn a_model_over_any_of_its_own_windows_is_flagged() {
        // The fixture is at 50% of the month but over the 5-hour share, and Go
        // meters per model per window: the row must say so, not just glow red.
        let plain = render_text(&report(), "/tmp/opencode.db", 10, false, DEFAULT_BAR_WIDTH);
        let row = plain
            .lines()
            .find(|line| line.starts_with("glm-5.3-flash"))
            .expect("the model row");
        assert!(row.contains("LIMIT EXCEEDED"), "{row}");
        // Share last, flag early: the informational column is clipped first.
        assert!(row.trim_end().ends_with('%'), "share ends the row: {row}");
    }

    #[test]
    fn a_model_within_its_limits_is_not_flagged() {
        let now = 1_800_000_000_000;
        // $5 against a $60 limit: every window is comfortably inside its share.
        let rows = vec![Row {
            at_ms: now - 60_000,
            provider: "opencode-go".into(),
            model: "glm-5.3-flash".into(),
            cost_usd: 5.0,
            ..Default::default()
        }];
        let report =
            crate::ocuse::window::build(&rows, &zen::catalog(), zen::DEFAULT_PLAN, now, None, None);
        for colour in [false, true] {
            let text = render_text(&report, "/tmp/opencode.db", 10, colour, DEFAULT_BAR_WIDTH);
            assert!(!text.contains("LIMIT EXCEEDED"), "colour={colour}: {text}");
        }
    }

    #[test]
    fn the_model_detail_spells_out_the_share() {
        let detail = model_text(&report(), "glm-5.3-flash", false);
        assert!(detail.contains("100.0% of period spend"), "{detail}");
        // A period with nothing to divide by omits the row rather than printing NaN.
        let empty = crate::ocuse::window::build(
            &[],
            &zen::catalog(),
            zen::DEFAULT_PLAN,
            1_800_000_000_000,
            None,
            None,
        );
        assert!(!model_text(&empty, "glm-5.3-flash", false).contains("share"));
    }

    #[test]
    fn colour_frames_get_the_palette_and_a_gauge() {
        // Gauge bars exist only where a share gates: the account's own rows.
        // The local estimate divides by no pool, so its rows carry no bar —
        // spend alone, never a gauge against a fiction. Palette assertions live
        // on the model table, whose per-model limits are real.
        let text = render_text(
            &report_with_account(),
            "/tmp/opencode.db",
            10,
            true,
            DEFAULT_BAR_WIDTH,
        );
        assert!(text.contains(crate::render::BOLD), "{text}");
        assert!(text.contains(crate::render::CYAN), "{text}");
        assert!(
            text.contains(crate::render::GREEN),
            "the 50% USE cell is green: {text}"
        );
        assert!(
            text.contains('━') && text.contains('╱'),
            "the account share's gauge bar: {text}"
        );
        assert!(text.contains("resets in"), "{text}");
    }

    #[test]
    fn watch_frame_ends_on_the_status_line_and_shows_bursts() {
        let frame = watch_frame(
            &report(),
            "/tmp/opencode.db",
            10,
            true,
            &[0.0, 1.5, 0.0],
            10,
            DEFAULT_BAR_WIDTH,
        );
        assert!(
            !frame.ends_with('\n'),
            "the caller's status line owns the last row"
        );
        assert!(frame.contains("spend bursts (10s samples)"), "{frame}");
        assert!(
            frame.contains('█'),
            "a nonzero delta shows as a tall bar: {frame}"
        );
    }

    #[test]
    fn idle_history_omits_the_sparkline() {
        let all_idle = watch_frame(
            &report(),
            "/tmp/opencode.db",
            10,
            true,
            &[0.0, 0.0],
            10,
            DEFAULT_BAR_WIDTH,
        );
        assert!(!all_idle.contains("spend bursts"), "{all_idle}");
        let first_frame = watch_frame(
            &report(),
            "/tmp/opencode.db",
            10,
            true,
            &[],
            10,
            DEFAULT_BAR_WIDTH,
        );
        assert!(!first_frame.contains("spend bursts"), "{first_frame}");
    }

    /// Every statusline placeholder resolves, unknown ones are dropped, and
    /// colours off means no SGR at all. The default template is the one the
    /// config ships, so it must render end to end.
    #[test]
    fn statusline_resolves_every_placeholder() {
        let r = report();
        let line = |tpl: &str| statusline_template(&r, "go", tpl, false, false, 20);

        // {plan} {period} are plain text
        assert_eq!(line("{plan}"), "go");
        assert_eq!(line("{period}"), "calendar month");
        // money placeholders reuse cmduse_core::money
        assert_eq!(line("{month}"), "$30.00");
        assert_eq!(line("{five_hour}"), "$30.00");
        assert_eq!(line("{weekly}"), "$30.00");
        // {models} is the top model by spend
        assert_eq!(line("{models}"), "glm-5.3-flash");
        // without an account there is no pool to divide by (limits are per
        // model), so the share placeholders degrade to the dash; the account's
        // own shares resolve when it answers (pinned by the account test above)
        assert_eq!(line("{month_pct}"), "—");
        assert_eq!(line("{month_bar}"), "");
        assert_eq!(line("{five_hour_pct}"), "—");
        assert_eq!(line("{weekly_pct}"), "—");

        // the default template resolves as a whole
        let default = line("{period} {month} · 5h {five_hour} · wk {weekly}");
        assert_eq!(default, "calendar month $30.00 · 5h $30.00 · wk $30.00");

        // unknown placeholders drop; text and separators pass through
        assert_eq!(line("{plan} {bogus} | tail"), "go  | tail");
        // unclosed brace is emitted verbatim
        assert_eq!(line("{plan} {oops"), "go {oops");
        // with colours off there is no escape anywhere
        assert!(!line("{plan} {month} {month_pct} {month_bar}").contains('\x1b'));
    }

    /// A period with no spend resolves no shares either way, so the pct
    /// placeholders degrade to the money-less dash instead of NaN.
    #[test]
    fn statusline_without_caps_degrades_gracefully() {
        let empty = crate::ocuse::window::build(
            &[],
            &zen::catalog(),
            zen::DEFAULT_PLAN,
            1_800_000_000_000,
            None,
            None,
        );
        let line = statusline_template(&empty, "go", "{month_pct} {models}", false, false, 20);
        assert_eq!(line, "— —");
    }

    /// The one-line compact frame is a single line and inlines the sparkline.
    #[test]
    fn compact_line_is_one_line_with_inline_sparkline() {
        let plain = compact_line(&report(), &[], true);
        assert_eq!(plain.lines().count(), 1, "{plain}");
        assert!(!plain.ends_with('\n'), "{plain}");
        let bursty = compact_line(&report(), &[0.0, 1.5], true);
        assert!(bursty.contains('█'), "nonzero delta shows: {bursty}");
        // colour off ⇒ no escapes; colour on ⇒ the palette appears
        assert!(!compact_line(&report(), &[], false).contains('\x1b'));
        assert!(compact_line(&report(), &[], true).contains(crate::render::BOLD));
    }
}