costroid 0.6.0

Local-first, FOCUS-native cost and limit visibility for your AI coding tools, right in your terminal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
use std::collections::BTreeMap;
use std::env;
use std::io::{self, IsTerminal};

use chrono::{DateTime, Datelike, Local, Utc};
use costroid_core::{
    AggregateTotals, Alert, AlertLevel, AnomaliesView, Anomaly, AnomalySignal, BenchFrontier,
    BenchView, BudgetExcludedTool, BudgetExclusion, BudgetPace, BudgetRow, BudgetScope, BudgetView,
    CostLane, CostLaneSummary, FocusRecord, ForecastView, FrontierPoint, FrontierStanding, GroupBy,
    LimitAvailability, LimitSummary, ModelRow, ModelsView, NowSummary, OverlayModel, Period,
    PeriodRange, ProviderCapabilityView, ProviderStatus, ProviderStatusKind, QuotaEta,
    QuotaEtaOutcome, QuotaEtaUnavailable, RepricingDelta, RepricingStatus, SpendForecast,
    TokenTotals, TrendsSummary,
};
use costroid_providers::{AuthMethod, DataSource, LimitKind, LimitMeasure, ProviderId};
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;

// The reconciliation renderer (T10c) is a pure function of the core `CostReconciliation`
// type, so it compiles + snapshot-tests in the default suite, but it is only *called* from
// the connect-gated `reconcile` command — gate the imports + functions on
// `any(feature = "connect", test)` so the default non-test build carries no dead code.
#[cfg(any(feature = "connect", test))]
use costroid_core::{
    AmountConfidence, BilledAbsence, CostReconciliation, DayReconciliation, ModelReconciliation,
    ReconciledReportStatus, UsdAmount, VendorBilled, VendorReportUnavailable,
};

const COST_BAR_WIDTH: usize = 12;
const DEFAULT_RENDER_WIDTH: usize = 64;
const LIMIT_BAR_WIDTH: usize = 12;
const STATUS_BAR_WIDTH: usize = 4;
// The near-limit meter/budget thresholds ALIAS the canonical core consts (T17) — ONE source, never
// a forked literal: the meter color the user sees and the alert that fires at the same fraction can
// never drift. The alert detector's `AlertThresholds` default these same two values.
const WARN_FRACTION: f64 = costroid_core::ALERT_WARN_FRACTION;
const CRITICAL_FRACTION: f64 = costroid_core::ALERT_CRITICAL_FRACTION;
/// A reading at least this old (capture time vs. the summary's `generated_at`) carries an
/// always-on "as of HH:MM" freshness stamp (STATUSLINE-CAPTURE-BRIEF §8): every Claude
/// reading is a cached push and every Codex window is only as fresh as its latest rollout
/// entry, so a hours-old reading must never render as a bare, confident meter. Tunable.
const LIMIT_FRESHNESS_STAMP_MINUTES: i64 = 10;
/// The distinct, color-free flag for a cross-check-failed (`Unverified`) reading — shown
/// INSTEAD of the confident `!`/`!!` state cue so a near-max unverified reading never
/// reads as a confident alarm (brief §8). Survives `--plain` / `NO_COLOR`.
const UNVERIFIED_CUE: &str = " ? unverified";
/// The push-only chat-under-report caveat carried by Claude `Available`/`Unverified`
/// lines (brief §8): claude.ai chat shares the 5h/7d limit but is invisible to the cache,
/// so the meter can read low.
const CLAUDE_CHAT_CAVEAT: &str =
    "reflects Claude Code's view; claude.ai chat usage may make true usage higher.";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RenderMode {
    Braille,
    Ascii,
    Plain,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RenderOptions {
    pub mode: RenderMode,
    pub ansi: bool,
    pub width: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SemanticStyle {
    Plain,
    Strong,
    Warn,
    Critical,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LimitState {
    Normal,
    Warn,
    Critical,
    Over,
}

impl RenderOptions {
    pub(crate) fn plain() -> Self {
        Self {
            mode: RenderMode::Plain,
            ansi: false,
            width: DEFAULT_RENDER_WIDTH,
        }
    }

    pub(crate) fn with_width(mut self, width: usize) -> Self {
        self.width = width.max(1);
        self
    }

    #[cfg(test)]
    fn braille(ansi: bool) -> Self {
        Self {
            mode: RenderMode::Braille,
            ansi,
            width: DEFAULT_RENDER_WIDTH,
        }
    }

    #[cfg(test)]
    fn ascii(ansi: bool) -> Self {
        Self {
            mode: RenderMode::Ascii,
            ansi,
            width: DEFAULT_RENDER_WIDTH,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StyledDocument {
    pub(crate) lines: Vec<StyledLine>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StyledLine {
    pub(crate) spans: Vec<StyledSpan>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StyledSpan {
    pub(crate) content: String,
    pub(crate) style: SemanticStyle,
}

impl StyledDocument {
    pub(crate) fn new() -> Self {
        Self { lines: Vec::new() }
    }

    pub(crate) fn push(&mut self, line: StyledLine) {
        self.lines.push(line);
    }

    pub(crate) fn render(&self, options: RenderOptions) -> String {
        let mut out = String::new();
        for line in &self.lines {
            out.push_str(&line.render(options));
            out.push('\n');
        }
        out
    }
}

impl StyledLine {
    pub(crate) fn new() -> Self {
        Self { spans: Vec::new() }
    }

    pub(crate) fn plain(content: impl Into<String>) -> Self {
        Self {
            spans: vec![StyledSpan::plain(content)],
        }
    }

    pub(crate) fn push_plain(&mut self, content: impl Into<String>) {
        self.spans.push(StyledSpan::plain(content));
    }

    pub(crate) fn push_styled(&mut self, content: impl Into<String>, style: SemanticStyle) {
        self.spans.push(StyledSpan {
            content: content.into(),
            style,
        });
    }

    pub(crate) fn render(&self, options: RenderOptions) -> String {
        let mut out = String::new();
        for span in &self.spans {
            out.push_str(&span.render(options));
        }
        out
    }
}

impl StyledSpan {
    pub(crate) fn plain(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            style: SemanticStyle::Plain,
        }
    }

    fn styled(content: impl Into<String>, style: SemanticStyle) -> Self {
        Self {
            content: content.into(),
            style,
        }
    }

    fn render(&self, options: RenderOptions) -> String {
        if !options.ansi || options.mode == RenderMode::Plain || self.style == SemanticStyle::Plain
        {
            return self.content.clone();
        }
        let code = match self.style {
            SemanticStyle::Plain => return self.content.clone(),
            SemanticStyle::Strong => "1",
            SemanticStyle::Warn => "33;1",
            SemanticStyle::Critical => "31;1",
        };
        format!("\x1b[{code}m{}\x1b[0m", self.content)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct EnvSnapshot {
    term: Option<String>,
    lang: Option<String>,
    lc_all: Option<String>,
    lc_ctype: Option<String>,
    no_color: Option<String>,
}

impl EnvSnapshot {
    fn current() -> Self {
        Self {
            term: env::var("TERM").ok(),
            lang: env::var("LANG").ok(),
            lc_all: env::var("LC_ALL").ok(),
            lc_ctype: env::var("LC_CTYPE").ok(),
            no_color: env::var("NO_COLOR").ok(),
        }
    }
}

pub(crate) fn detect_render_options(plain: bool) -> RenderOptions {
    select_render_options(plain, io::stdout().is_terminal(), &EnvSnapshot::current())
}

fn select_render_options(plain: bool, stdout_is_tty: bool, env: &EnvSnapshot) -> RenderOptions {
    if plain || !stdout_is_tty {
        return RenderOptions::plain();
    }

    let no_color = env
        .no_color
        .as_deref()
        .map(str::trim)
        .is_some_and(|value| !value.is_empty());
    let mode = if braille_capable(env) {
        RenderMode::Braille
    } else {
        RenderMode::Ascii
    };

    RenderOptions {
        mode,
        ansi: !no_color,
        width: DEFAULT_RENDER_WIDTH,
    }
}

fn braille_capable(env: &EnvSnapshot) -> bool {
    if env
        .term
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(|term| term.eq_ignore_ascii_case("dumb"))
        .unwrap_or(true)
    {
        return false;
    }

    match locale_value(env) {
        Some(locale) => {
            let locale = locale.to_ascii_uppercase();
            locale.contains("UTF-8") || locale.contains("UTF8")
        }
        None => true,
    }
}

fn locale_value(env: &EnvSnapshot) -> Option<&str> {
    [&env.lc_all, &env.lc_ctype, &env.lang]
        .into_iter()
        .filter_map(Option::as_deref)
        .map(str::trim)
        .find(|value| !value.is_empty())
}

// The plain string form of the now view. The production `now` path renders through
// `render_now_with_alerts` (which prepends the opt-in alert banner, T17), so this bare form is now
// only a test convenience for the now-document snapshots / ASCII-purity gates.
#[cfg(test)]
pub(crate) fn render_now(summary: &NowSummary, options: RenderOptions) -> String {
    render_now_document(summary, options).render(options)
}

pub(crate) fn render_trends(summary: &TrendsSummary, options: RenderOptions) -> String {
    render_trends_document(summary, options).render(options)
}

pub(crate) fn render_frontier(view: &BenchView, options: RenderOptions) -> String {
    render_frontier_document(view, options).render(options)
}

pub(crate) fn render_frontier_document(view: &BenchView, options: RenderOptions) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_frontier_plain_document(view),
        RenderMode::Braille | RenderMode::Ascii => render_frontier_visual_document(view, options),
    }
}

// ---------------------------------------------------------------------------
// Reconciliation surface (T10c) — `costroid reconcile`. Renders T9c's
// `CostReconciliation` HONESTLY: signed variance per UTC day + model; TYPED vendor-side
// absence as text, NEVER a fabricated $0; every caveat footnoted; the local figure ALWAYS
// labeled an estimate (`~`). It is a pure function of the core type (no `costroid-connect`
// dependency), so its snapshots run in the default test suite; the connect-gated `reconcile`
// command (apps/cli/src/reconcile.rs) fetches the report and calls it. Same monochrome voice
// as the frontier — no amber (reserved for near-limit); the over/under direction is carried
// as TEXT, never color. Gated `any(feature = "connect", test)` so the default non-test build
// (which never calls it) carries no dead code.
// ---------------------------------------------------------------------------

/// Render one vendor's reconciliation section to a string in `options`' mode.
#[cfg(any(feature = "connect", test))]
pub(crate) fn render_reconciliation(
    vendor: &str,
    window_label: &str,
    recon: &CostReconciliation,
    options: RenderOptions,
) -> String {
    render_reconciliation_document(vendor, window_label, recon, options).render(options)
}

#[cfg(any(feature = "connect", test))]
pub(crate) fn render_reconciliation_document(
    vendor: &str,
    window_label: &str,
    recon: &CostReconciliation,
    options: RenderOptions,
) -> StyledDocument {
    let mut out = StyledDocument::new();

    // Header: the vendor + section totals (estimate always `~`-marked; the invoice total
    // only when a report was available).
    let (total_est, total_billed) = reconciliation_totals(recon);
    let money = match total_billed {
        Some(billed) => format!(
            "est {} / inv {}",
            format_money(&total_est, Some("USD"), true),
            format_money(&billed, Some("USD"), false),
        ),
        None => format!("est {}", format_money(&total_est, Some("USD"), true)),
    };
    if options.mode == RenderMode::Plain {
        // Plain follows the established `costroid <screen>` convention (a clean header, like
        // now/trends/frontier's plain builders) — never the visual builder's `costroid
        // costroid` doubling, which would read awkwardly to a screen reader.
        push_line(&mut out, &format!("costroid reconcile  {vendor}  {money}"));
    } else {
        push_header_line(&mut out, mark(options), vendor, money, options);
    }
    push_line(
        &mut out,
        &fold_ascii(&format!("estimate vs invoice — {window_label}"), options),
    );
    // The standing hedge (DESIGN-SYSTEM voice): the local figure is an estimate; the vendor
    // invoice is the source of truth.
    push_line(
        &mut out,
        "Local figures are estimates (your tokens x current prices); the vendor invoice is the source of truth.",
    );

    // Report-level unavailability (Gemini, not-connected, auth failure, …): name the typed
    // reason once up top, then STILL surface the local estimate day by day below — every
    // vendor cell renders typed-absent, never a fabricated $0.
    if let ReconciledReportStatus::Unavailable(reason) = &recon.report {
        push_line(
            &mut out,
            &fold_ascii(
                &format!(
                    "vendor invoice unavailable: {}",
                    report_unavailable_text(reason, vendor)
                ),
                options,
            ),
        );
    }

    push_reconcile_rule(&mut out, options);

    if recon.days.is_empty() {
        push_line(
            &mut out,
            "No local usage recorded for this vendor in this window.",
        );
    }
    for day in &recon.days {
        push_reconciliation_day(&mut out, day, vendor, options);
    }

    push_reconciliation_footnotes(&mut out, recon, options);
    out
}

/// One UTC day (its total) plus its per-model breakdown, indented.
#[cfg(any(feature = "connect", test))]
fn push_reconciliation_day(
    out: &mut StyledDocument,
    day: &DayReconciliation,
    vendor: &str,
    options: RenderOptions,
) {
    let line = format!(
        "{date}  est {est}   {inv}   {var}",
        date = day.date,
        est = format_money(&day.local_estimate.as_usd(), Some("USD"), true),
        inv = reconcile_billed_cell(&day.vendor_billed, vendor),
        var = reconcile_variance_cell(
            day.variance,
            day.variance_pct,
            billed_usd(&day.vendor_billed),
            options
        ),
    );
    push_line(out, &fold_ascii(&line, options));
    for model in &day.by_model {
        push_reconciliation_model(out, model, vendor, options);
    }
}

#[cfg(any(feature = "connect", test))]
fn push_reconciliation_model(
    out: &mut StyledDocument,
    model: &ModelReconciliation,
    vendor: &str,
    options: RenderOptions,
) {
    // Mark a row whose vendor figure is best-effort (OpenAI per-model, derived from line
    // items) with `*`; the footnote explains it.
    let marker = if matches!(model.confidence, Some(AmountConfidence::DerivedBestEffort)) {
        " *"
    } else {
        ""
    };
    let line = format!(
        "    {name:<22} est {est}   {inv}   {var}{marker}",
        name = model.model,
        est = format_money(&model.local_estimate.as_usd(), Some("USD"), true),
        inv = reconcile_billed_cell(&model.vendor_billed, vendor),
        var = reconcile_variance_cell(
            model.variance,
            model.variance_pct,
            billed_usd(&model.vendor_billed),
            options
        ),
    );
    push_line(out, &fold_ascii(&line, options));
}

/// The vendor-billed cell: a dollar invoice figure when billed, otherwise the TYPED absence
/// reason as TEXT — never a fabricated `$0`. (Any em-dash in a reason message is folded by
/// the caller's `fold_ascii` on the whole line.)
#[cfg(any(feature = "connect", test))]
fn reconcile_billed_cell(billed: &VendorBilled, vendor: &str) -> String {
    match billed {
        VendorBilled::Billed(amount) => {
            format!("inv {}", format_money(&amount.as_usd(), Some("USD"), false))
        }
        VendorBilled::Unavailable(absence) => match absence {
            BilledAbsence::DayNotCovered => "report doesn't cover this day".to_string(),
            BilledAbsence::ModelNotInReport => "not attributed by the vendor".to_string(),
            BilledAbsence::ReportUnavailable(reason) => report_unavailable_text(reason, vendor),
        },
    }
}

/// The billed dollar figure when the vendor side is present, else `None` (a typed absence —
/// where the variance is also `None`). The variance cell uses it to detect a sub-cent
/// denominator (one that displays as `$0.00`) so a percentage doesn't explode against it.
#[cfg(any(feature = "connect", test))]
fn billed_usd(billed: &VendorBilled) -> Option<Decimal> {
    match billed {
        VendorBilled::Billed(amount) => Some(amount.as_usd()),
        VendorBilled::Unavailable(_) => None,
    }
}

/// The typed reason a whole report is unavailable. `NotConnected` becomes an actionable
/// "connect <vendor> first"; every other reason uses its single-sourced core message.
#[cfg(any(feature = "connect", test))]
fn report_unavailable_text(reason: &VendorReportUnavailable, vendor: &str) -> String {
    match reason {
        VendorReportUnavailable::NotConnected => format!("connect {vendor} first"),
        other => other.message(),
    }
}

/// The signed-variance cell: `+$X over (+P%)` / `-$X under (-P%)` / `exact`, or the typed
/// "—" when the vendor side is absent (no fabricated delta). The percentage is ROUNDED here,
/// at the render boundary — full `Decimal` precision is preserved upstream by the engine.
/// `billed_usd` is the vendor figure the percentage is relative to (its denominator); it's
/// used only to catch the sub-cent-denominator case below.
#[cfg(any(feature = "connect", test))]
fn reconcile_variance_cell(
    variance: Option<UsdAmount>,
    variance_pct: Option<Decimal>,
    billed_usd: Option<Decimal>,
    options: RenderOptions,
) -> String {
    let variance = match variance {
        Some(variance) => variance.as_usd(),
        // Typed vendor-side absence → "—" (folded to "-" outside braille), never "$0.00".
        None => return dash(options).to_string(),
    };
    if variance.is_zero() {
        return "exact".to_string();
    }
    let over = variance > Decimal::ZERO;
    let word = if over { "over" } else { "under" };
    let abs = variance.abs();
    // A genuinely non-zero variance whose dollar magnitude rounds below a cent: show
    // "<$0.01" (no numeric sign — the over/under word carries direction) so the row never
    // reads as a misleading "+$0.00 over". Real vendor bills are sub-cent (Anthropic bills
    // fractions of a cent), so this is reachable, not theoretical.
    let variance_subcent = abs.round_dp(2).is_zero();
    let money = if variance_subcent {
        format!("<$0.01 {word}")
    } else {
        let sign = if over { "+" } else { "-" };
        format!("{sign}{} {word}", format_money(&abs, Some("USD"), false))
    };
    match variance_pct {
        // A ≥ $0.01 variance against a billed figure that itself rounds below a cent (so the
        // invoice cell shows "$0.00") makes the percentage explode against an effectively-
        // invisible denominator (e.g. "+$1.40 over (+69950.0%)" beside "inv $0.00"). Name the
        // denominator's magnitude instead — parallel to the "(vs $0 billed)" case below. A
        // sub-cent variance keeps its percentage: those magnitudes are coherent and small.
        Some(_)
            if !variance_subcent
                && matches!(billed_usd, Some(billed) if !billed.is_zero() && billed.round_dp(2).is_zero()) =>
        {
            format!("{money} (vs <$0.01 billed)")
        }
        Some(pct) => format!("{money} ({})", format_signed_pct(pct)),
        // The vendor billed $0 → the percentage is undefined; the signed dollar still stands.
        None => format!("{money} (vs $0 billed)"),
    }
}

/// A percentage rounded to one decimal at the render boundary, with an explicit leading sign
/// and a uniform single fractional digit (so `-100.0%` lines up with `+20.0%`). The sign is
/// taken from the **unrounded** value, so a tiny negative that rounds to `0.0` still reads
/// `-0.0%` (sign-consistent with its `under`) rather than flipping to `+0.0%`.
#[cfg(any(feature = "connect", test))]
fn format_signed_pct(pct: Decimal) -> String {
    let mut magnitude = pct.abs().round_dp(1);
    magnitude.rescale(1);
    let sign = if pct.is_sign_negative() { "-" } else { "+" };
    format!("{sign}{magnitude}%")
}

/// The reconciliation section rule: an ASCII `-` outside braille (Plain is the accessibility
/// floor and must be pure ASCII, unlike the shared `push_rule` which keeps `─` in Plain).
#[cfg(any(feature = "connect", test))]
fn push_reconcile_rule(out: &mut StyledDocument, options: RenderOptions) {
    let glyph = if options.mode == RenderMode::Braille {
        ""
    } else {
        "-"
    };
    push_line(out, &glyph.repeat(options.width.max(1)));
}

/// Section totals: estimated dollars (always summed) and billed dollars (only when a report
/// was available — `None` folds the invoice total out of the header).
#[cfg(any(feature = "connect", test))]
fn reconciliation_totals(recon: &CostReconciliation) -> (Decimal, Option<Decimal>) {
    let total_est = recon
        .days
        .iter()
        .fold(Decimal::ZERO, |acc, day| acc + day.local_estimate.as_usd());
    let total_billed = match recon.report {
        ReconciledReportStatus::Available => Some(recon.days.iter().fold(
            Decimal::ZERO,
            |acc, day| match &day.vendor_billed {
                VendorBilled::Billed(amount) => acc + amount.as_usd(),
                VendorBilled::Unavailable(_) => acc,
            },
        )),
        ReconciledReportStatus::Unavailable(_) => None,
    };
    (total_est, total_billed)
}

/// The carried-through caveats, footnoted (they survive on `CostReconciliation.caveats`).
#[cfg(any(feature = "connect", test))]
fn push_reconciliation_footnotes(
    out: &mut StyledDocument,
    recon: &CostReconciliation,
    options: RenderOptions,
) {
    if recon.caveats.per_model_derived_best_effort {
        push_line(
            out,
            &fold_ascii(
                "* OpenAI per-model figures are best-effort (derived from line items).",
                options,
            ),
        );
    }
    if recon.caveats.priority_tier_absent {
        push_line(
            out,
            &fold_ascii(
                "Note: Anthropic Priority-Tier spend isn't in this report — the bill may be higher.",
                options,
            ),
        );
    }
    // When a report is available but doesn't span every local day, the header `inv` total
    // covers only the spanned days while `est` covers all of them — footnote it so the
    // headline pair isn't misread as a real over-estimate.
    let some_day_uncovered = matches!(recon.report, ReconciledReportStatus::Available)
        && recon.days.iter().any(|day| {
            matches!(
                day.vendor_billed,
                VendorBilled::Unavailable(BilledAbsence::DayNotCovered)
            )
        });
    if some_day_uncovered {
        push_line(
            out,
            "Note: the invoice total covers only the days this report spans; days outside it show \"report doesn't cover this day\".",
        );
    }
}

/// The absence/placeholder dash — an em-dash on a braille TTY, an ASCII hyphen otherwise.
#[cfg(any(feature = "connect", test))]
fn dash(options: RenderOptions) -> &'static str {
    if options.mode == RenderMode::Braille {
        ""
    } else {
        "-"
    }
}

/// Fold the handful of non-ASCII glyphs reconciliation copy can carry (`—`, `…`, `×`, `·`)
/// to ASCII for the Ascii/Plain modes — Plain is the accessibility floor (every byte ASCII),
/// and Ascii targets non-UTF-8 terminals — while a braille TTY keeps them.
#[cfg(any(feature = "connect", test))]
fn fold_ascii(value: &str, options: RenderOptions) -> String {
    if options.mode == RenderMode::Braille {
        value.to_string()
    } else {
        value
            .replace('', "-")
            .replace('', "...")
            .replace('×', "x")
            .replace('·', "-")
    }
}

// ---------------------------------------------------------------------------
// Frontier surface — the cost-vs-quality scatter. Monochrome (Plain/Strong only;
// never Warn — amber is reserved for the near-limit state). Informs, never prescribes.
// ---------------------------------------------------------------------------

const SCATTER_HEIGHT: usize = 6;
/// Braille 2x4 dot layout: `[row][col]` → dot number (left col 1,2,3,7; right 4,5,6,8).
const SCATTER_DOT_AT: [[u8; 2]; 4] = [[1, 4], [2, 5], [3, 6], [7, 8]];

/// A single benchmark point in plot space. The rasterizer is pure geometry — it knows
/// nothing about models, names, or money.
struct PlotPoint {
    x: f64,
    y: f64,
    on_frontier: bool,
}

fn render_frontier_visual_document(view: &BenchView, options: RenderOptions) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_header_line(
        &mut out,
        mark(options),
        "cost vs quality",
        format_money(&total_overlay_spend(view), Some("USD"), true),
        options,
    );

    for frontier in &view.frontiers {
        push_rule(&mut out, options);
        push_line(
            &mut out,
            &format!(
                "{} {} {}   as of {}",
                frontier.name,
                // The em-dash is not ASCII — substitute in the Ascii fallback mode.
                if options.mode == RenderMode::Ascii {
                    "-"
                } else {
                    ""
                },
                role_label(&frontier.role),
                frontier.as_of
            ),
        );
        push_line(&mut out, &format!("  {}", frontier.cost_note));
        push_line(&mut out, &format!("  source: {}", frontier.source));
        let points = plot_points(frontier);
        let width = scatter_width(options);
        for row in scatter_rows(&points, width, SCATTER_HEIGHT, options) {
            push_line(&mut out, &format!("  {row}"));
        }
        push_line(&mut out, "  x: cost/task ->   y: score (high = top)");
        for point in &frontier.points {
            push_line(&mut out, &format!("  {}", point_line(point, options)));
        }
    }

    push_rule(&mut out, options);
    push_line(&mut out, "your models (API-billed):");
    if view.no_api_usage || view.overlay.is_empty() {
        push_line(&mut out, "  no API-billed usage to compare");
    } else {
        for model in &view.overlay {
            out.push(overlay_line(model));
        }
    }

    push_rule(&mut out, options);
    push_line(
        &mut out,
        &mode_insight(frontier_insight_line(view), options),
    );
    push_provider_notes(&mut out, &view.providers);
    push_empty_provider_guidance(&mut out, &view.providers);
    out
}

fn render_frontier_plain_document(view: &BenchView) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid frontier");
    for frontier in &view.frontiers {
        push_line(
            &mut out,
            &format!(
                "{} - {}, source {}, as of {}",
                frontier.name,
                role_label(&frontier.role),
                frontier.source,
                frontier.as_of
            ),
        );
        push_line(&mut out, &format!("  caveat: {}", frontier.cost_note));
        for point in &frontier.points {
            push_line(&mut out, &format!("  {}", plain_point_line(point, view)));
        }
    }
    if view.no_api_usage || view.overlay.is_empty() {
        push_line(&mut out, "your models: no API-billed usage to compare");
    } else {
        push_line(&mut out, "your models (API-billed):");
        for model in &view.overlay {
            push_line(&mut out, &format!("  {}", plain_overlay_line(model)));
        }
    }
    push_line(&mut out, &plain_frontier_insight_line(view));
    push_provider_notes(&mut out, &view.providers);
    push_empty_provider_guidance(&mut out, &view.providers);
    out
}

fn total_overlay_spend(view: &BenchView) -> Decimal {
    view.overlay
        .iter()
        .fold(Decimal::ZERO, |total, model| total + model.billed_cost)
}

fn role_label(role: &str) -> String {
    match role {
        "primary" => "primary (neutral)".to_string(),
        "corroborating" => "corroborating (vendor)".to_string(),
        other => other.to_string(),
    }
}

fn plot_points(frontier: &BenchFrontier) -> Vec<PlotPoint> {
    frontier
        .points
        .iter()
        .filter_map(|point| {
            let cost = point.cost_per_task_usd?;
            Some(PlotPoint {
                x: cost.to_f64().unwrap_or(0.0),
                y: point.score_pct.to_f64().unwrap_or(0.0),
                on_frontier: point.standing == FrontierStanding::OnFrontier,
            })
        })
        .collect()
}

/// The compact text for a [`FrontierStanding`] — shared by the frontier point lines and the
/// Models tab's per-appearance standing. Pure ASCII. (The frontier's *plain* point line uses
/// a distinct yes/no phrasing, so it intentionally does not route through here.)
fn frontier_standing_text(standing: &FrontierStanding) -> String {
    match standing {
        FrontierStanding::OnFrontier => "on frontier".to_string(),
        FrontierStanding::Dominated { by } => format!("off (dominated by {by})"),
        FrontierStanding::CostUnknown => "score only".to_string(),
    }
}

fn point_line(point: &FrontierPoint, options: RenderOptions) -> String {
    let cost = match point.cost_per_task_usd {
        Some(value) => format!("@ {}", format_money(&value, Some("USD"), true)),
        None => "@ cost n/a".to_string(),
    };
    let standing = frontier_standing_text(&point.standing);
    let note = point
        .note
        .as_deref()
        .map(|note| {
            // The em-dash is not ASCII — substitute in the Ascii fallback mode.
            let separator = if options.mode == RenderMode::Ascii {
                "--"
            } else {
                ""
            };
            format!("  {separator} {note}")
        })
        .unwrap_or_default();
    format!(
        "{}  {}% {}  {}{}",
        point.label,
        score_text(point),
        cost,
        standing,
        note
    )
}

fn plain_point_line(point: &FrontierPoint, view: &BenchView) -> String {
    let cost = match point.cost_per_task_usd {
        Some(value) => format!("{}/task", format_money(&value, Some("USD"), true)),
        None => "n/a".to_string(),
    };
    let standing = match &point.standing {
        FrontierStanding::OnFrontier => "yes".to_string(),
        FrontierStanding::Dominated { by } => format!("no (dominated by {by})"),
        FrontierStanding::CostUnknown => "n/a (no published cost)".to_string(),
    };
    let spend = view
        .overlay
        .iter()
        .find(|model| model.model_id == point.model_id)
        .map(|model| format_money(&model.billed_cost, Some("USD"), true))
        .unwrap_or_else(|| "none".to_string());
    let note = point
        .note
        .as_deref()
        .map(|note| format!(" -- {note}"))
        .unwrap_or_default();
    format!(
        "{}: score {}%, cost {}, on frontier: {}, your API spend: {}{}",
        point.label,
        score_text(point),
        cost,
        standing,
        spend,
        note
    )
}

fn score_text(point: &FrontierPoint) -> String {
    point.score_pct.normalize().to_string()
}

fn overlay_line(model: &OverlayModel) -> StyledLine {
    // An unpriced baseline carries a placeholder $0/undercount — render the gap,
    // never the misleading dollar figure or a comparison against it.
    if !model.fully_priced {
        return StyledLine::plain(format!(
            "  {}  spend not fully priced (frontier comparison unavailable)",
            model.model_id
        ));
    }
    let mut line = StyledLine::new();
    line.push_plain(format!("  {}  spent ", model.model_id));
    line.push_styled(
        format_money(&model.billed_cost, Some("USD"), true),
        SemanticStyle::Strong,
    );
    if let Some(delta) = best_delta(model) {
        let phrase = delta_phrase(delta);
        if !phrase.is_empty() {
            line.push_plain(phrase);
        }
    }
    line
}

fn plain_overlay_line(model: &OverlayModel) -> String {
    if !model.fully_priced {
        return format!(
            "{}: spend not fully priced (frontier comparison unavailable)",
            model.model_id
        );
    }
    let mut line = format!(
        "{}: spent {}",
        model.model_id,
        format_money(&model.billed_cost, Some("USD"), true)
    );
    if let Some(delta) = best_delta(model) {
        line.push_str(&delta_phrase(delta));
    }
    line
}

/// The most-favorable computed re-pricing comparison (largest saving), if any.
fn best_delta(model: &OverlayModel) -> Option<&RepricingDelta> {
    model
        .repricing
        .iter()
        .filter(|delta| delta.status == RepricingStatus::Computed)
        .min_by(|left, right| left.delta_usd.cmp(&right.delta_usd))
}

/// Cost-only, equal-volume phrasing. INFORM, never PRESCRIBE — states a cost fact,
/// never "switch to X".
fn delta_phrase(delta: &RepricingDelta) -> String {
    let money = format_money(&delta.delta_usd.abs(), Some("USD"), true);
    if delta.delta_usd < Decimal::ZERO {
        format!(
            "; {} costs about {} less at equal volume",
            delta.target_model_id, money
        )
    } else if delta.delta_usd > Decimal::ZERO {
        format!(
            "; {} costs about {} more at equal volume",
            delta.target_model_id, money
        )
    } else {
        String::new()
    }
}

fn frontier_insight_line(view: &BenchView) -> String {
    if view.no_api_usage || view.overlay.is_empty() {
        return "◆ no API-billed usage to compare against the frontier. (estimated)".to_string();
    }
    let top = view
        .overlay
        .iter()
        .max_by(|left, right| left.billed_cost.cmp(&right.billed_cost));
    match top {
        Some(model) => {
            if let Some(delta) = best_delta(model) {
                if delta.delta_usd < Decimal::ZERO {
                    return format!(
                        "{} drove most of your API spend; {} sits cheaper on the frontier at equal volume. (estimated)",
                        model.model_id, delta.target_model_id
                    );
                }
            }
            if model
                .appearances
                .iter()
                .any(|appearance| appearance.standing == FrontierStanding::OnFrontier)
            {
                format!(
                    "{} drove most of your API spend and already sits on the frontier. (estimated)",
                    model.model_id
                )
            } else {
                format!(
                    "{} drove most of your API spend. (estimated)",
                    model.model_id
                )
            }
        }
        None => "◆ no API-billed usage to compare against the frontier. (estimated)".to_string(),
    }
}

fn plain_frontier_insight_line(view: &BenchView) -> String {
    frontier_insight_line(view).replace('', "insight:")
}

fn scatter_width(options: RenderOptions) -> usize {
    options.width.saturating_sub(4).clamp(20, 40)
}

fn scatter_rows(
    points: &[PlotPoint],
    width: usize,
    height: usize,
    options: RenderOptions,
) -> Vec<String> {
    match options.mode {
        RenderMode::Braille => braille_scatter(points, width, height, true),
        _ => ascii_scatter(points, width, height),
    }
}

/// Hand-rasterized braille scatter (no Ratatui `Canvas`, consistent with the sparkline).
/// A `Vec<u8>` of `w*h` cells, one braille bitmask byte each; points set dots in a
/// `w*2 × h*4` dot grid (y inverted so high score is at top); frontier points are bold
/// full cells, optionally joined by a thin connector.
fn braille_scatter(
    points: &[PlotPoint],
    w_cells: usize,
    h_cells: usize,
    draw_line: bool,
) -> Vec<String> {
    let w = w_cells.max(1);
    let h = h_cells.max(1);
    if points.is_empty() {
        return vec![braille_blank().to_string().repeat(w); h];
    }
    let dot_w = w * 2;
    let dot_h = h * 4;
    let mut buf = vec![0_u8; w * h];
    let (x_min, x_max) = min_max(points.iter().map(|point| point.x));
    let (y_min, y_max) = min_max(points.iter().map(|point| point.y));

    for point in points {
        let dx = axis_index(point.x, x_min, x_max, dot_w, false);
        let dy = axis_index(point.y, y_min, y_max, dot_h, true);
        set_scatter_dot(&mut buf, w, h, dx, dy);
    }

    let mut frontier_dots: Vec<(usize, usize)> = points
        .iter()
        .filter(|point| point.on_frontier)
        .map(|point| {
            (
                axis_index(point.x, x_min, x_max, dot_w, false),
                axis_index(point.y, y_min, y_max, dot_h, true),
            )
        })
        .collect();
    frontier_dots.sort_by_key(|&(dx, _)| dx);
    for &(dx, dy) in &frontier_dots {
        let cx = (dx / 2).min(w - 1);
        let cy = (dy / 4).min(h - 1);
        buf[cy * w + cx] = 0xFF;
    }
    if draw_line {
        for pair in frontier_dots.windows(2) {
            scatter_line(&mut buf, w, h, pair[0], pair[1]);
        }
    }

    (0..h)
        .map(|cy| {
            (0..w)
                .map(|cx| byte_to_braille(buf[cy * w + cx]))
                .collect::<String>()
        })
        .collect()
}

fn ascii_scatter(points: &[PlotPoint], w_cells: usize, h_cells: usize) -> Vec<String> {
    let w = w_cells.max(1);
    let h = h_cells.max(1);
    let mut grid = vec![vec![' '; w]; h];
    if !points.is_empty() {
        let (x_min, x_max) = min_max(points.iter().map(|point| point.x));
        let (y_min, y_max) = min_max(points.iter().map(|point| point.y));
        for point in points {
            let cx = axis_index(point.x, x_min, x_max, w, false);
            let cy = axis_index(point.y, y_min, y_max, h, true);
            let glyph = if point.on_frontier { '#' } else { '.' };
            if !(grid[cy][cx] == '#' && glyph == '.') {
                grid[cy][cx] = glyph;
            }
        }
    }
    grid.into_iter()
        .map(|row| row.into_iter().collect())
        .collect()
}

fn set_scatter_dot(buf: &mut [u8], w: usize, h: usize, dx: usize, dy: usize) {
    let cx = (dx / 2).min(w - 1);
    let cy = (dy / 4).min(h - 1);
    let dot = SCATTER_DOT_AT[dy % 4][dx % 2];
    buf[cy * w + cx] |= bit_for_dot(dot);
}

fn scatter_line(buf: &mut [u8], w: usize, h: usize, a: (usize, usize), b: (usize, usize)) {
    let mut x0 = a.0 as isize;
    let mut y0 = a.1 as isize;
    let x1 = b.0 as isize;
    let y1 = b.1 as isize;
    let dx = (x1 - x0).abs();
    let dy = -(y1 - y0).abs();
    let sx = if x0 < x1 { 1 } else { -1 };
    let sy = if y0 < y1 { 1 } else { -1 };
    let mut err = dx + dy;
    loop {
        let px = usize::try_from(x0).unwrap_or(0);
        let py = usize::try_from(y0).unwrap_or(0);
        set_scatter_dot(buf, w, h, px, py);
        if x0 == x1 && y0 == y1 {
            break;
        }
        let e2 = 2 * err;
        if e2 >= dy {
            err += dy;
            x0 += sx;
        }
        if e2 <= dx {
            err += dx;
            y0 += sy;
        }
    }
}

fn min_max(values: impl Iterator<Item = f64>) -> (f64, f64) {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for value in values {
        if value < lo {
            lo = value;
        }
        if value > hi {
            hi = value;
        }
    }
    if lo.is_finite() && hi.is_finite() {
        (lo, hi)
    } else {
        (0.0, 1.0)
    }
}

fn axis_index(value: f64, lo: f64, hi: f64, n: usize, invert: bool) -> usize {
    let max_index = n.saturating_sub(1) as f64;
    let fraction = if hi > lo {
        (value - lo) / (hi - lo)
    } else {
        0.5
    };
    let fraction = if invert { 1.0 - fraction } else { fraction };
    (fraction * max_index).round().clamp(0.0, max_index) as usize
}

pub(crate) fn render_statusline(summary: &NowSummary, options: RenderOptions) -> String {
    render_statusline_line(summary, options).render(options)
}

pub(crate) fn render_now_document(summary: &NowSummary, options: RenderOptions) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_now_plain_document(summary),
        RenderMode::Braille | RenderMode::Ascii => render_now_visual_document(summary, options),
    }
}

/// The `now` document with the opt-in alert banner (T17) prepended ATOP it. When `alerts` is empty
/// (the feature is off, or no crossing is active) this is byte-identical to [`render_now_document`].
/// The shared composition for both the plain CLI (`costroid`) and the TUI Now tab.
pub(crate) fn render_now_with_alerts_document(
    summary: &NowSummary,
    alerts: &[Alert],
    options: RenderOptions,
) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_alert_banner(&mut out, alerts, options);
    out.lines
        .extend(render_now_document(summary, options).lines);
    out
}

/// String form of [`render_now_with_alerts_document`] — used by the plain CLI `now` path.
pub(crate) fn render_now_with_alerts(
    summary: &NowSummary,
    alerts: &[Alert],
    options: RenderOptions,
) -> String {
    render_now_with_alerts_document(summary, alerts, options).render(options)
}

pub(crate) fn render_trends_document(
    summary: &TrendsSummary,
    options: RenderOptions,
) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_trends_plain_document(summary),
        RenderMode::Braille | RenderMode::Ascii => render_trends_visual_document(summary, options),
    }
}

#[cfg(test)]
pub(crate) fn render_providers(
    capabilities: &[ProviderCapabilityView],
    statuses: &[ProviderStatus],
    options: RenderOptions,
) -> String {
    render_providers_document(capabilities, statuses, options).render(options)
}

/// The Providers tab (T11): per provider, each data lane's declared source (§2b
/// `Capability`), how it authenticates, the quota windows it can report, and its detection
/// health — i.e. *what is available, what is unavailable, and why*. The first production
/// consumer of the `Capability` descriptor. Honest by construction: a lane with no clean
/// source renders "no sanctioned source", never a fabricated one.
///
/// The connect-gated connection lane (your own usage-API keys) is appended separately by
/// [`push_provider_connection_lane`] under `--features connect`; the default build renders
/// the local `Capability`/`ProviderStatus` alone.
pub(crate) fn render_providers_document(
    capabilities: &[ProviderCapabilityView],
    statuses: &[ProviderStatus],
    options: RenderOptions,
) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_providers_plain_document(capabilities, statuses),
        RenderMode::Braille | RenderMode::Ascii => {
            render_providers_visual_document(capabilities, statuses, options)
        }
    }
}

fn render_providers_visual_document(
    capabilities: &[ProviderCapabilityView],
    statuses: &[ProviderStatus],
    options: RenderOptions,
) -> StyledDocument {
    let mut out = StyledDocument::new();
    let mut header = StyledLine::new();
    header.push_plain(format!("{} costroid", mark(options)));
    header.push_styled("  providers", SemanticStyle::Strong);
    out.push(header);

    if capabilities.is_empty() {
        push_rule(&mut out, options);
        push_line(&mut out, "no providers to describe");
        return out;
    }

    for capability in capabilities {
        push_rule(&mut out, options);
        let status = find_status(statuses, capability.provider);
        let mut head = StyledLine::new();
        head.push_styled(provider_name(capability.provider), SemanticStyle::Strong);
        head.push_plain(format!(" ({})", provider_state_word(status)));
        out.push(head);
        push_line(
            &mut out,
            &format!("  api cost   {}", data_source_phrase(capability.api_cost)),
        );
        push_line(
            &mut out,
            &format!("  quota      {}", quota_phrase(capability)),
        );
        push_line(
            &mut out,
            &format!("  model mix  {}", data_source_phrase(capability.model_mix)),
        );
        push_line(
            &mut out,
            &format!("  auth       {}", auth_phrase(capability.auth)),
        );
        if let Some(note) = status.and_then(|status| status.message.as_deref()) {
            push_line(&mut out, &format!("  note: {note}"));
        }
    }
    out
}

fn render_providers_plain_document(
    capabilities: &[ProviderCapabilityView],
    statuses: &[ProviderStatus],
) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid providers");
    if capabilities.is_empty() {
        push_line(&mut out, "no providers to describe");
        return out;
    }
    for capability in capabilities {
        let status = find_status(statuses, capability.provider);
        push_line(
            &mut out,
            &format!(
                "{} ({}):",
                provider_name(capability.provider),
                provider_state_word(status)
            ),
        );
        push_line(
            &mut out,
            &format!("  api cost: {}", data_source_phrase(capability.api_cost)),
        );
        push_line(&mut out, &format!("  quota: {}", quota_phrase(capability)));
        push_line(
            &mut out,
            &format!("  model mix: {}", data_source_phrase(capability.model_mix)),
        );
        push_line(
            &mut out,
            &format!("  auth: {}", auth_phrase(capability.auth)),
        );
        if let Some(note) = status.and_then(|status| status.message.as_deref()) {
            push_line(&mut out, &format!("  note: {note}"));
        }
    }
    out
}

fn find_status(statuses: &[ProviderStatus], provider: ProviderId) -> Option<&ProviderStatus> {
    statuses.iter().find(|status| status.provider == provider)
}

/// The detection-health word for a provider, joining its `ProviderStatus` (if collected)
/// to its capability. A provider with no status row (never collected) reads "not detected"
/// rather than a fabricated state.
fn provider_state_word(status: Option<&ProviderStatus>) -> &'static str {
    match status {
        Some(status) => provider_status(status.status),
        None => "not detected",
    }
}

/// Author-written human copy for a [`DataSource`] (T11 card). Pure ASCII so the Providers
/// tab renders identically in `--plain`; phrased to match `cursor_detected_message`
/// ("no sanctioned source").
fn data_source_phrase(source: DataSource) -> &'static str {
    match source {
        DataSource::LocalArtifact => "from local logs",
        DataSource::SanctionedHook => "from the statusLine capture; run setup-statusline",
        // Tiers 2-3 of the auth ladder both surface as the user's connected credential.
        DataSource::SanctionedOauth | DataSource::ApiKey => "via your connected key",
        DataSource::Unavailable => "no sanctioned source",
    }
}

/// Author-written human copy for an [`AuthMethod`] (T11 card). Pure ASCII.
fn auth_phrase(auth: AuthMethod) -> &'static str {
    match auth {
        AuthMethod::None => "no login required",
        AuthMethod::Oauth => "sanctioned OAuth",
        AuthMethod::ApiKey => "your own API key",
    }
}

/// The quota line: the subscription-quota source plus the windows the provider can report.
/// An empty `quota_kinds` carries no window suffix (e.g. Cursor, which keeps no local quota
/// window), so the source phrase ("no sanctioned source") stands alone.
fn quota_phrase(capability: &ProviderCapabilityView) -> String {
    let source = data_source_phrase(capability.subscription_quota);
    if capability.quota_kinds.is_empty() {
        source.to_string()
    } else {
        let kinds = capability
            .quota_kinds
            .iter()
            .map(|kind| limit_kind(*kind))
            .collect::<Vec<_>>()
            .join(", ");
        format!("{source} ({kinds})")
    }
}

/// A single billing-vendor's connection state for the Providers tab's connection lane,
/// gathered read-only over the existing keychain/registry (no network). Carries only the
/// non-secret org label — NEVER key material. Connect-gated: the default build never
/// compiles it, so it links no `costroid-connect` symbols.
#[cfg(feature = "connect")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConnectionEntry {
    pub(crate) vendor: String,
    pub(crate) state: ConnectionState,
}

#[cfg(feature = "connect")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ConnectionState {
    /// Linked: the key is present in the OS keychain AND the registry marks it connected
    /// (the dual gate). `org` is the non-secret organization label, if captured.
    Connected {
        org: Option<String>,
    },
    NotConnected,
    /// No sanctioned source (e.g. Gemini): carries the pinned unavailable message verbatim.
    Unavailable(String),
}

/// Append the connect-gated connection lane (your own usage-API keys) to the Providers tab.
/// Called only under `--features connect`; renders the org label + connected/not state,
/// NEVER key material. Pure ASCII in `--plain`/Ascii (the pinned Gemini message and any
/// server-supplied org label are folded via [`fold_for_ascii`]); the em-dash is kept only
/// on a UTF-8 (Braille) TTY.
#[cfg(feature = "connect")]
pub(crate) fn push_provider_connection_lane(
    out: &mut StyledDocument,
    connections: &[ConnectionEntry],
    options: RenderOptions,
) {
    if connections.is_empty() {
        return;
    }
    // Plain mode delimits sections by labels alone (no rules), like the other plain docs;
    // the visual modes get the horizontal rule.
    if options.mode != RenderMode::Plain {
        push_rule(out, options);
    }
    push_line(out, "connections (your own usage API keys)");
    let dash = if options.mode == RenderMode::Braille {
        ""
    } else {
        "-"
    };
    for entry in connections {
        let detail = match &entry.state {
            ConnectionState::Connected { org: Some(org) } => {
                format!("connected {dash} organization {org}")
            }
            ConnectionState::Connected { org: None } => "connected".to_string(),
            ConnectionState::NotConnected => "not connected".to_string(),
            ConnectionState::Unavailable(message) => message.clone(),
        };
        push_line(
            out,
            &fold_for_ascii(&format!("  {:<10} {detail}", entry.vendor), options),
        );
    }
}

/// Strip control characters always, and for `--plain`/Ascii fold the known glyphs (em-dash,
/// ellipsis) and map any remaining non-ASCII to `?` — mirroring the connect command's
/// `emit`, so the connection lane is guaranteed pure ASCII there regardless of a
/// server-supplied org label. Braille keeps printable Unicode.
#[cfg(feature = "connect")]
fn fold_for_ascii(value: &str, options: RenderOptions) -> String {
    let sanitized: String = value.chars().filter(|ch| !ch.is_control()).collect();
    match options.mode {
        RenderMode::Braille => sanitized,
        RenderMode::Ascii | RenderMode::Plain => sanitized
            .replace('', "-")
            .replace('', "...")
            .chars()
            .map(|ch| if ch.is_ascii() { ch } else { '?' })
            .collect(),
    }
}

// ---------------------------------------------------------------------------
// Models tab (T12) — `costroid` TUI tab `4`. Per API-billed model, the spend + token mix
// (the now/trends-consistent `CostLaneSummary` numbers) fused with the bench/frontier overlay
// (cost-vs-quality standing + equal-volume re-pricing). API-cost rows ONLY (the frontier is
// API-only, ARCHITECTURE §9.6). Monochrome (Strong/bold spend only; amber/red reserved for
// the near-limit state). A model with no bundled-benchmark appearance renders "not
// benchmarked" — a GAP, never a guessed standing. Local figures are always estimates (the `~`
// hedge). Mirrors the `render_providers_*` split; plain delimits by labels, never the `─` rule
// (T11's gotcha).
// ---------------------------------------------------------------------------

#[cfg(test)]
pub(crate) fn render_models(view: &ModelsView, options: RenderOptions) -> String {
    render_models_document(view, options).render(options)
}

pub(crate) fn render_models_document(view: &ModelsView, options: RenderOptions) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_models_plain_document(view),
        RenderMode::Braille | RenderMode::Ascii => render_models_visual_document(view, options),
    }
}

fn render_models_visual_document(view: &ModelsView, options: RenderOptions) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_header_line(
        &mut out,
        mark(options),
        "models",
        format_money(&total_models_spend(view), Some("USD"), true),
        options,
    );
    // Scope label (mirrors Now's "period:" line): Models is lifetime-scoped, so it can differ
    // from the period-scoped Now tab — say so on screen.
    push_line(&mut out, "scope: all usage (all time)");
    if view.no_api_usage || view.models.is_empty() {
        push_rule(&mut out, options);
        push_line(&mut out, "no API-billed usage to compare");
    } else {
        for model in &view.models {
            push_rule(&mut out, options);
            out.push(model_spend_line(model));
            push_line(
                &mut out,
                &format!("  tokens: {}", format_token_mix(&model.totals.tokens)),
            );
            push_line(
                &mut out,
                &format!(
                    "  frontier: {}",
                    model_standing_phrase(model.overlay.as_ref())
                ),
            );
            if let Some(phrase) = model_repricing_phrase(model.overlay.as_ref()) {
                push_line(&mut out, &format!("  {phrase}"));
            }
        }
    }
    push_rule(&mut out, options);
    push_models_disclaimer(&mut out, view);
    push_provider_notes(&mut out, &view.providers);
    push_empty_provider_guidance(&mut out, &view.providers);
    out
}

fn render_models_plain_document(view: &ModelsView) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid models");
    // Scope label (mirrors Now's "period:" line): lifetime-scoped, unlike the Now tab.
    push_line(&mut out, "scope: all usage (all time)");
    if view.no_api_usage || view.models.is_empty() {
        push_line(&mut out, "no API-billed usage to compare");
    } else {
        for model in &view.models {
            push_line(&mut out, &plain_model_line(model));
            push_line(
                &mut out,
                &format!("  tokens: {}", format_token_mix(&model.totals.tokens)),
            );
            push_line(
                &mut out,
                &format!(
                    "  frontier: {}",
                    model_standing_phrase(model.overlay.as_ref())
                ),
            );
            if let Some(phrase) = model_repricing_phrase(model.overlay.as_ref()) {
                push_line(&mut out, &format!("  {phrase}"));
            }
        }
    }
    push_models_disclaimer(&mut out, view);
    push_provider_notes(&mut out, &view.providers);
    push_empty_provider_guidance(&mut out, &view.providers);
    out
}

fn total_models_spend(view: &ModelsView) -> Decimal {
    view.models.iter().fold(Decimal::ZERO, |total, model| {
        total + model.totals.billed_cost
    })
}

/// The visual per-model spend line: name (bold) + the always-estimated (`~`) spend (bold) +
/// the honest pricing-coverage badge (e.g. "(partial pricing)") when some rows were unpriced.
fn model_spend_line(model: &ModelRow) -> StyledLine {
    let mut line = StyledLine::new();
    line.push_styled(model.model.clone(), SemanticStyle::Strong);
    line.push_plain("  spent ".to_string());
    line.push_styled(
        format_money(
            &model.totals.billed_cost,
            model.totals.currency.as_deref(),
            true,
        ),
        SemanticStyle::Strong,
    );
    let badge = pricing_badge_plain(&model.totals);
    if !badge.is_empty() {
        line.push_plain(format!(" ({})", badge.trim_start_matches(", ")));
    }
    line
}

fn plain_model_line(model: &ModelRow) -> String {
    let mut line = format!(
        "{}: spent {}",
        model.model,
        format_money(
            &model.totals.billed_cost,
            model.totals.currency.as_deref(),
            true
        )
    );
    let badge = pricing_badge_plain(&model.totals);
    if !badge.is_empty() {
        line.push_str(&format!(" ({})", badge.trim_start_matches(", ")));
    }
    line
}

/// The token mix for a model: input / output / cache (read+write summed). Pure ASCII
/// (thousands-grouped), so it renders identically in `--plain`.
fn format_token_mix(tokens: &TokenTotals) -> String {
    format!(
        "{} in / {} out / {} cache",
        with_thousands(&tokens.input.to_string()),
        with_thousands(&tokens.output.to_string()),
        with_thousands(&(tokens.cache_read + tokens.cache_write).to_string()),
    )
}

/// A compact frontier-standing summary across a model's bench appearances. No overlay, or a
/// matched overlay with empty `appearances`, => "not benchmarked" — a GAP, never a fabricated
/// standing. Pure ASCII (benchmark names + model ids are ASCII catalog data).
fn model_standing_phrase(overlay: Option<&OverlayModel>) -> String {
    match overlay {
        Some(model) if !model.appearances.is_empty() => model
            .appearances
            .iter()
            .map(|appearance| {
                format!(
                    "{} {}% - {}",
                    appearance.benchmark_name,
                    appearance.score_pct.normalize(),
                    frontier_standing_text(&appearance.standing)
                )
            })
            .collect::<Vec<_>>()
            .join("; "),
        _ => "not benchmarked".to_string(),
    }
}

/// The most-favorable equal-volume re-pricing phrase, if any — reuses the frontier's
/// `best_delta`/`delta_phrase` (cost-only; INFORM never PRESCRIBE; pure ASCII). `None` when
/// there is no computed comparison (un-benchmarked, a rate gap, or an unpriced baseline).
fn model_repricing_phrase(overlay: Option<&OverlayModel>) -> Option<String> {
    let delta = best_delta(overlay?)?;
    let phrase = delta_phrase(delta);
    if phrase.is_empty() {
        None
    } else {
        Some(phrase.trim_start_matches("; ").to_string())
    }
}

fn push_models_disclaimer(out: &mut StyledDocument, view: &ModelsView) {
    push_line(
        out,
        &format!(
            "{} (pricing as of {})",
            view.disclaimer.note, view.disclaimer.pricing_as_of
        ),
    );
}

// ---------------------------------------------------------------------------
// History tab (T13) — `costroid` TUI tab `5`. The full per-turn record: each FOCUS meter
// row's time, model, token usage, access path, and (for API rows) the always-estimated cost.
// Usage is read from `x_ConsumedTokens` — the raw count that stays populated even when FOCUS
// nulls `ConsumedQuantity` on an unpriced row — NEVER `ConsumedQuantity` alone, so no usage is
// dropped. Newest-first and scrollable (the TUI's first viewport state lives in tui.rs).
// Informational, so monochrome (Strong/bold model only; amber/red reserved for the near-limit
// state). The unchanged `costroid export` command is surfaced for the COMPLETE FOCUS 1.3 record
// (every column, every row) — the tab is a readable view, not a replacement. Mirrors the
// `render_models_*` split; plain delimits by labels, never the `─` rule (T11's gotcha).
// ---------------------------------------------------------------------------

/// The pointer to the unchanged `costroid export` command. The tab is a readable list; the
/// full FOCUS 1.3 record (all columns, all rows) comes from the export. Pure ASCII.
const HISTORY_EXPORT_HINT: &str =
    "export: costroid export --format json|csv  (full FOCUS 1.3 record)";

#[cfg(test)]
pub(crate) fn render_history(rows: &[FocusRecord], options: RenderOptions) -> String {
    render_history_document(rows, options).render(options)
}

pub(crate) fn render_history_document(
    rows: &[FocusRecord],
    options: RenderOptions,
) -> StyledDocument {
    // Newest-first by charge-period start; reference-only ordering, no record clone. A stable
    // sort keeps same-timestamp meter rows (e.g. a turn's input + output) in their source order.
    let mut ordered: Vec<&FocusRecord> = rows.iter().collect();
    ordered.sort_by_key(|record| std::cmp::Reverse(record.charge_period_start));
    match options.mode {
        RenderMode::Plain => render_history_plain_document(&ordered),
        RenderMode::Braille | RenderMode::Ascii => {
            render_history_visual_document(&ordered, options)
        }
    }
}

fn render_history_visual_document(rows: &[&FocusRecord], options: RenderOptions) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_header_line(
        &mut out,
        mark(options),
        "history",
        format_money(&history_api_spend(rows), Some("USD"), true),
        options,
    );
    push_line(&mut out, &history_scope_line(rows.len()));
    push_line(&mut out, HISTORY_EXPORT_HINT);
    push_rule(&mut out, options);
    if rows.is_empty() {
        push_line(&mut out, "no usage recorded yet");
    } else {
        for record in rows {
            out.push(history_row_line(record));
        }
    }
    out
}

fn render_history_plain_document(rows: &[&FocusRecord]) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid history");
    push_line(&mut out, &history_scope_line(rows.len()));
    push_line(&mut out, HISTORY_EXPORT_HINT);
    if rows.is_empty() {
        push_line(&mut out, "no usage recorded yet");
    } else {
        for record in rows {
            push_line(&mut out, &plain_history_row(record));
        }
    }
    out
}

/// The header figure: the always-estimated API-lane cost across the shown rows. Subscription
/// turns are a flat-fee plan, not a per-token bill (golden rule: limits are not summable
/// dollars), so only API rows contribute — matching the now/trends API total.
fn history_api_spend(rows: &[&FocusRecord]) -> Decimal {
    rows.iter()
        .filter(|record| record.x_access_path == "api")
        .fold(Decimal::ZERO, |total, record| total + record.billed_cost)
}

fn history_scope_line(count: usize) -> String {
    let noun = if count == 1 { "record" } else { "records" };
    format!("scope: {count} {noun}, newest first (all time)")
}

/// `YYYY-MM-DD HH:MM` in UTC (the FOCUS charge period is UTC) — a stable, pure-ASCII stamp.
fn history_time(record: &FocusRecord) -> String {
    record
        .charge_period_start
        .format("%Y-%m-%d %H:%M")
        .to_string()
}

/// The raw token usage for this meter row, read from `x_ConsumedTokens` (always populated, even
/// when FOCUS nulls `ConsumedQuantity` on an unpriced row) — NEVER `ConsumedQuantity` alone.
fn history_tokens(record: &FocusRecord) -> String {
    format!(
        "{} {}",
        with_thousands(&record.x_consumed_tokens.trunc().to_string()),
        record.x_token_type
    )
}

/// The trailing per-row detail: token usage + access path, with the always-estimated (`~`) cost
/// for API rows only (a subscription turn carries no per-token bill). Pure ASCII.
fn history_detail(record: &FocusRecord) -> String {
    let mut detail = format!("{}  {}", history_tokens(record), record.x_access_path);
    if record.x_access_path == "api" {
        detail.push_str(&format!(
            "  {}",
            format_money(
                &record.billed_cost,
                Some(record.billing_currency.as_str()),
                true
            )
        ));
    }
    detail
}

/// The visual per-record line: time, the model (bold — an allowed monochrome cue), then the
/// usage / access-path / cost detail.
fn history_row_line(record: &FocusRecord) -> StyledLine {
    let mut line = StyledLine::new();
    line.push_plain(format!("{}  ", history_time(record)));
    line.push_styled(record.x_model.clone(), SemanticStyle::Strong);
    line.push_plain(format!("  {}", history_detail(record)));
    line
}

fn plain_history_row(record: &FocusRecord) -> String {
    format!(
        "{}  {}  {}",
        history_time(record),
        record.x_model,
        history_detail(record)
    )
}

// ---------------------------------------------------------------------------
// Budget tab (T14) — `costroid` TUI tab `6`. Compare the user's monthly $ target(s) (read from
// the config TOML, API-lane only) against ACTUAL API-lane spend this month — the local estimate
// (always `~`-hedged; `costroid reconcile` is the invoice-true surface). A fill bar + pace cue +
// an honest over-budget state. This is the ONE tab where amber/red is allowed — but ONLY paired
// with a non-color textual cue (`!`/`!!`/`OVER`, spelled out in `--plain`). A flat-fee
// subscription never gets a $ comparison (§170); the empty state points at the config file.
// Mirrors the `render_models_*` split; plain delimits by labels, never the `─` rule (T11 gotcha).
// ---------------------------------------------------------------------------

/// The config-file hint shown when no budget is set, and in the over/near cues. Pure ASCII
/// (the documented path; the resolver may honor `$XDG_CONFIG_HOME`, but the hint uses the
/// canonical location).
const BUDGET_CONFIG_HINT: &str = "no budget set - set targets in ~/.config/costroid/config.toml";
/// The standing reminder that the figures are local estimates, not the invoice. Pure ASCII.
const BUDGET_ESTIMATE_NOTE: &str = "figures are local estimates (your tokens x current prices); \
     run `costroid reconcile` to compare against the provider invoice.";

#[cfg(test)]
pub(crate) fn render_budget(view: &BudgetView, options: RenderOptions) -> String {
    render_budget_document(view, options).render(options)
}

pub(crate) fn render_budget_document(view: &BudgetView, options: RenderOptions) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_budget_plain_document(view),
        RenderMode::Braille | RenderMode::Ascii => render_budget_visual_document(view, options),
    }
}

fn render_budget_visual_document(view: &BudgetView, options: RenderOptions) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_header_line(
        &mut out,
        mark(options),
        "budget",
        format_money(&view.spent_total_usd, Some("USD"), true),
        options,
    );
    push_line(&mut out, &budget_scope_line(view));
    if view.no_budget_set {
        push_rule(&mut out, options);
        push_budget_empty_state(&mut out);
        return out;
    }
    let mut any = false;
    for row in &view.rows {
        push_rule(&mut out, options);
        out.push(budget_row_meter_line(row, options));
        push_line(&mut out, &format!("  {}", budget_pace_line(row, view)));
        if let Some(over) = &row.over_by_usd {
            push_line(&mut out, &format!("  over by {}", format_over_by(over)));
        }
        any = true;
    }
    if !view.excluded_tools.is_empty() {
        push_rule(&mut out, options);
        for excluded in &view.excluded_tools {
            push_line(&mut out, &budget_excluded_line(excluded));
        }
        any = true;
    }
    if !any {
        push_rule(&mut out, options);
        push_line(&mut out, BUDGET_NO_USABLE_TARGETS);
    }
    push_rule(&mut out, options);
    push_line(&mut out, BUDGET_ESTIMATE_NOTE);
    out
}

fn render_budget_plain_document(view: &BudgetView) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid budget");
    push_line(&mut out, &budget_scope_line(view));
    if view.no_budget_set {
        push_budget_empty_state(&mut out);
        return out;
    }
    let mut any = false;
    for row in &view.rows {
        push_line(&mut out, &plain_budget_row(row));
        push_line(&mut out, &format!("  {}", budget_pace_line(row, view)));
        any = true;
    }
    for excluded in &view.excluded_tools {
        push_line(&mut out, &budget_excluded_line(excluded));
        any = true;
    }
    if !any {
        push_line(&mut out, BUDGET_NO_USABLE_TARGETS);
    }
    push_line(&mut out, BUDGET_ESTIMATE_NOTE);
    out
}

const BUDGET_NO_USABLE_TARGETS: &str =
    "no usable budget targets - check ~/.config/costroid/config.toml";

/// The on-screen scope label: what spend is being compared (API-lane, this month) and how far
/// through the month we are — the pace reference. Mirrors Now's `period:` line.
fn budget_scope_line(view: &BudgetView) -> String {
    format!(
        "scope: API-lane spend this month ({} of month elapsed)",
        percent(view.month_elapsed_fraction)
    )
}

/// The visual per-budget line: scope (bold) + spent/target (always `~`-estimated) + a
/// state-colored fill meter + the percent and the non-color state cue (`!`/`!!`/`OVER`). The
/// meter clamps to 100%, so an over-budget bar reads full — the spelled-out cue carries the
/// over-state that color/length cannot.
fn budget_row_meter_line(row: &BudgetRow, options: RenderOptions) -> StyledLine {
    let state = budget_state(row);
    let mut line = StyledLine::new();
    line.push_styled(budget_scope_label(&row.scope), SemanticStyle::Strong);
    line.push_plain(format!(
        "  {} / {}  ",
        format_money(&row.spent_usd, Some("USD"), true),
        format_money(&row.target_usd, Some("USD"), true),
    ));
    // The fill bar is colored by the SAME state the cue uses (one source of truth), so the bar,
    // the percent, and the spelled-out cue can never disagree at a boundary.
    line.spans.push(StyledSpan::styled(
        positional_meter_text(row.fraction, LIMIT_BAR_WIDTH, options),
        state_style(state),
    ));
    // Percent + the non-color cue, colored by state so a near-/over-budget number reads amber/red
    // — but the `!`/`!!`/`OVER` text means color is never the only signal.
    line.push_styled(
        format!(" {}{}", percent(row.fraction), state_cue(state)),
        state_style(state),
    );
    line
}

/// The display state of a budget row, derived from the core's HONEST fields so the cue, the
/// `over by` figure, and the pace always agree. Crucially, "over" is keyed on
/// `over_by_usd.is_some()` (core's STRICT `spent > target`), NOT on `limit_state`'s
/// `fraction >= 1.0` — so a row at exactly 100% reads "at budget" (Critical), never "OVER, over
/// by $0.00". (`limit_state` stays `>= 1.0`-over for the live-quota meters, where an exhausted
/// quota IS over; budgets want the strict boundary.)
fn budget_state(row: &BudgetRow) -> LimitState {
    if row.over_by_usd.is_some() {
        LimitState::Over
    } else if row.fraction >= CRITICAL_FRACTION {
        LimitState::Critical
    } else if row.fraction >= WARN_FRACTION {
        LimitState::Warn
    } else {
        LimitState::Normal
    }
}

/// The plain (screen-reader) per-budget line: `<scope>: ~$X / ~$Y budget (NN%)<cue>`, where the
/// cue spells out the near/at/over state in pure ASCII (and, when over, the dollar overshoot) —
/// no color, no glyphs. Matches the card's `$X / $Y budget (over by $Z)` contract.
fn plain_budget_row(row: &BudgetRow) -> String {
    format!(
        "{}: {} / {} budget ({}){}",
        budget_scope_label(&row.scope),
        format_money(&row.spent_usd, Some("USD"), true),
        format_money(&row.target_usd, Some("USD"), true),
        percent(row.fraction),
        budget_plain_suffix(row),
    )
}

/// Format a strictly-positive budget overshoot, guarding the sub-cent case so a real overshoot
/// never renders as the self-contradictory `~$0.00`. `over` is core's strict `spent > target`,
/// so it is always > 0; when it rounds below a cent (what `format_money` would show as `~$0.00`),
/// render `<$0.01` instead — still an honest "less than a cent over budget".
fn format_over_by(over: &Decimal) -> String {
    if over.round_dp(2) == Decimal::ZERO {
        "<$0.01".to_string()
    } else {
        format_money(over, Some("USD"), true)
    }
}

/// The pure-ASCII state suffix for a plain budget line: empty when comfortably under, the
/// spelled-out `!`/`!!` near/at cue otherwise, and `!! OVER, over by ~$Z` once STRICTLY over
/// budget. Uses the same [`budget_state`] as the visual line, so exactly-100% reads "at budget".
fn budget_plain_suffix(row: &BudgetRow) -> String {
    match budget_state(row) {
        LimitState::Normal => String::new(),
        LimitState::Warn => " ! near budget".to_string(),
        LimitState::Critical => " !! at budget".to_string(),
        // Over implies `over_by_usd.is_some()` by construction (see `budget_state`), so the
        // overshoot is always real here — the `unwrap_or` is a defensive floor, never hit.
        LimitState::Over => format!(
            " !! OVER, over by {}",
            format_over_by(&row.over_by_usd.unwrap_or(Decimal::ZERO))
        ),
    }
}

fn budget_pace_line(row: &BudgetRow, view: &BudgetView) -> String {
    format!(
        "pace: {} used vs {} of month elapsed ({})",
        percent(row.fraction),
        percent(view.month_elapsed_fraction),
        budget_pace_phrase(row.pace),
    )
}

fn budget_pace_phrase(pace: BudgetPace) -> &'static str {
    match pace {
        BudgetPace::OnTrack => "on track",
        BudgetPace::AheadOfPace => "ahead of pace",
        BudgetPace::OverBudget => "over budget",
    }
}

/// The label for a budget scope: the tool id, or "total (all tools)" for the overall cap. Tool
/// ids are ASCII catalog values, so this renders identically in `--plain`.
fn budget_scope_label(scope: &BudgetScope) -> String {
    match scope {
        BudgetScope::Total => "total (all tools)".to_string(),
        BudgetScope::Tool(tool) => tool.clone(),
    }
}

/// The honest note for a budgeted tool with no API lane (§170): no API bill to budget, so no $
/// comparison is shown. Distinguishes a flat-fee *subscription* (assertable) from a merely
/// *unclassified* install (no subscription claim). Pure ASCII.
fn budget_excluded_line(excluded: &BudgetExcludedTool) -> String {
    match excluded.reason {
        BudgetExclusion::FlatFeeSubscription => format!(
            "{}: flat-fee subscription - no $ budget applies (not API-billed)",
            excluded.tool
        ),
        BudgetExclusion::NotApiBilled => format!(
            "{}: no API-billed usage - a $ budget tracks API spend only",
            excluded.tool
        ),
    }
}

/// The empty state: point the user at the config file with a copy-paste-able schema. Pure ASCII
/// (no `─` rule, no glyphs), so it reads identically in `--plain`.
fn push_budget_empty_state(out: &mut StyledDocument) {
    push_line(out, BUDGET_CONFIG_HINT);
    push_line(out, "");
    push_line(out, "[budget]");
    push_line(out, "total_monthly_usd = 100.00");
    push_line(out, "");
    push_line(out, "[budget.per_tool]");
    push_line(out, "claude-code = 60.00");
    push_line(out, "codex = 40.00");
}

// ---------------------------------------------------------------------------
// Alerts (T17) — the inline `now` banner + the `costroid alerts` / `alerts --check` surface.
// Opt-in, default OFF. The detector (`costroid_core::active_alerts`) produces the data; THIS layer
// owns the copy. Quota alerts use quota-extension framing (NEVER money); budget alerts are dollars.
// Sentence case, no emoji, one crossing per line. Amber/red is ALLOWED for the crossing state (like
// Budget) but is NEVER alone — every styled line carries a `!`/`!!` (visual) or a spelled-out
// `(near limit)`/`(critical)`/`(over budget)` (plain) cue, so it survives `--plain`/`NO_COLOR`. The
// `alerts --check` line and every Plain byte are pure ASCII.
// ---------------------------------------------------------------------------

/// The one-line enable hint shown when the alerts feature is off. Pure ASCII (the canonical path;
/// the resolver may honor `$XDG_CONFIG_HOME`, but the hint uses the documented location — mirrors
/// [`BUDGET_CONFIG_HINT`]).
const ALERTS_OFF_HINT: &str = "alerts are off - enable them in ~/.config/costroid/config.toml";

/// The readable window phrase for a quota alert — quota-extension framing, never an abbreviation.
fn alert_window_phrase(kind: LimitKind) -> &'static str {
    match kind {
        LimitKind::FiveHour => "5-hour",
        LimitKind::Weekly => "weekly",
        LimitKind::Daily => "daily",
        LimitKind::Monthly => "monthly",
        LimitKind::BillingCycle => "billing-cycle",
    }
}

/// The budget scope phrase for a budget alert ($ framing).
fn alert_budget_scope(scope: &BudgetScope) -> String {
    match scope {
        BudgetScope::Total => "total budget".to_string(),
        BudgetScope::Tool(tool) => format!("{tool} budget"),
    }
}

/// One alert's human sentence WITHOUT a severity cue (the cue is appended per-mode). Quota copy is
/// quota-extension framing ("... limit at N%, resets in T") — NEVER money; budget copy is dollars,
/// always `~`-hedged (the figures are local estimates). Pure ASCII in ASCII/Plain modes.
fn alert_sentence(alert: &Alert) -> String {
    match alert {
        Alert::Quota {
            tool,
            kind,
            fraction,
            reset_in_seconds,
            ..
        } => format!(
            "{} {} limit at {}, resets in {}",
            provider_name(*tool),
            alert_window_phrase(*kind),
            percent(*fraction),
            reset_countdown(*reset_in_seconds),
        ),
        Alert::Budget {
            scope,
            spent_usd,
            target_usd,
            over_by_usd,
        } => format!(
            "{} over by {}, spent {} of {}",
            alert_budget_scope(scope),
            format_over_by(over_by_usd),
            format_money(spent_usd, Some("USD"), true),
            format_money(target_usd, Some("USD"), true),
        ),
        // Advisory (T17b): a projection, framed as such — never asserted as a present overrun.
        Alert::Forecast {
            projected_month_usd,
            target_usd,
            projected_over_by_usd,
        } => format!(
            "total budget projected over by {}, {} projected of {}",
            format_over_by(projected_over_by_usd),
            format_money(projected_month_usd, Some("USD"), true),
            format_money(target_usd, Some("USD"), true),
        ),
        // Advisory (T17b): a spend spike vs the user's own norm. The "~Nx your $Y norm" multiple is
        // shown only when it reads honestly (mirrors the Anomalies tab); otherwise "well above".
        Alert::SpendSpike {
            date,
            value_usd,
            baseline_median_usd,
            magnitude,
        } => {
            let median_display = format_money(baseline_median_usd, Some("USD"), true);
            let baseline_displays_zero = baseline_median_usd.round_dp(2) == Decimal::ZERO;
            let comparison = match anomaly_multiple_phrase(*magnitude, baseline_displays_zero) {
                Some(multiple) => format!("~{multiple}x your {median_display} norm"),
                None => format!("well above your {median_display} norm"),
            };
            format!(
                "daily spend spike: {} on {}, {comparison}",
                format_money(value_usd, Some("USD"), true),
                date.format("%b %d"),
            )
        }
    }
}

/// The visual (braille/ascii) non-color cue: `!` for a WARN quota, `!!` for any critical-tier
/// crossing (a CRITICAL quota or an over-budget). `!!` carries the over-budget state without a
/// redundant "OVER" (the budget sentence already says "over by").
fn alert_cue(alert: &Alert) -> &'static str {
    if alert.is_critical() {
        " !!"
    } else {
        " !"
    }
}

/// The plain (screen-reader) spelled-out cue, one per severity/class. The two advisory sources
/// (T17b) carry their own heads-up cue, distinct from the hard quota/budget crossings.
fn alert_plain_cue(alert: &Alert) -> &'static str {
    match alert {
        Alert::Quota {
            level: AlertLevel::Warn,
            ..
        } => " (near limit)",
        Alert::Quota {
            level: AlertLevel::Critical,
            ..
        } => " (critical)",
        Alert::Budget { .. } => " (over budget)",
        Alert::Forecast { .. } => " (projected over budget)",
        Alert::SpendSpike { .. } => " (spend spike)",
    }
}

/// The semantic style of an alert line: amber (Warn) vs red (Critical / over-budget). Shares the
/// near-/over-limit palette the meter + Budget use (so the alert color matches the meter color).
fn alert_style(alert: &Alert) -> SemanticStyle {
    if alert.is_critical() {
        SemanticStyle::Critical
    } else {
        SemanticStyle::Warn
    }
}

/// Push one styled line per alert into `out`, mode-aware — the shared body of the inline banner
/// AND `costroid alerts`. Visual: an amber/red sentence + the `!`/`!!` cue; plain: an uncolored
/// sentence + the spelled-out cue.
fn push_alert_lines(out: &mut StyledDocument, alerts: &[Alert], options: RenderOptions) {
    for alert in alerts {
        let sentence = alert_sentence(alert);
        match options.mode {
            RenderMode::Plain => {
                push_line(out, &format!("  {sentence}{}", alert_plain_cue(alert)));
            }
            RenderMode::Braille | RenderMode::Ascii => {
                let mut line = StyledLine::new();
                line.push_plain("  ");
                line.push_styled(
                    format!("{sentence}{}", alert_cue(alert)),
                    alert_style(alert),
                );
                out.push(line);
            }
        }
    }
}

/// The inline alert banner shown ATOP the `now` view when alerts are enabled and at least one is
/// active (T17). No-op when `alerts` is empty (disabled OR clear). Amber/red is allowed (the
/// crossing state) but ALWAYS paired with a textual cue (`!`/`!!` visual, spelled-out plain), so it
/// survives `--plain`/`NO_COLOR`. A separating rule sits below it in the visual modes — Plain
/// delimits by the `alerts:` / `costroid now` labels, never the multi-byte `─` rule (T11 gotcha).
pub(crate) fn push_alert_banner(
    out: &mut StyledDocument,
    alerts: &[Alert],
    options: RenderOptions,
) {
    if alerts.is_empty() {
        return;
    }
    match options.mode {
        RenderMode::Plain => {
            push_line(out, "alerts:");
            push_alert_lines(out, alerts, options);
        }
        RenderMode::Braille | RenderMode::Ascii => {
            let mut header = StyledLine::new();
            header.push_plain(format!("{} ", mark(options)));
            header.push_styled("alerts", SemanticStyle::Strong);
            out.push(header);
            push_alert_lines(out, alerts, options);
            push_rule(out, options);
        }
    }
}

/// `costroid alerts` — the human list (header + one line per active crossing, or the honest "no
/// active alerts" clean state). The OFF state is [`render_alerts_off`]; the caller branches on the
/// config `enabled` flag first.
pub(crate) fn render_alerts(alerts: &[Alert], options: RenderOptions) -> String {
    let mut out = StyledDocument::new();
    push_alerts_header(&mut out, options);
    if alerts.is_empty() {
        push_line(&mut out, "no active alerts");
    } else {
        push_alert_lines(&mut out, alerts, options);
    }
    out.render(options)
}

/// `costroid alerts` when the feature is OFF (the default): the honest off state + the one-line
/// enable hint + a copy-paste `[alerts]` stanza. Pure ASCII.
pub(crate) fn render_alerts_off(options: RenderOptions) -> String {
    let mut out = StyledDocument::new();
    push_alerts_header(&mut out, options);
    push_line(&mut out, ALERTS_OFF_HINT);
    push_line(&mut out, "");
    push_line(&mut out, "[alerts]");
    push_line(&mut out, "enabled = true");
    out.render(options)
}

fn push_alerts_header(out: &mut StyledDocument, options: RenderOptions) {
    match options.mode {
        RenderMode::Plain => push_line(out, "costroid alerts"),
        RenderMode::Braille | RenderMode::Ascii => {
            let mut header = StyledLine::new();
            header.push_plain(format!("{} costroid", mark(options)));
            header.push_styled("  alerts", SemanticStyle::Strong);
            out.push(header);
        }
    }
}

/// The single cron-friendly line for `alerts --check`. Always pure ASCII, no color — a cron log or
/// pipe target. One alert → its sentence; several → a count + the most-pressing headline (the
/// detector already orders critical-tier first). An empty slice yields `""` (the caller never
/// prints it — a clear run is silent).
pub(crate) fn alert_check_line(alerts: &[Alert]) -> String {
    match alerts.first() {
        None => String::new(),
        Some(headline) if alerts.len() == 1 => format!("costroid: {}", alert_sentence(headline)),
        Some(headline) => format!(
            "costroid: {} active alerts; most pressing: {}",
            alerts.len(),
            alert_sentence(headline),
        ),
    }
}

/// The `alerts --check` exit code: `0` when clear (no active alert), `1` when any crossing fired —
/// the cron contract. (A config / collect error is the caller's separate, distinct non-`1` code.)
pub(crate) fn alerts_check_exit_code(alerts: &[Alert]) -> i32 {
    if alerts.is_empty() {
        0
    } else {
        1
    }
}

// ---------------------------------------------------------------------------
// Forecast tab (T15) — `costroid` TUI tab `7`. Project this month's API-lane $ spend (a linear
// run-rate over the elapsed UTC month) + per-quota-window exhaustion ETAs (a linear burn off the
// fresh token-fraction reading), every figure a labeled estimate. An ADVISORY tab: monochrome
// (amber/red is reserved for the near-limit/over-budget meter state, which the forecast has none
// of — it is advisory text + a sparkline). The quota ETA degrades to "unavailable" on any
// reading that is not a fresh, cross-checked `Available` token-fraction — never a confident wrong
// ETA. Mirrors the `render_budget_*` split; plain delimits by labels, never the `─` rule (T11
// gotcha).
// ---------------------------------------------------------------------------

/// The standing reminder that the forecast figures are local estimates, not the invoice. ASCII.
const FORECAST_ESTIMATE_NOTE: &str =
    "figures are local estimates (your tokens x current prices), projected - not the vendor invoice.";
/// The label width that aligns the `actual` / `projected` sparkline rows.
const FORECAST_SERIES_LABEL_WIDTH: usize = 10;

#[cfg(test)]
pub(crate) fn render_forecast(view: &ForecastView, options: RenderOptions) -> String {
    render_forecast_document(view, options).render(options)
}

pub(crate) fn render_forecast_document(
    view: &ForecastView,
    options: RenderOptions,
) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_forecast_plain_document(view),
        RenderMode::Braille | RenderMode::Ascii => render_forecast_visual_document(view, options),
    }
}

fn render_forecast_visual_document(view: &ForecastView, options: RenderOptions) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_header_line(
        &mut out,
        mark(options),
        "forecast",
        forecast_header_money(view)
            .map(|money| format_money(&money, Some("USD"), true))
            .unwrap_or_default(),
        options,
    );
    push_line(&mut out, FORECAST_SCOPE_LINE);
    if view.no_api_usage {
        push_line(&mut out, FORECAST_NO_USAGE);
    } else {
        for line in forecast_spend_lines(view) {
            push_line(&mut out, &line);
        }
        // The actual-vs-projected sparkline (visual only): actual daily spend (one cell per
        // elapsed day), then the flat projected run-rate for the remaining days, distinguished by
        // glyph — never color.
        if let Some((actual, projected)) = forecast_series_glyphs(view, options) {
            push_rule(&mut out, options);
            push_line(
                &mut out,
                &format!(
                    "{:<width$}{actual}",
                    "actual",
                    width = FORECAST_SERIES_LABEL_WIDTH
                ),
            );
            if let Some(projected) = projected {
                push_line(
                    &mut out,
                    &format!(
                        "{:<width$}{projected}",
                        "projected",
                        width = FORECAST_SERIES_LABEL_WIDTH
                    ),
                );
            }
        }
    }
    push_rule(&mut out, options);
    push_forecast_quota_section(&mut out, view);
    push_rule(&mut out, options);
    push_line(&mut out, FORECAST_ESTIMATE_NOTE);
    out
}

fn render_forecast_plain_document(view: &ForecastView) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid forecast");
    push_line(&mut out, FORECAST_SCOPE_LINE);
    if view.no_api_usage {
        push_line(&mut out, FORECAST_NO_USAGE);
    } else {
        for line in forecast_spend_lines(view) {
            push_line(&mut out, &line);
        }
    }
    push_forecast_quota_section(&mut out, view);
    push_line(&mut out, FORECAST_ESTIMATE_NOTE);
    out
}

const FORECAST_SCOPE_LINE: &str = "scope: API-lane spend this month + quota burn (estimated)";
const FORECAST_NO_USAGE: &str = "no API usage recorded - nothing to forecast yet";

/// The header figure: the projected month-end total when we can project, else the spend-to-date
/// (both always an estimate at the render layer). `None` when there is **no API usage at all** —
/// the header then carries no dollar figure, so the visual surface never renders a fabricated
/// `~$0.00` above the "nothing to forecast yet" body (the §12.21 never-fabricate-$0 empty-state
/// rule; the plain renderer already omits the header figure unconditionally).
fn forecast_header_money(view: &ForecastView) -> Option<Decimal> {
    if view.no_api_usage {
        return None;
    }
    Some(match &view.spend {
        SpendForecast::Projected {
            projected_month_usd,
            ..
        } => *projected_month_usd,
        SpendForecast::InsufficientData {
            spend_to_date_usd, ..
        } => *spend_to_date_usd,
    })
}

/// The two text spend lines (projected / spend-so-far, or the honest below-floor state), the
/// `--plain`-surviving actual-vs-projected distinction. Always `~`-hedged + `(estimated)`-tagged.
fn forecast_spend_lines(view: &ForecastView) -> Vec<String> {
    match &view.spend {
        SpendForecast::Projected {
            projected_month_usd,
            spend_to_date_usd,
            days_elapsed,
            days_in_month,
        } => vec![
            format!(
                "projected {} by {} (estimated)",
                format_money(projected_month_usd, Some("USD"), true),
                forecast_month_end_label(view.generated_at, *days_in_month),
            ),
            format!(
                "spend so far {} over {} of {} days (estimated)",
                format_money(spend_to_date_usd, Some("USD"), true),
                days_elapsed,
                days_in_month,
            ),
        ],
        SpendForecast::InsufficientData {
            spend_to_date_usd,
            days_elapsed,
            days_in_month,
            min_days,
        } => vec![
            format!(
                "insufficient data to project - {} of {} days elapsed (need {}+) (estimated)",
                days_elapsed, days_in_month, min_days,
            ),
            format!(
                "spend so far {} over {} of {} days (estimated)",
                format_money(spend_to_date_usd, Some("USD"), true),
                days_elapsed,
                days_in_month,
            ),
        ],
    }
}

/// The last calendar day of the projection's (UTC) month, e.g. `Jun 30`. Month-end days are
/// 28-31, so `%b %d` carries no leading-zero surprise; English `%b` is ASCII. Falls back to a
/// generic label (never a panic) on an impossible date.
fn forecast_month_end_label(generated_at: DateTime<Utc>, days_in_month: u32) -> String {
    let today = generated_at.date_naive();
    match chrono::NaiveDate::from_ymd_opt(today.year(), today.month(), days_in_month) {
        Some(end) => end.format("%b %d").to_string(),
        None => "month end".to_string(),
    }
}

/// Build the actual + projected sparkline glyph strings (visual modes only; `None` in Plain).
/// `actual` is one cell per elapsed day (zero-filled days included), self-normalized by the
/// existing [`sparkline`]; `projected` is a flat run of a distinct glyph for the remaining days —
/// present ONLY when we can project (the `Projected` state). The two glyph sets differ so actual
/// vs projected is told apart WITHOUT color.
fn forecast_series_glyphs(
    view: &ForecastView,
    options: RenderOptions,
) -> Option<(String, Option<String>)> {
    if options.mode == RenderMode::Plain {
        return None;
    }
    let (days_elapsed, days_in_month, projecting) = match &view.spend {
        SpendForecast::Projected {
            days_elapsed,
            days_in_month,
            ..
        } => (*days_elapsed, *days_in_month, true),
        SpendForecast::InsufficientData {
            days_elapsed,
            days_in_month,
            ..
        } => (*days_elapsed, *days_in_month, false),
    };
    let actual = sparkline(&forecast_actual_series(view, days_elapsed), options);
    let projected = if projecting {
        let remaining = days_in_month.saturating_sub(days_elapsed) as usize;
        Some(forecast_projected_glyphs(remaining, options))
    } else {
        None
    };
    Some((actual, projected))
}

/// A dense per-elapsed-day actual-spend series (one [`Decimal`] per day `1..=days_elapsed`,
/// zero-filled), placing each day's estimate at its day-of-month index — so `actual` + `projected`
/// together span the whole month.
fn forecast_actual_series(view: &ForecastView, days_elapsed: u32) -> Vec<Decimal> {
    let mut series = vec![Decimal::ZERO; days_elapsed as usize];
    for day in &view.daily_actuals {
        let index = day.date.day().saturating_sub(1) as usize;
        if index < series.len() {
            series[index] += day.spent_usd;
        }
    }
    series
}

/// The flat projected run-rate continuation as a distinct glyph run (a middle dashed braille
/// cell, or `~` in Ascii — never the actual bar glyphs, so actual vs projected reads by GLYPH not
/// color). Empty in Plain (handled upstream).
fn forecast_projected_glyphs(remaining: usize, options: RenderOptions) -> String {
    match options.mode {
        RenderMode::Plain => String::new(),
        RenderMode::Ascii => "~".repeat(remaining),
        RenderMode::Braille => braille_cell(&[4, 5]).to_string().repeat(remaining),
    }
}

/// The quota section: a `quota:` header, then one honest line per window — a projected hit
/// weekday, a "resets before you hit it", or a typed "ETA unavailable (reason)". Pure ASCII.
fn push_forecast_quota_section(out: &mut StyledDocument, view: &ForecastView) {
    if view.quota_etas.is_empty() {
        push_line(out, "quota: no quota windows tracked");
        return;
    }
    push_line(out, "quota:");
    for eta in &view.quota_etas {
        push_line(out, &forecast_quota_line(eta));
    }
}

/// One quota window's forecast line, e.g. `claude code weekly: projected to hit ~Friday
/// (UTC, estimated)`. The hit weekday is formatted in UTC and **labeled `UTC`** — the instant is
/// deterministic (the freshness-stamp convention) and the explicit marker keeps a near-midnight
/// projection from silently naming the wrong local weekday for an off-UTC user; the unavailable
/// arms name the typed reason.
fn forecast_quota_line(eta: &QuotaEta) -> String {
    let window = format!(
        "{} {}",
        provider_name(eta.tool),
        forecast_kind_word(eta.kind)
    );
    match &eta.outcome {
        QuotaEtaOutcome::ProjectedHit { at, .. } => {
            format!(
                "{window}: projected to hit ~{} (UTC, estimated)",
                at.format("%A")
            )
        }
        QuotaEtaOutcome::ResetsFirst { .. } => {
            format!("{window}: resets before you hit it (estimated)")
        }
        QuotaEtaOutcome::Unavailable { reason } => {
            format!(
                "{window}: ETA unavailable ({})",
                quota_eta_unavailable_text(*reason)
            )
        }
    }
}

/// A readable window-length word for the forecast quota lines (fuller than the meter's terse
/// `limit_kind` abbreviations, since the forecast has room).
fn forecast_kind_word(kind: LimitKind) -> &'static str {
    match kind {
        LimitKind::FiveHour => "5h",
        LimitKind::Weekly => "weekly",
        LimitKind::Daily => "daily",
        LimitKind::Monthly => "monthly",
        LimitKind::BillingCycle => "billing cycle",
    }
}

fn quota_eta_unavailable_text(reason: QuotaEtaUnavailable) -> &'static str {
    match reason {
        QuotaEtaUnavailable::ReadingNotProjectable => "no fresh verified usage reading",
        QuotaEtaUnavailable::WindowJustStarted => "window just started",
    }
}

// ---------------------------------------------------------------------------
// Anomalies tab (T16) — `costroid` TUI tab `8`. Proactive, non-alarmist callouts vs the user's
// OWN recent history: two signals (a daily spend spike + a model-mix shift), each compared to a
// robust median+MAD baseline over the trailing 14 UTC days, suppressed below a 7-day floor. An
// ADVISORY tab: MONOCHROME (amber/red is reserved for the near-limit/over-budget meter state,
// which the anomalies tab has none of — it is advisory text). Each callout carries a NON-COLOR
// marker (`◆`/`*`) that survives `--plain`, never color. The quota burn-rate signal is DEFERRED
// (local data keeps no multi-day quota history) — surfaced honestly in the footnote, never faked.
// Mirrors the `render_forecast_*` split; plain delimits by labels, never the `─` rule (T11 gotcha).
// ---------------------------------------------------------------------------

/// The standing reminder that the anomaly figures are local estimates vs the user's own history.
/// ASCII.
const ANOMALIES_ESTIMATE_NOTE: &str =
    "figures are local estimates (your tokens x current prices), vs your own recent history.";
/// The honest disclosure that the quota burn-rate signal is deferred — local data keeps only a
/// single point-in-time quota reading, so there is no multi-day series to difference (§11.5 T16).
/// Surfaced so the missing third signal reads as a stated limitation, never a silent gap. ASCII.
const ANOMALIES_QUOTA_DEFERRED_NOTE: &str =
    "quota burn-rate anomalies need multi-day quota history, which local data does not keep - not shown.";
/// The scope line names the two signals' **asymmetric lane scopes** + the comparison basis WITHOUT
/// a day count — each rendered count below reflects the user's ACTUAL realized baseline days
/// (per-signal), so the 14-day window policy is never cited as if it were the realized comparison.
/// The spend spike is **API-lane $** (subscription lanes are not a summable dollar — matching the
/// Budget/Forecast "API-lane spend" scope); the model mix is **all-lane** token share (a share is
/// lane-agnostic, so a subscription-only user IS served — T16b). Naming both keeps the asymmetry
/// honest on screen. ASCII.
const ANOMALIES_SCOPE_LINE: &str =
    "scope: API-lane spend spike + all-lane model mix vs your own recent history (estimated)";
/// The TRANSIENT zero-state for a user with **no usage recorded at all** (`history_days == 0` — the
/// all-lane token series is empty). After T16b the model-mix counts every lane, so a
/// subscription-only user (e.g. Claude Code Max with no API key) IS covered once they accrue enough
/// token-days — so the copy says it fills in as usage accrues, NOT the old permanent "no API-lane
/// usage" no-coverage framing. ASCII.
const ANOMALIES_NO_USAGE: &str =
    "no usage recorded yet - callouts need a few days of history (estimated)";

#[cfg(test)]
pub(crate) fn render_anomalies(view: &AnomaliesView, options: RenderOptions) -> String {
    render_anomalies_document(view, options).render(options)
}

pub(crate) fn render_anomalies_document(
    view: &AnomaliesView,
    options: RenderOptions,
) -> StyledDocument {
    match options.mode {
        RenderMode::Plain => render_anomalies_plain_document(view),
        RenderMode::Braille | RenderMode::Ascii => render_anomalies_visual_document(view, options),
    }
}

fn render_anomalies_visual_document(
    view: &AnomaliesView,
    options: RenderOptions,
) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_header_line(
        &mut out,
        mark(options),
        "anomalies",
        anomalies_header_label(view),
        options,
    );
    push_line(&mut out, ANOMALIES_SCOPE_LINE);
    push_anomalies_body(&mut out, view, options);
    push_rule(&mut out, options);
    push_line(&mut out, ANOMALIES_QUOTA_DEFERRED_NOTE);
    push_line(&mut out, ANOMALIES_ESTIMATE_NOTE);
    out
}

fn render_anomalies_plain_document(view: &AnomaliesView) -> StyledDocument {
    let mut out = StyledDocument::new();
    push_line(&mut out, "costroid anomalies");
    push_line(&mut out, ANOMALIES_SCOPE_LINE);
    push_anomalies_body(&mut out, view, RenderOptions::plain());
    push_line(&mut out, ANOMALIES_QUOTA_DEFERRED_NOTE);
    push_line(&mut out, ANOMALIES_ESTIMATE_NOTE);
    out
}

/// The right-hand header label: the count of callouts when there are any, else empty (no
/// fabricated figure above an empty/insufficient state).
fn anomalies_header_label(view: &AnomaliesView) -> String {
    if !view.enough_history || view.anomalies.is_empty() {
        String::new()
    } else {
        format!("{} flagged", view.anomalies.len())
    }
}

/// The body: the honest insufficient-history state, the honest no-anomalies state, or one marked
/// line per anomaly. Shared by the visual and plain renderers.
fn push_anomalies_body(out: &mut StyledDocument, view: &AnomaliesView, options: RenderOptions) {
    // The TRANSIENT zero-state first: no usage recorded at all. After T16b this is NOT permanent —
    // a subscription-only user is covered once they accrue enough token-days — so the copy says it
    // fills in, never the old "API-lane only" permanent framing. (The "N of M days" thin-history
    // line below is the 1..6-day state.)
    if view.no_usage {
        push_line(out, ANOMALIES_NO_USAGE);
        return;
    }
    if !view.enough_history {
        push_line(
            out,
            &format!(
                "not enough history yet - {} of {} days (estimated)",
                view.history_days, view.min_history_days
            ),
        );
        return;
    }
    if view.anomalies.is_empty() {
        push_line(
            out,
            &format!(
                "no anomalies - usage in line with your {}-day norm (estimated)",
                view.history_days
            ),
        );
        return;
    }
    for anomaly in &view.anomalies {
        push_line(out, &anomaly_line(anomaly, options));
    }
}

/// The non-color callout marker — a glyph (never color) that survives `--plain`: a filled diamond
/// in braille, a pure-ASCII `*` elsewhere (the proactive insight voice, mirroring [`insight_line`]).
fn anomaly_marker(options: RenderOptions) -> &'static str {
    match options.mode {
        RenderMode::Braille => "",
        RenderMode::Ascii | RenderMode::Plain => "* ",
    }
}

/// One anomaly's proactive, hedged callout line — always `~`-hedged + `(estimated)`-tagged, with
/// the compared `N-day` window named. The "~N.Nx your norm" multiple is shown ONLY when it would
/// read honestly (see [`anomaly_multiple_phrase`]); otherwise the descriptive ("well above" / "up
/// from") phrasing is used so the line never contradicts its own displayed baseline.
fn anomaly_line(anomaly: &Anomaly, options: RenderOptions) -> String {
    let marker = anomaly_marker(options);
    match &anomaly.signal {
        AnomalySignal::SpendSpike { date } => {
            let median_display = format_money(&anomaly.baseline_median, Some("USD"), true);
            // The displayed $ baseline rounds to zero when it is below half a cent (`format_money`
            // is 2dp) — a "~Nx your $0.00" line would be self-contradictory.
            let baseline_displays_zero = anomaly.baseline_median.round_dp(2) == Decimal::ZERO;
            let comparison =
                match anomaly_multiple_phrase(anomaly.magnitude, baseline_displays_zero) {
                    Some(multiple) => {
                        format!(
                            "~{multiple}x your {median_display} {}-day median",
                            anomaly.baseline_days
                        )
                    }
                    None => {
                        format!(
                            "well above your {median_display} {}-day median",
                            anomaly.baseline_days
                        )
                    }
                };
            format!(
                "{marker}spend spike: {} on {}, {comparison} (estimated)",
                format_money(&anomaly.value, Some("USD"), true),
                date.format("%b %d"),
            )
        }
        AnomalySignal::ModelMixShift { model } => {
            let today_share = percent(anomaly.value.to_f64().unwrap_or(0.0));
            let median_share = percent(anomaly.baseline_median.to_f64().unwrap_or(0.0));
            let comparison = if anomaly.value > anomaly.baseline_median {
                // The displayed share baseline rounds to "0%" when it is below half a percent
                // (`percent` is 0dp) — a "~Nx your 0% median" line would be self-contradictory.
                // Key off the EXACT displayed string so the guard can never diverge from the shown
                // percent (the f64 round `percent` uses differs from Decimal banker's-rounding at the
                // 0.5% boundary — keying off `median_share` keeps them identical).
                let baseline_displays_zero = median_share == "0%";
                match anomaly_multiple_phrase(anomaly.magnitude, baseline_displays_zero) {
                    Some(multiple) => {
                        format!(
                            "~{multiple}x your {median_share} {}-day median",
                            anomaly.baseline_days
                        )
                    }
                    None => {
                        format!(
                            "up from your {median_share} {}-day median",
                            anomaly.baseline_days
                        )
                    }
                }
            } else {
                format!(
                    "down from your {} {}-day median",
                    median_share, anomaly.baseline_days
                )
            };
            format!("{marker}model mix shift: {model} at {today_share} of tokens, {comparison} (estimated)")
        }
    }
}

/// The "~N.Nx" multiple to show for a callout, or `None` to fall back to the descriptive
/// (no-multiple) phrasing. Suppressed when there is no magnitude (the median was `0`), when the
/// DISPLAYED baseline rounds to zero (a multiple over a shown "$0.00"/"0%" is self-contradictory —
/// finding #1), or when the multiple rounds to `1.0x` (a flagged-but-tiny move — e.g. a $1 bump on
/// a tight-history high-spend user; honest to describe, misleading to quantify as "~1.0x" — finding
/// #4). All money/share math stays exact [`Decimal`]; only the final label is text.
fn anomaly_multiple_phrase(
    magnitude: Option<Decimal>,
    baseline_displays_zero: bool,
) -> Option<String> {
    let multiple = magnitude?;
    if baseline_displays_zero {
        return None;
    }
    let rounded = multiple.round_dp(1);
    if rounded <= Decimal::ONE {
        return None;
    }
    Some(rounded.to_string())
}

fn render_statusline_line(summary: &NowSummary, options: RenderOptions) -> StyledLine {
    let api = sorted_lane_rows(&summary.current_costs, CostLane::Api);
    let api_total = sum_costs(&api);
    let spend = format_money(&api_total, Some("USD"), true);
    let api_state = if api.is_empty() { " no api" } else { "" };

    match options.mode {
        RenderMode::Plain => match most_constrained_limit(&summary.limits) {
            Some(limit) => StyledLine::plain(format!(
                "costroid {spend},{} {}",
                if api.is_empty() { " no API usage," } else { "" },
                plain_limit_phrase(limit)
            )),
            None => StyledLine::plain(format!(
                "costroid {spend}{}",
                if api.is_empty() { ", no API usage" } else { "" }
            )),
        },
        RenderMode::Braille | RenderMode::Ascii => match most_constrained_limit(&summary.limits) {
            Some(limit) => {
                let (fraction, reset) = limit_fraction_and_reset(limit);
                let pct = percent(fraction);
                // An unverified window may be the most-constrained pick (brief §8); it must
                // carry the `? unverified` cue and a neutral meter, never a confident `!!`.
                let unverified = matches!(limit.availability, LimitAvailability::Unverified { .. });
                let cue = if unverified {
                    UNVERIFIED_CUE.to_string()
                } else {
                    state_cue(limit_state(fraction)).to_string()
                };
                let reset = reset
                    .map(|seconds| format!(" {}", compact_reset(seconds)))
                    .unwrap_or_default();
                let mut line = StyledLine::new();
                line.push_plain(format!("{} {spend}{api_state}  ", mark(options)));
                line.spans.push(limit_meter_with_confidence(
                    fraction,
                    unverified,
                    STATUS_BAR_WIDTH,
                    options,
                ));
                line.push_plain(format!(" {pct}{cue}{reset}"));
                line
            }
            None => StyledLine::plain(format!("{} {spend}{api_state}", mark(options))),
        },
    }
}

fn render_now_visual_document(summary: &NowSummary, options: RenderOptions) -> StyledDocument {
    let mut out = StyledDocument::new();
    let api = sorted_lane_rows(&summary.current_costs, CostLane::Api);
    let api_total = sum_costs(&api);

    push_header_line(
        &mut out,
        mark(options),
        "this week",
        format_money(&api_total, Some("USD"), true),
        options,
    );
    push_rule(&mut out, options);
    push_line(&mut out, "limits");
    if summary.limits.is_empty() {
        push_line(&mut out, "  no local limit data found");
    } else {
        for limit in &summary.limits {
            out.push(render_limit_line(limit, summary.generated_at, options));
            if let Some(caveat) = claude_caveat(limit) {
                push_line(&mut out, &format!("    {caveat}"));
            }
        }
    }
    push_rule(&mut out, options);
    push_line(&mut out, "api costs (this week)");
    if api.is_empty() {
        push_line(&mut out, "  no API usage in this period");
    } else {
        push_cost_rows(&mut out, &api, options);
    }
    push_non_api_sections(&mut out, &summary.current_costs, options);
    push_rule(&mut out, options);
    push_line(
        &mut out,
        &mode_insight(insight_line(&api, &summary.limits), options),
    );
    push_provider_notes(&mut out, &summary.providers);
    push_empty_provider_guidance(&mut out, &summary.providers);
    out
}

fn render_now_plain_document(summary: &NowSummary) -> StyledDocument {
    let mut out = StyledDocument::new();
    let api = sorted_lane_rows(&summary.current_costs, CostLane::Api);
    let api_total = sum_costs(&api);

    push_line(&mut out, "costroid now");
    push_line(
        &mut out,
        &format!(
            "period: this week, estimated API spend: {}",
            format_money(&api_total, Some("USD"), true)
        ),
    );
    push_line(&mut out, "limits:");
    if summary.limits.is_empty() {
        push_line(&mut out, "  no local limit data found");
    } else {
        for limit in &summary.limits {
            push_line(&mut out, &plain_limit_line(limit, summary.generated_at));
            if let Some(caveat) = claude_caveat(limit) {
                push_line(&mut out, &format!("    {caveat}"));
            }
        }
    }
    push_line(&mut out, "api costs this week:");
    if api.is_empty() {
        push_line(&mut out, "  no API usage in this period");
    } else {
        for row in &api {
            push_line(&mut out, &plain_cost_line(row));
        }
    }
    push_plain_non_api_sections(&mut out, &summary.current_costs);
    push_line(&mut out, &plain_insight_line(&api, &summary.limits));
    push_provider_notes(&mut out, &summary.providers);
    push_empty_provider_guidance(&mut out, &summary.providers);
    out
}

fn render_trends_visual_document(
    summary: &TrendsSummary,
    options: RenderOptions,
) -> StyledDocument {
    let mut out = StyledDocument::new();
    let api = sorted_lane_rows(&summary.totals, CostLane::Api);
    let api_total = sum_costs(&api);

    push_header_line(
        &mut out,
        mark(options),
        period_scope(summary.period),
        format_money(&api_total, Some("USD"), true),
        options,
    );
    push_line(
        &mut out,
        &format!(
            "  {}            group: {}",
            period_tabs(summary.period),
            group_tabs(summary.group_by)
        ),
    );
    push_rule(&mut out, options);
    push_line(
        &mut out,
        &format!("  api spend / {}", period_bucket_label(summary.period)),
    );
    let values = api_bucket_values(summary);
    if api.is_empty() {
        push_line(&mut out, "  no API usage in this period");
    } else {
        push_line(&mut out, &format!("  {}", sparkline(&values, options)));
        push_line(
            &mut out,
            &format!("  {}", sparkline_labels(summary.period, values.len())),
        );
    }
    push_rule(&mut out, options);
    push_line(&mut out, "breakdown");
    if api.is_empty() {
        push_line(&mut out, "  no API usage in this period");
    } else {
        push_cost_rows(&mut out, &api, options);
    }
    push_non_api_sections(&mut out, &summary.totals, options);
    push_rule(&mut out, options);
    push_line(&mut out, &mode_insight(insight_line(&api, &[]), options));
    push_provider_notes(&mut out, &summary.providers);
    push_empty_provider_guidance(&mut out, &summary.providers);
    out
}

fn render_trends_plain_document(summary: &TrendsSummary) -> StyledDocument {
    let mut out = StyledDocument::new();
    let api = sorted_lane_rows(&summary.totals, CostLane::Api);
    let api_total = sum_costs(&api);

    push_line(&mut out, "costroid trends");
    push_line(
        &mut out,
        &format!(
            "period: {}, group: {}, estimated API spend: {}",
            period_name(summary.period),
            group_name(summary.group_by),
            format_money(&api_total, Some("USD"), true)
        ),
    );
    push_line(&mut out, "api spend buckets:");
    if api.is_empty() {
        push_line(&mut out, "  no API usage in this period");
    } else {
        for (range, value) in plain_api_bucket_values(summary) {
            push_line(
                &mut out,
                &format!(
                    "  {}: {}",
                    format_bucket_start(&range),
                    format_money(&value, Some("USD"), true)
                ),
            );
        }
    }
    push_line(&mut out, "breakdown:");
    if api.is_empty() {
        push_line(&mut out, "  no API usage in this period");
    } else {
        for row in &api {
            push_line(&mut out, &plain_cost_line(row));
        }
    }
    push_plain_non_api_sections(&mut out, &summary.totals);
    push_line(&mut out, &plain_insight_line(&api, &[]));
    push_provider_notes(&mut out, &summary.providers);
    push_empty_provider_guidance(&mut out, &summary.providers);
    out
}

fn push_non_api_sections(
    out: &mut StyledDocument,
    rows: &[CostLaneSummary],
    options: RenderOptions,
) {
    let subscription = sorted_lane_rows(rows, CostLane::SubscriptionEstimate);
    if !subscription.is_empty() {
        push_rule(out, options);
        push_line(
            out,
            "subscription API-equivalent value (estimate, not bill)",
        );
        push_cost_rows(out, &subscription, options);
    }

    let unknown = sorted_lane_rows(rows, CostLane::UnknownAccess);
    if !unknown.is_empty() {
        push_rule(out, options);
        push_line(out, "unknown-access usage (partial)");
        push_cost_rows(out, &unknown, options);
    }
}

fn push_plain_non_api_sections(out: &mut StyledDocument, rows: &[CostLaneSummary]) {
    let subscription = sorted_lane_rows(rows, CostLane::SubscriptionEstimate);
    if !subscription.is_empty() {
        push_line(out, "subscription API-equivalent value, estimate not bill:");
        for row in &subscription {
            push_line(out, &plain_cost_line(row));
        }
    }

    let unknown = sorted_lane_rows(rows, CostLane::UnknownAccess);
    if !unknown.is_empty() {
        push_line(out, "unknown-access usage, partial:");
        for row in &unknown {
            push_line(out, &plain_cost_line(row));
        }
    }
}

fn push_cost_rows(out: &mut StyledDocument, rows: &[CostLaneSummary], options: RenderOptions) {
    let max = rows
        .iter()
        .map(|row| row.totals.billed_cost)
        .max()
        .unwrap_or_default();
    for row in rows {
        let money = format_money(
            &row.totals.billed_cost,
            row.totals.currency.as_deref(),
            row.totals.estimated_rows > 0,
        );
        let rendered_money_len = StyledSpan::styled(money.clone(), SemanticStyle::Strong)
            .render(options)
            .len();
        let badge = pricing_badge(&row.totals);
        let mut line = StyledLine::new();
        line.push_plain(format!("  {:<18}  ", display_group(&row.group.value)));
        line.spans.push(cost_bar_span(
            row.totals.billed_cost,
            max,
            cost_bar_width(options),
            options,
        ));
        line.push_plain(format!(
            "  {}",
            " ".repeat(12_usize.saturating_sub(rendered_money_len))
        ));
        line.push_styled(money, SemanticStyle::Strong);
        line.push_plain(badge);
        out.push(line);
    }
}

fn plain_cost_line(row: &CostLaneSummary) -> String {
    format!(
        "  {}: {}, {} tokens{}",
        display_group(&row.group.value),
        format_money(
            &row.totals.billed_cost,
            row.totals.currency.as_deref(),
            row.totals.estimated_rows > 0
        ),
        row.totals.tokens.total(),
        pricing_badge_plain(&row.totals)
    )
}

fn sorted_lane_rows(rows: &[CostLaneSummary], lane: CostLane) -> Vec<CostLaneSummary> {
    let mut selected = rows
        .iter()
        .filter(|row| row.lane == lane)
        .cloned()
        .collect::<Vec<_>>();
    selected.sort_by(|left, right| {
        right
            .totals
            .billed_cost
            .cmp(&left.totals.billed_cost)
            .then_with(|| left.group.value.cmp(&right.group.value))
    });
    selected
}

fn sum_costs(rows: &[CostLaneSummary]) -> Decimal {
    rows.iter()
        .fold(Decimal::ZERO, |total, row| total + row.totals.billed_cost)
}

/// The token-fraction carried by a [`LimitMeasure`], if any. `Spend` measures meter a
/// dollar pool, not a fraction, so they return `None` and are never selected as the
/// "most constrained" window (they render their own dollar line instead).
fn measure_fraction(measure: &LimitMeasure) -> Option<f64> {
    match measure {
        LimitMeasure::TokenFraction(fraction) => Some(*fraction),
        LimitMeasure::Spend { .. } => None,
    }
}

/// The always-on "as of HH:MM" freshness stamp (brief §8): once a reading is at least
/// [`LIMIT_FRESHNESS_STAMP_MINUTES`] old it must carry an age signal so it never renders
/// as a bare, confident meter. Empty for a still-fresh reading. Formatted in **UTC** so
/// snapshots stay timezone-deterministic (the suite avoids env mutation).
fn freshness_stamp(captured_at: DateTime<Utc>, generated_at: DateTime<Utc>) -> String {
    // The UNIX-epoch sentinel means "no observation instant recorded" (a cache or
    // rollout entry with a missing/unparseable capture time). Stamping it would render
    // a bogus, confident "as of 00:00" — disclose the unknown age instead.
    if captured_at.timestamp() == 0 {
        return "  capture time unknown".to_string();
    }
    if (generated_at - captured_at).num_minutes() >= LIMIT_FRESHNESS_STAMP_MINUTES {
        format!("  as of {}", captured_at.format("%H:%M"))
    } else {
        String::new()
    }
}

/// The Claude chat-under-report caveat for a Claude window that shows usage, else `None`.
/// The now-screen builders render it as an indented sub-note line. Covers `Available` /
/// `Unverified` (the meter reads low — brief §8) AND `Estimated` (the volume shown is
/// Claude-Code-only and must not be misread as account-wide — brief §6 requires the
/// "excludes claude.ai chat" disclosure on the absent→estimate fallback).
fn claude_caveat(limit: &LimitSummary) -> Option<&'static str> {
    let shows_usage = matches!(
        limit.availability,
        LimitAvailability::Available { .. }
            | LimitAvailability::Unverified { .. }
            | LimitAvailability::Estimated { .. }
    );
    (limit.tool == ProviderId::ClaudeCode && shows_usage).then_some(CLAUDE_CHAT_CAVEAT)
}

/// A meter span that never alarm-colors an `unverified` reading — an unverified near-max
/// must draw as a neutral bar, not a confident red one (brief §8). Verified readings keep
/// the state-based color from [`limit_meter_span`].
fn limit_meter_with_confidence(
    fraction: f64,
    unverified: bool,
    width: usize,
    options: RenderOptions,
) -> StyledSpan {
    if unverified {
        StyledSpan::styled(
            positional_meter_text(fraction, width, options),
            SemanticStyle::Strong,
        )
    } else {
        limit_meter_span(fraction, width, options)
    }
}

/// Format a `Spend` dollar pool as "$used / $included used", or "$used used" when there is
/// no published allowance — never fabricate a denominator (brief §6/§8).
fn spend_text(used_usd: &Decimal, included_usd: &Option<Decimal>) -> String {
    match included_usd {
        Some(included) => format!(
            "{} / {} used",
            format_money(used_usd, Some("USD"), false),
            format_money(included, Some("USD"), false)
        ),
        None => format!("{} used", format_money(used_usd, Some("USD"), false)),
    }
}

/// The `Estimated` window's local token volume (thousands-grouped for readability).
fn estimated_volume_text(volume_tokens: u64) -> String {
    format!("{} tokens", with_thousands(&volume_tokens.to_string()))
}

/// The estimated dollar value suffix for an `Estimated` window: "(~$value, estimated)"
/// when priced, or "(estimated)" alone when the model is unpriced — never a guessed price.
fn estimated_value_suffix(estimated_usd: &Option<Decimal>) -> String {
    match estimated_usd {
        Some(value) => format!(" ({}, estimated)", format_money(value, Some("USD"), true)),
        None => " (estimated)".to_string(),
    }
}

fn render_limit_line(
    limit: &LimitSummary,
    generated_at: DateTime<Utc>,
    options: RenderOptions,
) -> StyledLine {
    let tool = provider_name(limit.tool);
    let kind = limit_kind(limit.kind);
    let stamp = freshness_stamp(limit.captured_at, generated_at);
    match &limit.availability {
        LimitAvailability::Available {
            measure,
            reset_in_seconds,
            ..
        } => match measure {
            LimitMeasure::TokenFraction(fraction) => {
                let fraction = *fraction;
                let cue = state_cue(limit_state(fraction));
                let mut line = StyledLine::new();
                line.push_plain(format!("  {tool:<12} {kind:<3} "));
                line.spans
                    .push(limit_meter_span(fraction, LIMIT_BAR_WIDTH, options));
                line.push_plain(format!(
                    "  {}{}  resets {}{}",
                    percent(fraction),
                    cue,
                    reset_countdown(*reset_in_seconds),
                    stamp
                ));
                line
            }
            LimitMeasure::Spend {
                used_usd,
                included_usd,
            } => StyledLine::plain(format!(
                "  {tool:<12} {kind:<3} {}  resets {}{}",
                spend_text(used_usd, included_usd),
                reset_countdown(*reset_in_seconds),
                stamp
            )),
        },
        LimitAvailability::Partial {
            measure,
            reset_in_seconds,
            reason,
            ..
        } => {
            let reset = reset_in_seconds
                .map(reset_countdown)
                .map(|value| format!("  resets {value}"))
                .unwrap_or_default();
            // A Partial reading still carries an observation instant — give it the same
            // age signal as Available/Unverified (an arbitrarily old % must never render
            // with zero age cue; measure-less Partial has no reading to age).
            match measure {
                Some(LimitMeasure::TokenFraction(fraction)) => {
                    let fraction = *fraction;
                    let cue = state_cue(limit_state(fraction));
                    let mut line = StyledLine::new();
                    line.push_plain(format!("  {tool:<12} {kind:<3} "));
                    line.spans
                        .push(limit_meter_span(fraction, LIMIT_BAR_WIDTH, options));
                    line.push_plain(format!(
                        "  {}{}  partial: {}{}{}",
                        percent(fraction),
                        cue,
                        reason,
                        reset,
                        stamp
                    ));
                    line
                }
                Some(LimitMeasure::Spend {
                    used_usd,
                    included_usd,
                }) => StyledLine::plain(format!(
                    "  {tool:<12} {kind:<3} {}  partial: {}{}{}",
                    spend_text(used_usd, included_usd),
                    reason,
                    reset,
                    stamp
                )),
                None => {
                    StyledLine::plain(format!("  {tool:<12} {kind:<3} partial: {reason}{reset}"))
                }
            }
        }
        LimitAvailability::Unverified {
            measure,
            reset_in_seconds,
            ..
        } => {
            let reset = reset_in_seconds
                .map(reset_countdown)
                .map(|value| format!("  resets {value}"))
                .unwrap_or_default();
            match measure {
                LimitMeasure::TokenFraction(fraction) => {
                    let fraction = *fraction;
                    let mut line = StyledLine::new();
                    line.push_plain(format!("  {tool:<12} {kind:<3} "));
                    line.spans.push(limit_meter_with_confidence(
                        fraction,
                        true,
                        LIMIT_BAR_WIDTH,
                        options,
                    ));
                    line.push_plain(format!(
                        "  {}{}{}{}",
                        percent(fraction),
                        UNVERIFIED_CUE,
                        reset,
                        stamp
                    ));
                    line
                }
                LimitMeasure::Spend {
                    used_usd,
                    included_usd,
                } => StyledLine::plain(format!(
                    "  {tool:<12} {kind:<3} {}{}{}{}",
                    spend_text(used_usd, included_usd),
                    UNVERIFIED_CUE,
                    reset,
                    stamp
                )),
            }
        }
        LimitAvailability::Estimated {
            volume_tokens,
            estimated_usd,
        } => StyledLine::plain(format!(
            "  {tool:<12} {kind:<3} usage: {}{} {} quota % unavailable",
            estimated_volume_text(*volume_tokens),
            estimated_value_suffix(estimated_usd),
            // The em-dash is not ASCII — substitute in the Ascii fallback mode.
            if options.mode == RenderMode::Ascii {
                "--"
            } else {
                ""
            }
        )),
        LimitAvailability::Unavailable { reason } => {
            StyledLine::plain(format!("  {tool:<12} {kind:<3} unavailable: {reason}"))
        }
    }
}

fn plain_limit_line(limit: &LimitSummary, generated_at: DateTime<Utc>) -> String {
    let tool = provider_name(limit.tool);
    let kind = limit_kind(limit.kind);
    let stamp = freshness_stamp(limit.captured_at, generated_at);
    match &limit.availability {
        LimitAvailability::Available {
            measure,
            reset_in_seconds,
            ..
        } => match measure {
            LimitMeasure::TokenFraction(fraction) => {
                let cue = plain_state_phrase(limit_state(*fraction));
                format!(
                    "  {tool} {kind}: {} used{cue}, resets in {}{stamp}",
                    percent(*fraction),
                    reset_countdown(*reset_in_seconds)
                )
            }
            LimitMeasure::Spend {
                used_usd,
                included_usd,
            } => format!(
                "  {tool} {kind}: {}, resets in {}{stamp}",
                spend_text(used_usd, included_usd),
                reset_countdown(*reset_in_seconds)
            ),
        },
        LimitAvailability::Partial {
            measure,
            reset_in_seconds,
            reason,
            ..
        } => {
            let usage = match measure {
                Some(LimitMeasure::TokenFraction(fraction)) => format!(
                    "{} used{}",
                    percent(*fraction),
                    plain_state_phrase(limit_state(*fraction))
                ),
                Some(LimitMeasure::Spend {
                    used_usd,
                    included_usd,
                }) => spend_text(used_usd, included_usd),
                None => "usage unknown".to_string(),
            };
            let reset = reset_in_seconds
                .map(reset_countdown)
                .map(|value| format!(", resets in {value}"))
                .unwrap_or_default();
            // A Partial reading still carries an observation instant — give it the same
            // age signal as Available/Unverified (an arbitrarily old % must never render
            // with zero age cue; measure-less Partial has no reading to age).
            let stamp = if measure.is_some() {
                stamp
            } else {
                String::new()
            };
            format!("  {tool} {kind}: partial, {usage}{reset}, {reason}{stamp}")
        }
        LimitAvailability::Unverified {
            measure,
            reset_in_seconds,
            ..
        } => {
            let usage = match measure {
                LimitMeasure::TokenFraction(fraction) => format!("{} used", percent(*fraction)),
                LimitMeasure::Spend {
                    used_usd,
                    included_usd,
                } => spend_text(used_usd, included_usd),
            };
            let reset = reset_in_seconds
                .map(reset_countdown)
                .map(|value| format!(", resets in {value}"))
                .unwrap_or_default();
            format!("  {tool} {kind}: {usage}{UNVERIFIED_CUE}{reset}{stamp}")
        }
        LimitAvailability::Estimated {
            volume_tokens,
            estimated_usd,
        } => format!(
            "  {tool} {kind}: usage {}{}, quota % unavailable",
            estimated_volume_text(*volume_tokens),
            estimated_value_suffix(estimated_usd)
        ),
        LimitAvailability::Unavailable { reason } => {
            format!("  {tool} {kind}: unavailable, {reason}")
        }
    }
}

fn plain_limit_phrase(limit: &LimitSummary) -> String {
    let tool = provider_name(limit.tool);
    let kind = limit_kind(limit.kind);
    match &limit.availability {
        LimitAvailability::Available {
            measure,
            reset_in_seconds,
            ..
        } => match measure {
            LimitMeasure::TokenFraction(fraction) => format!(
                "{tool} {kind} {} used{}, resets in {}",
                percent(*fraction),
                plain_state_phrase(limit_state(*fraction)),
                compact_reset(*reset_in_seconds)
            ),
            LimitMeasure::Spend {
                used_usd,
                included_usd,
            } => format!(
                "{tool} {kind} {}, resets in {}",
                spend_text(used_usd, included_usd),
                compact_reset(*reset_in_seconds)
            ),
        },
        LimitAvailability::Partial {
            measure,
            reset_in_seconds,
            reason,
            ..
        } => {
            let usage = match measure {
                Some(LimitMeasure::TokenFraction(fraction)) => format!(
                    "{}{}",
                    percent(*fraction),
                    plain_state_phrase(limit_state(*fraction))
                ),
                Some(LimitMeasure::Spend {
                    used_usd,
                    included_usd,
                }) => spend_text(used_usd, included_usd),
                None => "unknown usage".to_string(),
            };
            let reset = reset_in_seconds
                .map(compact_reset)
                .map(|value| format!(", resets in {value}"))
                .unwrap_or_default();
            format!("{tool} {kind} partial, {usage}{reset}, {reason}")
        }
        LimitAvailability::Unverified {
            measure,
            reset_in_seconds,
            ..
        } => {
            let usage = match measure {
                LimitMeasure::TokenFraction(fraction) => format!("{} used", percent(*fraction)),
                LimitMeasure::Spend {
                    used_usd,
                    included_usd,
                } => spend_text(used_usd, included_usd),
            };
            let reset = reset_in_seconds
                .map(compact_reset)
                .map(|value| format!(", resets in {value}"))
                .unwrap_or_default();
            format!("{tool} {kind} {usage}{UNVERIFIED_CUE}{reset}")
        }
        LimitAvailability::Estimated {
            volume_tokens,
            estimated_usd,
        } => format!(
            "{tool} {kind} usage {}{}, quota % unavailable",
            estimated_volume_text(*volume_tokens),
            estimated_value_suffix(estimated_usd)
        ),
        LimitAvailability::Unavailable { reason } => {
            format!("{tool} {kind} unavailable, {reason}")
        }
    }
}

fn most_constrained_limit(limits: &[LimitSummary]) -> Option<&LimitSummary> {
    limits.iter().filter(has_fraction).max_by(|left, right| {
        let left_fraction = limit_fraction(left).unwrap_or(0.0);
        let right_fraction = limit_fraction(right).unwrap_or(0.0);
        left_fraction.total_cmp(&right_fraction)
    })
}

fn has_fraction(limit: &&LimitSummary) -> bool {
    limit_fraction(limit).is_some()
}

fn limit_fraction(limit: &LimitSummary) -> Option<f64> {
    match &limit.availability {
        LimitAvailability::Available { measure, .. } => measure_fraction(measure),
        LimitAvailability::Partial {
            measure: Some(measure),
            ..
        } => measure_fraction(measure),
        // An Unverified window IS eligible to be the most-constrained pick (brief §8); the
        // statusline carries its `? unverified` cue so a maxed-looking reading is never
        // shown as confident. `Estimated` has no fraction → excluded, like `Unavailable`.
        LimitAvailability::Unverified { measure, .. } => measure_fraction(measure),
        LimitAvailability::Partial { measure: None, .. }
        | LimitAvailability::Estimated { .. }
        | LimitAvailability::Unavailable { .. } => None,
    }
}

fn limit_fraction_and_reset(limit: &LimitSummary) -> (f64, Option<i64>) {
    match &limit.availability {
        LimitAvailability::Available {
            measure,
            reset_in_seconds,
            ..
        } => (
            measure_fraction(measure).unwrap_or(0.0),
            Some(*reset_in_seconds),
        ),
        LimitAvailability::Partial {
            measure,
            reset_in_seconds,
            ..
        } => (
            measure.as_ref().and_then(measure_fraction).unwrap_or(0.0),
            *reset_in_seconds,
        ),
        LimitAvailability::Unverified {
            measure,
            reset_in_seconds,
            ..
        } => (measure_fraction(measure).unwrap_or(0.0), *reset_in_seconds),
        LimitAvailability::Estimated { .. } | LimitAvailability::Unavailable { .. } => (0.0, None),
    }
}

fn limit_state(fraction: f64) -> LimitState {
    if fraction >= 1.0 {
        LimitState::Over
    } else if fraction >= CRITICAL_FRACTION {
        LimitState::Critical
    } else if fraction >= WARN_FRACTION {
        LimitState::Warn
    } else {
        LimitState::Normal
    }
}

fn state_cue(state: LimitState) -> &'static str {
    match state {
        LimitState::Normal => "",
        LimitState::Warn => " !",
        LimitState::Critical => " !!",
        LimitState::Over => " !! OVER",
    }
}

fn plain_state_phrase(state: LimitState) -> &'static str {
    match state {
        LimitState::Normal => "",
        LimitState::Warn => " (near limit)",
        LimitState::Critical => " (critical)",
        LimitState::Over => " (over limit)",
    }
}

#[cfg(test)]
fn limit_meter(fraction: f64, width: usize, options: RenderOptions) -> String {
    limit_meter_span(fraction, width, options).render(options)
}

fn limit_meter_span(fraction: f64, width: usize, options: RenderOptions) -> StyledSpan {
    StyledSpan::styled(
        positional_meter_text(fraction, width, options),
        state_style(limit_state(fraction)),
    )
}

/// The semantic style for a near-/over-limit state: Normal stays bold (a non-color cue),
/// Warn is amber, Critical/Over are red. Shared by the limit meter and the Budget tab — the
/// two places where amber/red is allowed, always paired with a non-color textual cue.
fn state_style(state: LimitState) -> SemanticStyle {
    match state {
        LimitState::Normal => SemanticStyle::Strong,
        LimitState::Warn => SemanticStyle::Warn,
        LimitState::Critical | LimitState::Over => SemanticStyle::Critical,
    }
}

fn cost_bar_span(
    amount: Decimal,
    max: Decimal,
    width: usize,
    options: RenderOptions,
) -> StyledSpan {
    let fraction = if max > Decimal::ZERO {
        (amount / max).to_f64().unwrap_or(0.0)
    } else {
        0.0
    };
    StyledSpan::styled(
        positional_meter_text(fraction, width, options),
        SemanticStyle::Strong,
    )
}

fn positional_meter_text(fraction: f64, width: usize, options: RenderOptions) -> String {
    let segments = meter_segments(fraction, width);
    match options.mode {
        RenderMode::Plain => String::new(),
        RenderMode::Ascii => {
            let mut meter = String::with_capacity(width + 2);
            meter.push('[');
            meter.extend(std::iter::repeat_n('#', segments.full));
            if segments.partial {
                meter.push('+');
            }
            meter.extend(std::iter::repeat_n('-', segments.remaining));
            meter.push(']');
            meter
        }
        RenderMode::Braille => {
            let mut meter = String::with_capacity(width);
            meter.extend(std::iter::repeat_n(braille_full(), segments.full));
            if segments.partial {
                meter.push(braille_left_column());
            }
            meter.extend(std::iter::repeat_n(braille_light(), segments.remaining));
            meter
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MeterSegments {
    full: usize,
    partial: bool,
    remaining: usize,
}

fn meter_segments(fraction: f64, width: usize) -> MeterSegments {
    if width == 0 {
        return MeterSegments {
            full: 0,
            partial: false,
            remaining: 0,
        };
    }
    let clamped = fraction.clamp(0.0, 1.0);
    if clamped >= 1.0 {
        return MeterSegments {
            full: width,
            partial: false,
            remaining: 0,
        };
    }
    if clamped <= 0.0 {
        return MeterSegments {
            full: 0,
            partial: false,
            remaining: width,
        };
    }

    let exact = clamped * width as f64;
    let mut full = exact.floor() as usize;
    let mut partial = exact - full as f64 >= 0.5;
    if full == 0 && !partial {
        partial = true;
    }
    if partial && full >= width {
        partial = false;
    }
    let used = full + usize::from(partial);
    if used > width {
        full = width;
        partial = false;
    }

    MeterSegments {
        full,
        partial,
        remaining: width.saturating_sub(full + usize::from(partial)),
    }
}

fn sparkline(values: &[Decimal], options: RenderOptions) -> String {
    match options.mode {
        RenderMode::Plain => String::new(),
        RenderMode::Ascii => ascii_sparkline(values),
        RenderMode::Braille => braille_sparkline(values),
    }
}

fn ascii_sparkline(values: &[Decimal]) -> String {
    let max = values.iter().copied().max().unwrap_or_default();
    let ramp = ['.', ':', '-', '=', '+', '*', '#'];
    values
        .iter()
        .map(|value| {
            if max <= Decimal::ZERO || *value <= Decimal::ZERO {
                '.'
            } else {
                let fraction = (*value / max).to_f64().unwrap_or(0.0);
                let index =
                    ((fraction * (ramp.len() - 1) as f64).round() as usize).min(ramp.len() - 1);
                ramp[index]
            }
        })
        .collect()
}

fn braille_sparkline(values: &[Decimal]) -> String {
    let max = values.iter().copied().max().unwrap_or_default();
    values
        .iter()
        .map(|value| {
            if max <= Decimal::ZERO || *value <= Decimal::ZERO {
                braille_blank()
            } else {
                let fraction = (*value / max).to_f64().unwrap_or(0.0);
                let height = ((fraction * 4.0).round() as u8).clamp(1, 4);
                braille_bar_height(height)
            }
        })
        .collect()
}

fn api_bucket_values(summary: &TrendsSummary) -> Vec<Decimal> {
    plain_api_bucket_values(summary)
        .into_iter()
        .map(|(_, value)| value)
        .collect()
}

fn plain_api_bucket_values(summary: &TrendsSummary) -> Vec<(PeriodRange, Decimal)> {
    let mut buckets = BTreeMap::<PeriodRange, Decimal>::new();
    for bucket in summary
        .buckets
        .iter()
        .filter(|bucket| bucket.lane == CostLane::Api)
    {
        let total = buckets.entry(bucket.period.clone()).or_default();
        *total += bucket.totals.billed_cost;
    }
    buckets.into_iter().collect()
}

fn mark(options: RenderOptions) -> &'static str {
    match options.mode {
        RenderMode::Braille => "C⠉",
        RenderMode::Ascii | RenderMode::Plain => "costroid",
    }
}

/// Bit for a braille dot number (1-8) in the U+2800 cell mask.
fn bit_for_dot(dot: u8) -> u8 {
    match dot {
        1 => 1,
        2 => 2,
        3 => 4,
        4 => 8,
        5 => 16,
        6 => 32,
        7 => 64,
        8 => 128,
        _ => 0,
    }
}

fn braille_cell(dots: &[u8]) -> char {
    let mut mask = 0_u8;
    for dot in dots {
        mask |= bit_for_dot(*dot);
    }
    byte_to_braille(mask)
}

/// A filled braille cell mask → its glyph (base U+2800 + the 8-bit dot mask).
fn byte_to_braille(mask: u8) -> char {
    char::from_u32(0x2800 + u32::from(mask)).unwrap_or('\u{2800}')
}

fn braille_blank() -> char {
    braille_cell(&[])
}

fn braille_full() -> char {
    braille_cell(&[1, 2, 3, 4, 5, 6, 7, 8])
}

fn braille_light() -> char {
    braille_cell(&[7, 8])
}

fn braille_left_column() -> char {
    braille_cell(&[1, 2, 3, 7])
}

fn braille_bar_height(height: u8) -> char {
    match height {
        0 => braille_blank(),
        1 => braille_cell(&[7, 8]),
        2 => braille_cell(&[3, 6, 7, 8]),
        3 => braille_cell(&[2, 3, 5, 6, 7, 8]),
        _ => braille_full(),
    }
}

fn push_line(out: &mut StyledDocument, line: &str) {
    out.push(StyledLine::plain(line));
}

fn push_rule(out: &mut StyledDocument, options: RenderOptions) {
    // RenderMode::Ascii targets terminals that may not render multi-byte glyphs
    // (chosen when braille capability — incl. a UTF-8 locale — is absent), so the
    // horizontal rule must be pure ASCII there.
    let glyph = if options.mode == RenderMode::Ascii {
        "-"
    } else {
        ""
    };
    push_line(out, &glyph.repeat(options.width.max(1)));
}

/// Swap the ◆ insight marker for a pure-ASCII one in [`RenderMode::Ascii`] (plain mode
/// replaces it with "insight:" separately).
fn mode_insight(line: String, options: RenderOptions) -> String {
    if options.mode == RenderMode::Ascii {
        line.replace('', "*")
    } else {
        line
    }
}

fn push_header_line(
    out: &mut StyledDocument,
    mark: &str,
    scope: &str,
    money: String,
    options: RenderOptions,
) {
    let mut line = StyledLine::new();
    if options.width == DEFAULT_RENDER_WIDTH {
        line.push_plain(format!(
            "{mark} costroid                                   {scope}  "
        ));
    } else {
        let left = format!("{mark} costroid");
        let right = format!("{scope}  ");
        let spacing = options
            .width
            .saturating_sub(visible_width(&left) + visible_width(&right) + visible_width(&money))
            .max(1);
        line.push_plain(format!("{left}{}{right}", " ".repeat(spacing)));
    }
    line.push_styled(money, SemanticStyle::Strong);
    out.push(line);
}

fn visible_width(value: &str) -> usize {
    value.chars().count()
}

fn cost_bar_width(options: RenderOptions) -> usize {
    if options.width <= DEFAULT_RENDER_WIDTH {
        COST_BAR_WIDTH
    } else {
        (COST_BAR_WIDTH + (options.width - DEFAULT_RENDER_WIDTH) / 4).min(32)
    }
}

fn push_provider_notes(out: &mut StyledDocument, providers: &[costroid_core::ProviderStatus]) {
    for provider in providers
        .iter()
        .filter(|provider| provider.status != ProviderStatusKind::Available)
    {
        let message = provider
            .message
            .as_deref()
            .unwrap_or("local data incomplete");
        push_line(
            out,
            &format!(
                "provider {} {}: {}",
                provider_name(provider.provider),
                provider_status(provider.status),
                message
            ),
        );
    }
}

fn push_empty_provider_guidance(
    out: &mut StyledDocument,
    providers: &[costroid_core::ProviderStatus],
) {
    if providers.iter().any(|provider| {
        matches!(
            provider.status,
            ProviderStatusKind::Available | ProviderStatusKind::Detected
        )
    }) {
        return;
    }

    push_line(out, "no providers detected");
    push_line(
        out,
        "looked for Claude Code, Codex, and Cursor local logs under the usual home/config dirs.",
    );
    push_line(
        out,
        "under WSL, Costroid also checks Windows paths like /mnt/c/Users/<you>/...",
    );
    push_line(
        out,
        "set CLAUDE_CONFIG_DIR or CODEX_HOME if your logs live elsewhere.",
    );
}

fn insight_line(api: &[CostLaneSummary], limits: &[LimitSummary]) -> String {
    if let Some(limit) = most_constrained_limit(limits) {
        let fraction = limit_fraction(limit).unwrap_or(0.0);
        if fraction >= WARN_FRACTION {
            // An unverified near-max must not read as a confident insight (brief §8) — flag it.
            let flag = if matches!(limit.availability, LimitAvailability::Unverified { .. }) {
                " (unverified)"
            } else {
                ""
            };
            return format!(
                "{} {} at {}{}, resets {}.",
                provider_name(limit.tool),
                limit_kind(limit.kind),
                percent(fraction),
                flag,
                limit_fraction_and_reset(limit)
                    .1
                    .map(reset_countdown)
                    .unwrap_or_else(|| "unknown".to_string())
            );
        }
    }

    match api.first() {
        Some(row) => format!(
            "{} drove most of your API spend in this period. (estimated)",
            display_group(&row.group.value)
        ),
        None => "◆ no API usage in this period. (estimated)".to_string(),
    }
}

fn plain_insight_line(api: &[CostLaneSummary], limits: &[LimitSummary]) -> String {
    insight_line(api, limits).replace('', "insight:")
}

fn pricing_badge(totals: &AggregateTotals) -> String {
    let label = pricing_badge_plain(totals);
    if label.is_empty() {
        String::new()
    } else {
        format!("  [{}]", label.trim_start_matches(", "))
    }
}

fn pricing_badge_plain(totals: &AggregateTotals) -> String {
    let missing = totals.pricing_coverage.missing_price_rows;
    let unknown = totals.pricing_coverage.unknown_model_rows;
    let priced = totals.pricing_coverage.priced_rows;
    if unknown > 0 {
        if priced > 0 || missing > 0 {
            ", unknown model/partial".to_string()
        } else {
            ", unknown model/unpriced".to_string()
        }
    } else if missing > 0 {
        if priced > 0 {
            ", partial pricing".to_string()
        } else {
            ", unpriced/partial".to_string()
        }
    } else {
        String::new()
    }
}

fn format_money(amount: &Decimal, currency: Option<&str>, estimated: bool) -> String {
    let prefix = if estimated { "~" } else { "" };
    let rounded = amount.round_dp(2).to_string();
    let (whole, fraction) = match rounded.split_once('.') {
        Some((whole, fraction)) => (whole, fraction),
        None => (rounded.as_str(), ""),
    };
    let fraction = two_decimal_digits(fraction);
    let whole = with_thousands(whole);
    match currency.unwrap_or("USD") {
        "USD" => format!("{prefix}${whole}.{fraction}"),
        other => format!("{prefix}{other} {whole}.{fraction}"),
    }
}

fn two_decimal_digits(value: &str) -> String {
    let mut fraction = value.chars().take(2).collect::<String>();
    while fraction.len() < 2 {
        fraction.push('0');
    }
    fraction
}

fn with_thousands(value: &str) -> String {
    let (sign, digits) = value
        .strip_prefix('-')
        .map(|digits| ("-", digits))
        .unwrap_or(("", value));
    let mut reversed = String::new();
    for (index, ch) in digits.chars().rev().enumerate() {
        if index > 0 && index % 3 == 0 {
            reversed.push(',');
        }
        reversed.push(ch);
    }
    let grouped = reversed.chars().rev().collect::<String>();
    format!("{sign}{grouped}")
}

fn percent(fraction: f64) -> String {
    format!("{:.0}%", (fraction * 100.0).round())
}

fn reset_countdown(seconds: i64) -> String {
    if seconds <= 0 {
        return "<1m".to_string();
    }
    let minutes = seconds / 60;
    if minutes < 1 {
        "<1m".to_string()
    } else if minutes < 60 {
        format!("{minutes}m")
    } else {
        let hours = minutes / 60;
        let remaining_minutes = minutes % 60;
        if hours < 24 {
            if remaining_minutes == 0 {
                format!("{hours}h")
            } else {
                format!("{hours}h {remaining_minutes}m")
            }
        } else {
            let days = hours / 24;
            let remaining_hours = hours % 24;
            if remaining_hours == 0 {
                format!("{days}d")
            } else {
                format!("{days}d {remaining_hours}h")
            }
        }
    }
}

fn compact_reset(seconds: i64) -> String {
    reset_countdown(seconds).replace(' ', "")
}

fn display_group(value: &str) -> String {
    let last = value
        .rsplit(['/', '\\'])
        .find(|part| !part.is_empty())
        .unwrap_or(value);
    last.replace('-', " ")
}

fn provider_name(provider: ProviderId) -> &'static str {
    match provider {
        ProviderId::ClaudeCode => "claude code",
        ProviderId::Codex => "codex",
        ProviderId::Cursor => "cursor",
    }
}

fn provider_status(status: ProviderStatusKind) -> &'static str {
    match status {
        ProviderStatusKind::Available => "available",
        ProviderStatusKind::Detected => "detected",
        ProviderStatusKind::Partial => "partial",
        ProviderStatusKind::Missing => "missing",
        ProviderStatusKind::Error => "error",
    }
}

fn limit_kind(kind: LimitKind) -> &'static str {
    // Short window labels (fit the `{kind:<3}` column). Daily/Monthly/BillingCycle
    // have no producer yet (no adapter emits them); revisit their abbreviations when
    // the first one lands (e.g. a Cursor billing-cycle window).
    match kind {
        LimitKind::FiveHour => "5h",
        LimitKind::Weekly => "wk",
        LimitKind::Daily => "1d",
        LimitKind::Monthly => "mo",
        LimitKind::BillingCycle => "cyc",
    }
}

fn period_scope(period: Period) -> &'static str {
    match period {
        Period::Day => "today",
        Period::Week => "this week",
        Period::Month => "this month",
        Period::Year => "this year",
    }
}

fn period_name(period: Period) -> &'static str {
    match period {
        Period::Day => "day",
        Period::Week => "week",
        Period::Month => "month",
        Period::Year => "year",
    }
}

fn period_bucket_label(period: Period) -> &'static str {
    match period {
        Period::Day => "day",
        Period::Week => "week",
        Period::Month => "month",
        Period::Year => "year",
    }
}

fn group_name(group: GroupBy) -> &'static str {
    match group {
        GroupBy::Model => "model",
        GroupBy::App => "app",
        GroupBy::Total => "total",
    }
}

fn period_tabs(active: Period) -> String {
    [Period::Day, Period::Week, Period::Month, Period::Year]
        .into_iter()
        .map(|period| {
            if period == active {
                format!("({})", period_name(period))
            } else {
                format!("[{}]", period_name(period))
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn group_tabs(active: GroupBy) -> String {
    [GroupBy::Model, GroupBy::App, GroupBy::Total]
        .into_iter()
        .map(|group| {
            if group == active {
                format!("({})", group_name(group))
            } else {
                group_name(group).to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn sparkline_labels(period: Period, len: usize) -> String {
    if len == 0 {
        return String::new();
    }
    match period {
        Period::Day => "start      now".to_string(),
        Period::Week => "mon       sun".to_string(),
        Period::Month => (1..=len)
            .map(|index| format!("w{index}"))
            .collect::<Vec<_>>()
            .join("   "),
        Period::Year => "jan       dec".to_string(),
    }
}

fn format_bucket_start(range: &PeriodRange) -> String {
    let local: DateTime<Local> = range.start.with_timezone(&Local);
    local.format("%Y-%m-%d").to_string()
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, LocalResult, NaiveDate, TimeZone, Utc};
    use costroid_core::{
        reconcile_cost, AggregateTotals, CostLaneSummary, CostLineItem, CostReportCaveats,
        CostReportOutcome, ForecastDay, GroupKey, LimitSummary, LocalCostEstimate, NowSummary,
        PeriodRange, PricingCoverage, ProviderStatus, TrendsSummary, VendorCostDay,
        VendorCostReport,
    };
    use rust_decimal::Decimal;

    use super::*;

    fn utc(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
        match Utc.with_ymd_and_hms(year, month, day, hour, minute, 0) {
            LocalResult::Single(value) => value,
            LocalResult::Ambiguous(_, _) | LocalResult::None => {
                panic!("test timestamp should be valid")
            }
        }
    }

    fn range(start: DateTime<Utc>, days: i64) -> PeriodRange {
        PeriodRange {
            start,
            end: start + Duration::days(days),
        }
    }

    /// A bucket start the way production builds them — a LOCAL midnight (core's
    /// `start_of_period_local`) — so the trends snapshot's `%Y-%m-%d` label (formatted
    /// in Local, the documented product behavior) is the same date in every timezone
    /// the suite runs in. A UTC-midnight fixture would render the previous day in any
    /// UTC-negative zone and break the snapshot.
    fn local_midnight_utc(year: i32, month: u32, day: u32) -> DateTime<Utc> {
        match Local.with_ymd_and_hms(year, month, day, 0, 0, 0) {
            LocalResult::Single(value) | LocalResult::Ambiguous(value, _) => {
                value.with_timezone(&Utc)
            }
            LocalResult::None => panic!("test local midnight should exist"),
        }
    }

    fn totals(cost_cents: i64, priced: usize, missing: usize, unknown: usize) -> AggregateTotals {
        AggregateTotals {
            row_count: priced + missing + unknown,
            billed_cost: Decimal::new(cost_cents, 2),
            effective_cost: Decimal::new(cost_cents, 2),
            currency: Some("USD".to_string()),
            multiple_currencies: false,
            tokens: costroid_core::TokenTotals {
                input: 10,
                output: 20,
                cache_read: 30,
                cache_write: 0,
            },
            pricing_coverage: PricingCoverage {
                priced_rows: priced,
                missing_price_rows: missing,
                unknown_model_rows: unknown,
            },
            estimated_rows: priced + missing + unknown,
        }
    }

    fn row(group: &str, lane: CostLane, cost_cents: i64) -> CostLaneSummary {
        CostLaneSummary {
            group: GroupKey {
                kind: GroupBy::Model,
                value: group.to_string(),
            },
            lane,
            totals: totals(cost_cents, 3, 0, 0),
        }
    }

    fn unpriced_row(group: &str, lane: CostLane) -> CostLaneSummary {
        CostLaneSummary {
            group: GroupKey {
                kind: GroupBy::Model,
                value: group.to_string(),
            },
            lane,
            totals: totals(0, 0, 3, 0),
        }
    }

    fn unknown_model_row(group: &str, lane: CostLane) -> CostLaneSummary {
        CostLaneSummary {
            group: GroupKey {
                kind: GroupBy::Model,
                value: group.to_string(),
            },
            lane,
            totals: totals(0, 0, 0, 3),
        }
    }

    fn limits() -> Vec<LimitSummary> {
        let now = utc(2026, 6, 2, 9, 0);
        vec![
            LimitSummary {
                tool: ProviderId::ClaudeCode,
                plan: None,
                kind: LimitKind::FiveHour,
                // Mirrors the descriptive label `unavailable_limit` emits since the
                // F26 fix (never the redundant "unavailable: unavailable").
                label: Some("no captured reading; run `costroid setup-statusline`".to_string()),
                captured_at: now,
                availability: LimitAvailability::Unavailable {
                    reason: "no captured reading; run `costroid setup-statusline`".to_string(),
                },
            },
            LimitSummary {
                tool: ProviderId::Codex,
                plan: Some("plus".to_string()),
                kind: LimitKind::FiveHour,
                label: None,
                captured_at: now,
                availability: LimitAvailability::Available {
                    measure: LimitMeasure::TokenFraction(0.78),
                    resets_at: now + Duration::minutes(41),
                    reset_in_seconds: 41 * 60,
                },
            },
            LimitSummary {
                tool: ProviderId::Codex,
                plan: Some("plus".to_string()),
                kind: LimitKind::Weekly,
                label: None,
                captured_at: now,
                availability: LimitAvailability::Available {
                    measure: LimitMeasure::TokenFraction(0.92),
                    resets_at: now + Duration::hours(54),
                    reset_in_seconds: 54 * 60 * 60,
                },
            },
            LimitSummary {
                tool: ProviderId::Cursor,
                plan: None,
                kind: LimitKind::Weekly,
                label: None,
                captured_at: now,
                availability: LimitAvailability::Partial {
                    measure: Some(LimitMeasure::TokenFraction(0.97)),
                    resets_at: None,
                    reset_in_seconds: None,
                    reason: "limit data incomplete".to_string(),
                },
            },
        ]
    }

    /// Every availability arm + both `LimitMeasure` shapes in one fixture so the snapshots
    /// prove T6 renders all five distinctly and uniformly across providers (brief §8/§9).
    /// All "live" readings are captured 30 min before `generated_at` so the always-on
    /// "as of HH:MM" stamp fires (threshold is 10 min); UTC keeps the stamp deterministic.
    fn all_arms_limits() -> Vec<LimitSummary> {
        let now = utc(2026, 6, 2, 9, 0);
        let captured = now - Duration::minutes(30);
        vec![
            // Available, TokenFraction — Claude: meter + stamp + chat caveat.
            LimitSummary {
                tool: ProviderId::ClaudeCode,
                plan: Some("max".to_string()),
                kind: LimitKind::FiveHour,
                label: None,
                captured_at: captured,
                availability: LimitAvailability::Available {
                    measure: LimitMeasure::TokenFraction(0.55),
                    resets_at: now + Duration::hours(2),
                    reset_in_seconds: 2 * 60 * 60,
                },
            },
            // Unverified, TokenFraction — Claude near-max, cross-check failed: neutral meter +
            // "? unverified" (never "!!") + stamp + caveat.
            LimitSummary {
                tool: ProviderId::ClaudeCode,
                plan: Some("max".to_string()),
                kind: LimitKind::Weekly,
                label: None,
                captured_at: captured,
                availability: LimitAvailability::Unverified {
                    measure: LimitMeasure::TokenFraction(0.96),
                    resets_at: Some(now + Duration::hours(50)),
                    reset_in_seconds: Some(50 * 60 * 60),
                },
            },
            // Available, TokenFraction — Codex: proves the stamp + render are uniform, not
            // Claude-only (no caveat — caveat is Claude-only).
            LimitSummary {
                tool: ProviderId::Codex,
                plan: Some("plus".to_string()),
                kind: LimitKind::FiveHour,
                label: None,
                captured_at: captured,
                availability: LimitAvailability::Available {
                    measure: LimitMeasure::TokenFraction(0.40),
                    resets_at: now + Duration::minutes(41),
                    reset_in_seconds: 41 * 60,
                },
            },
            // Available, Spend — a dollar credit pool with NO meter, NEVER a fabricated %.
            LimitSummary {
                tool: ProviderId::Cursor,
                plan: Some("pro".to_string()),
                kind: LimitKind::Monthly,
                label: None,
                captured_at: captured,
                availability: LimitAvailability::Available {
                    measure: LimitMeasure::Spend {
                        used_usd: Decimal::new(1850, 2),
                        included_usd: Some(Decimal::new(2000, 2)),
                    },
                    resets_at: now + Duration::days(12),
                    reset_in_seconds: 12 * 24 * 60 * 60,
                },
            },
            // Partial, TokenFraction — incomplete but not flagged (reset unknown).
            LimitSummary {
                tool: ProviderId::Cursor,
                plan: Some("pro".to_string()),
                kind: LimitKind::Weekly,
                label: None,
                captured_at: captured,
                availability: LimitAvailability::Partial {
                    measure: Some(LimitMeasure::TokenFraction(0.88)),
                    resets_at: None,
                    reset_in_seconds: None,
                    reason: "limit data incomplete".to_string(),
                },
            },
            // Estimated WITH a priced value — volume + ~$value, quota % unavailable, no meter.
            LimitSummary {
                tool: ProviderId::ClaudeCode,
                plan: Some("max".to_string()),
                kind: LimitKind::Daily,
                label: None,
                captured_at: now,
                availability: LimitAvailability::Estimated {
                    volume_tokens: 1_234_567,
                    estimated_usd: Some(Decimal::new(1234, 2)),
                },
            },
            // Estimated WITHOUT a value — unpriced model → volume alone, never a guessed price.
            LimitSummary {
                tool: ProviderId::Codex,
                plan: Some("plus".to_string()),
                kind: LimitKind::Daily,
                label: None,
                captured_at: now,
                availability: LimitAvailability::Estimated {
                    volume_tokens: 5_000,
                    estimated_usd: None,
                },
            },
            // Unavailable — unchanged arm, no meter, no stamp.
            LimitSummary {
                tool: ProviderId::Cursor,
                plan: None,
                kind: LimitKind::BillingCycle,
                label: Some("no sanctioned source".to_string()),
                captured_at: now,
                availability: LimitAvailability::Unavailable {
                    reason: "no sanctioned source".to_string(),
                },
            },
        ]
    }

    fn all_arms_now() -> NowSummary {
        let mut summary = priced_now();
        summary.limits = all_arms_limits();
        summary
    }

    fn provider_statuses() -> Vec<ProviderStatus> {
        vec![
            ProviderStatus {
                provider: ProviderId::ClaudeCode,
                status: ProviderStatusKind::Available,
                files: 1,
                usage_events: 1,
                focus_rows: 3,
                limit_windows: 2,
                message: None,
            },
            ProviderStatus {
                provider: ProviderId::Cursor,
                status: ProviderStatusKind::Missing,
                files: 0,
                usage_events: 0,
                focus_rows: 0,
                limit_windows: 0,
                message: Some("no local data found".to_string()),
            },
        ]
    }

    /// The three providers' honest capability descriptors (mirroring the as-built
    /// `capability()` impls) for the Providers tab (T11).
    fn provider_capabilities_fixture() -> Vec<ProviderCapabilityView> {
        vec![
            ProviderCapabilityView {
                provider: ProviderId::ClaudeCode,
                api_cost: DataSource::LocalArtifact,
                subscription_quota: DataSource::SanctionedHook,
                model_mix: DataSource::LocalArtifact,
                auth: AuthMethod::None,
                quota_kinds: vec![LimitKind::FiveHour, LimitKind::Weekly],
            },
            ProviderCapabilityView {
                provider: ProviderId::Codex,
                api_cost: DataSource::LocalArtifact,
                subscription_quota: DataSource::LocalArtifact,
                model_mix: DataSource::LocalArtifact,
                auth: AuthMethod::None,
                quota_kinds: vec![LimitKind::FiveHour, LimitKind::Weekly],
            },
            ProviderCapabilityView {
                provider: ProviderId::Cursor,
                api_cost: DataSource::Unavailable,
                subscription_quota: DataSource::Unavailable,
                model_mix: DataSource::LocalArtifact,
                auth: AuthMethod::None,
                quota_kinds: Vec::new(),
            },
        ]
    }

    /// Detection health spanning the arms: Claude available (no note), Codex missing (a
    /// "no local data" note), Cursor detected (the BETA detect-and-defer note). The Cursor
    /// row pins the card's "detected, never coming soon" requirement.
    fn provider_statuses_for_tab() -> Vec<ProviderStatus> {
        vec![
            ProviderStatus {
                provider: ProviderId::ClaudeCode,
                status: ProviderStatusKind::Available,
                files: 2,
                usage_events: 4,
                focus_rows: 9,
                limit_windows: 2,
                message: None,
            },
            ProviderStatus {
                provider: ProviderId::Codex,
                status: ProviderStatusKind::Missing,
                files: 0,
                usage_events: 0,
                focus_rows: 0,
                limit_windows: 0,
                message: Some("no local data found".to_string()),
            },
            ProviderStatus {
                provider: ProviderId::Cursor,
                status: ProviderStatusKind::Detected,
                files: 1,
                usage_events: 0,
                focus_rows: 0,
                limit_windows: 0,
                message: Some(
                    "BETA - model Composer 2.5 Fast (composer-2.5), logged in; \
                     usage unavailable - no sanctioned source; \
                     quota unavailable - no sanctioned source"
                        .to_string(),
                ),
            },
        ]
    }

    fn priced_now() -> NowSummary {
        let now = utc(2026, 6, 2, 9, 0);
        NowSummary {
            generated_at: now,
            cost_period: range(utc(2026, 6, 1, 0, 0), 7),
            group_by: GroupBy::Model,
            limits: limits(),
            current_costs: vec![
                row("sonnet-4.6", CostLane::Api, 678),
                row("gpt-5.5", CostLane::Api, 1130),
                row("claude-opus-4.7", CostLane::Api, 2410),
                unpriced_row("gpt-5.5", CostLane::SubscriptionEstimate),
                unknown_model_row("mystery-model", CostLane::UnknownAccess),
            ],
            providers: provider_statuses(),
        }
    }

    fn subscription_only_now() -> NowSummary {
        let mut summary = priced_now();
        summary.current_costs = vec![unpriced_row("gpt-5.5", CostLane::SubscriptionEstimate)];
        summary
    }

    fn priced_trends() -> TrendsSummary {
        let now = utc(2026, 6, 2, 9, 0);
        let week_one = range(local_midnight_utc(2026, 6, 1), 7);
        let week_two = range(local_midnight_utc(2026, 6, 8), 7);
        TrendsSummary {
            generated_at: now,
            period: Period::Month,
            group_by: GroupBy::Model,
            buckets: vec![
                costroid_core::TrendBucket {
                    period: week_one,
                    group: GroupKey {
                        kind: GroupBy::Model,
                        value: "claude-opus-4.7".to_string(),
                    },
                    lane: CostLane::Api,
                    totals: totals(9600, 3, 0, 0),
                },
                costroid_core::TrendBucket {
                    period: week_two,
                    group: GroupKey {
                        kind: GroupBy::Model,
                        value: "gpt-5.5".to_string(),
                    },
                    lane: CostLane::Api,
                    totals: totals(4500, 3, 0, 0),
                },
            ],
            totals: vec![
                row("sonnet-4.6", CostLane::Api, 2700),
                row("gpt-5.5", CostLane::Api, 4500),
                row("claude-opus-4.7", CostLane::Api, 9600),
                unpriced_row("gpt-5.5", CostLane::SubscriptionEstimate),
            ],
            providers: provider_statuses(),
        }
    }

    #[test]
    fn cli_mode_selection_keeps_braille_when_no_color_is_set() {
        let env = EnvSnapshot {
            term: Some("xterm-256color".to_string()),
            lang: Some("en_US.UTF-8".to_string()),
            lc_all: None,
            lc_ctype: None,
            no_color: Some("1".to_string()),
        };
        let options = select_render_options(false, true, &env);

        assert_eq!(options.mode, RenderMode::Braille);
        assert!(!options.ansi);
    }

    #[test]
    fn cli_mode_selection_plain_wins_for_pipes_and_flag() {
        let env = EnvSnapshot {
            term: Some("xterm-256color".to_string()),
            lang: Some("en_US.UTF-8".to_string()),
            lc_all: None,
            lc_ctype: None,
            no_color: None,
        };

        assert_eq!(
            select_render_options(true, true, &env),
            RenderOptions::plain()
        );
        assert_eq!(
            select_render_options(false, false, &env),
            RenderOptions::plain()
        );
    }

    #[test]
    fn cli_mode_selection_ascii_is_for_braille_incapability() {
        let env = EnvSnapshot {
            term: Some("dumb".to_string()),
            lang: Some("en_US.UTF-8".to_string()),
            lc_all: None,
            lc_ctype: None,
            no_color: None,
        };
        let options = select_render_options(false, true, &env);

        assert_eq!(options.mode, RenderMode::Ascii);
        assert!(options.ansi);
    }

    #[test]
    fn braille_codepoint_math_matches_design_system() {
        assert_eq!(braille_cell(&[1, 4]), '');
        assert_eq!(braille_full(), '');
        assert_eq!(braille_left_column(), '');
        assert_eq!(braille_light(), '');
    }

    #[test]
    fn meter_segments_keep_braille_fill_visible_without_ansi() {
        let meter = limit_meter(0.42, 6, RenderOptions::braille(false));

        assert_eq!(meter, "⣿⣿⡇⣀⣀⣀");
    }

    #[test]
    fn thresholds_have_non_color_cues() {
        assert_eq!(state_cue(limit_state(0.79)), "");
        assert_eq!(state_cue(limit_state(0.80)), " !");
        assert_eq!(state_cue(limit_state(0.95)), " !!");
        assert_eq!(state_cue(limit_state(1.0)), " !! OVER");
    }

    #[test]
    fn reset_countdown_uses_compact_two_unit_format() {
        assert_eq!(reset_countdown(30), "<1m");
        assert_eq!(reset_countdown(46 * 60), "46m");
        assert_eq!(reset_countdown((2 * 60 + 14) * 60), "2h 14m");
        assert_eq!(reset_countdown((3 * 24 + 4) * 60 * 60), "3d 4h");
    }

    #[test]
    fn money_formatting_marks_estimates() {
        assert_eq!(
            format_money(&Decimal::new(2410, 2), Some("USD"), true),
            "~$24.10"
        );
        assert_eq!(
            format_money(&Decimal::new(184000, 2), Some("USD"), false),
            "$1,840.00"
        );
    }

    #[test]
    fn snapshot_now_braille() {
        insta::assert_snapshot!(render_now(&priced_now(), RenderOptions::braille(true)));
    }

    #[test]
    fn snapshot_now_braille_no_ansi() {
        insta::assert_snapshot!(render_now(&priced_now(), RenderOptions::braille(false)));
    }

    #[test]
    fn snapshot_now_ascii() {
        insta::assert_snapshot!(render_now(&priced_now(), RenderOptions::ascii(false)));
    }

    #[test]
    fn snapshot_now_plain() {
        insta::assert_snapshot!(render_now(&priced_now(), RenderOptions::plain()));
    }

    // ----- T6: the five availability arms + Spend, across all four render modes -----

    #[test]
    fn snapshot_now_all_arms_braille() {
        insta::assert_snapshot!(render_now(&all_arms_now(), RenderOptions::braille(true)));
    }

    #[test]
    fn snapshot_now_all_arms_braille_no_ansi() {
        insta::assert_snapshot!(render_now(&all_arms_now(), RenderOptions::braille(false)));
    }

    #[test]
    fn snapshot_now_all_arms_ascii() {
        insta::assert_snapshot!(render_now(&all_arms_now(), RenderOptions::ascii(false)));
    }

    #[test]
    fn snapshot_now_all_arms_plain() {
        insta::assert_snapshot!(render_now(&all_arms_now(), RenderOptions::plain()));
    }

    #[test]
    fn now_all_arms_render_honestly_in_plain() {
        // The Done-when checks, pinned against drift: plain has no ANSI; Unverified is
        // flagged (never a confident phrase); the freshness stamp appears (UTC, so it is
        // deterministic); the Claude caveat is reachable; Spend shows a dollar pool with no
        // fabricated %; Estimated shows volume + value + "quota % unavailable" and no meter.
        let output = render_now(&all_arms_now(), RenderOptions::plain());
        assert!(
            !output.contains('\u{1b}'),
            "plain now must contain no ANSI escapes: {output}"
        );
        assert!(
            output.contains("96% used ? unverified"),
            "unverified reading must be flagged, never confident: {output}"
        );
        assert!(
            output.contains("as of 08:30"),
            "an aged reading must carry the freshness stamp: {output}"
        );
        assert!(
            output.contains(
                "reflects Claude Code's view; claude.ai chat usage may make true usage higher."
            ),
            "Claude quota lines must carry the chat caveat: {output}"
        );
        assert!(
            output.contains("$18.50 / $20.00 used"),
            "Spend must render a dollar pool, never a fabricated %: {output}"
        );
        assert!(
            output.contains("usage 1,234,567 tokens (~$12.34, estimated), quota % unavailable"),
            "Estimated must show volume + value + unavailable-%: {output}"
        );
        assert!(
            output.contains("usage 5,000 tokens (estimated), quota % unavailable"),
            "unpriced Estimated must show volume alone, never a guessed price: {output}"
        );
    }

    #[test]
    fn now_all_arms_spend_draws_no_meter_in_braille() {
        // A Spend window has no fraction, so it must NOT draw a braille meter — the dollar
        // line stands alone (brief §6/§8).
        let output = render_now(&all_arms_now(), RenderOptions::braille(true));
        let spend_line = output
            .lines()
            .find(|line| line.contains("$18.50 / $20.00 used"))
            .unwrap_or_else(|| panic!("spend line should render: {output}"));
        assert!(
            !spend_line.contains('') && !spend_line.contains(''),
            "spend line must not draw a meter: {spend_line}"
        );
    }

    #[test]
    fn statusline_flags_unverified_when_most_constrained() {
        // The 0.96 Unverified window is the highest fraction, so it is the most-constrained
        // pick — the one-liner must carry the `? unverified` cue, never a confident `!!`
        // (the exact confident-wrong-number failure brief §0/§8 forbids).
        let braille = render_statusline(&all_arms_now(), RenderOptions::braille(true));
        assert!(
            braille.contains("96% ? unverified"),
            "statusline must flag the unverified pick: {braille}"
        );
        assert!(
            !braille.contains("96% !!"),
            "unverified must never render as a confident alarm: {braille}"
        );
        let plain = render_statusline(&all_arms_now(), RenderOptions::plain());
        assert!(plain.contains("? unverified"), "plain statusline: {plain}");
        assert!(
            !plain.contains('\u{1b}'),
            "plain statusline must contain no ANSI: {plain}"
        );
    }

    #[test]
    fn snapshot_statusline_unverified_braille() {
        insta::assert_snapshot!(render_statusline(
            &all_arms_now(),
            RenderOptions::braille(true)
        ));
    }

    #[test]
    fn snapshot_statusline_unverified_plain() {
        insta::assert_snapshot!(render_statusline(&all_arms_now(), RenderOptions::plain()));
    }

    #[test]
    fn freshness_stamp_appears_only_past_the_threshold() {
        let now = utc(2026, 6, 2, 9, 0);
        // Fresh reading (under 10 min) → no stamp; aged reading → "as of HH:MM" in UTC.
        assert_eq!(freshness_stamp(now - Duration::minutes(5), now), "");
        assert_eq!(
            freshness_stamp(now - Duration::minutes(10), now),
            "  as of 08:50"
        );
    }

    #[test]
    fn epoch_sentinel_discloses_unknown_capture_time_never_midnight() {
        // A reading whose capture instant was never recorded (the UNIX-epoch sentinel)
        // must disclose the unknown age — never render the bogus, confident
        // "as of 00:00" the bare arithmetic would produce.
        let now = utc(2026, 6, 2, 9, 0);
        let stamp = freshness_stamp(Utc.timestamp_nanos(0), now);
        assert_eq!(stamp, "  capture time unknown");
        assert!(!stamp.contains("as of"));
    }

    #[test]
    fn plain_paths_carry_the_state_cue() {
        // In --plain (and the plain statusline) there is no color at all, so the
        // textual cue is the ONLY near-limit signal — Available AND Partial must
        // carry it, exactly like the styled paths' `!`/`!!`.
        let generated = utc(2026, 6, 2, 9, 0);
        let available = LimitSummary {
            tool: ProviderId::Codex,
            plan: None,
            kind: LimitKind::FiveHour,
            label: None,
            captured_at: generated,
            availability: LimitAvailability::Available {
                measure: LimitMeasure::TokenFraction(0.97),
                resets_at: generated + Duration::hours(1),
                reset_in_seconds: 3600,
            },
        };
        assert!(plain_limit_line(&available, generated).contains("(critical)"));
        assert!(plain_limit_phrase(&available).contains("(critical)"));

        let partial = LimitSummary {
            availability: LimitAvailability::Partial {
                measure: Some(LimitMeasure::TokenFraction(0.97)),
                resets_at: None,
                reset_in_seconds: None,
                reason: "limit data incomplete".to_string(),
            },
            ..available
        };
        assert!(plain_limit_line(&partial, generated).contains("(critical)"));
        assert!(plain_limit_phrase(&partial).contains("(critical)"));
    }

    #[test]
    fn ascii_mode_output_is_pure_ascii() {
        // RenderMode::Ascii is the fallback for terminals without braille capability —
        // including non-UTF-8 locales — so every Ascii-mode surface (now, trends,
        // frontier with and without API usage, statusline) must be pure ASCII
        // (no ─ rule, no ◆ marker, no em-dash, no braille scatter/meter glyphs).
        let now = render_now(&all_arms_now(), RenderOptions::ascii(false));
        assert!(now.is_ascii(), "ascii now screen must be pure ASCII: {now}");
        let trends = render_trends(&priced_trends(), RenderOptions::ascii(false));
        assert!(
            trends.is_ascii(),
            "ascii trends screen must be pure ASCII: {trends}"
        );
        let frontier = render_frontier(&used_gpt(), RenderOptions::ascii(false));
        assert!(
            frontier.is_ascii(),
            "ascii frontier screen must be pure ASCII: {frontier}"
        );
        let frontier_no_api = render_frontier(&bench_view_for(&[]), RenderOptions::ascii(false));
        assert!(
            frontier_no_api.is_ascii(),
            "ascii frontier screen without API usage must be pure ASCII: {frontier_no_api}"
        );
        let statusline = render_statusline(&all_arms_now(), RenderOptions::ascii(false));
        assert!(
            statusline.is_ascii(),
            "ascii statusline must be pure ASCII: {statusline}"
        );
        let providers = render_providers(
            &provider_capabilities_fixture(),
            &provider_statuses_for_tab(),
            RenderOptions::ascii(false),
        );
        assert!(
            providers.is_ascii(),
            "ascii providers tab must be pure ASCII: {providers}"
        );
        let models = render_models(&models_view_fixture(), RenderOptions::ascii(false));
        assert!(
            models.is_ascii(),
            "ascii models tab must be pure ASCII: {models}"
        );
        let history = render_history(&history_rows_fixture(), RenderOptions::ascii(false));
        assert!(
            history.is_ascii(),
            "ascii history tab must be pure ASCII: {history}"
        );
        let budget = render_budget(&budget_view_fixture(), RenderOptions::ascii(false));
        assert!(
            budget.is_ascii(),
            "ascii budget tab must be pure ASCII: {budget}"
        );
        // Alerts (T17): the inline banner (atop now), the `alerts` list, and the off state must all
        // be pure ASCII in Ascii mode (the `!`/`!!` cues are ASCII; no `─`/`◆`/em-dash).
        let alerts_banner = render_now_with_alerts(
            &all_arms_now(),
            &alerts_fixture(),
            RenderOptions::ascii(false),
        );
        assert!(
            alerts_banner.is_ascii(),
            "ascii alert banner must be pure ASCII: {alerts_banner}"
        );
        let alerts_cmd = render_alerts(&alerts_fixture(), RenderOptions::ascii(false));
        assert!(
            alerts_cmd.is_ascii(),
            "ascii alerts command must be pure ASCII: {alerts_cmd}"
        );
        let alerts_off = render_alerts_off(RenderOptions::ascii(false));
        assert!(
            alerts_off.is_ascii(),
            "ascii alerts-off must be pure ASCII: {alerts_off}"
        );
        // Forecast in Ascii: the projected sparkline glyph (`~`) + the ascii actual ramp must
        // both be pure ASCII, across the projected / insufficient / no-usage states.
        for view in [
            forecast_view_projected_fixture(),
            forecast_view_insufficient_fixture(),
            forecast_view_eta_unavailable_fixture(),
        ] {
            let forecast = render_forecast(&view, RenderOptions::ascii(false));
            assert!(
                forecast.is_ascii(),
                "ascii forecast tab must be pure ASCII: {forecast}"
            );
        }
        // Anomalies in Ascii: the `*` marker + the callouts must be pure ASCII across the flagged,
        // collapse, clean, insufficient, and (T16b) no-usage zero states (the `◆` marker is
        // braille-only).
        for view in [
            anomalies_view_flagged_fixture(),
            anomalies_view_collapse_fixture(),
            anomalies_view_suppressed_multiples_fixture(),
            anomalies_view_clean_fixture(),
            anomalies_view_insufficient_fixture(),
            anomalies_view_no_usage_fixture(),
        ] {
            let anomalies = render_anomalies(&view, RenderOptions::ascii(false));
            assert!(
                anomalies.is_ascii(),
                "ascii anomalies tab must be pure ASCII: {anomalies}"
            );
        }
    }

    #[test]
    fn plain_now_renders_cursor_detected_note_without_color() {
        // Pins the Cursor detect-and-defer note in `--plain` output: the BETA / model /
        // deferred-live wording must render as plain text against drift (§9.7), and —
        // because accessibility forbids relying on color — carry NO ANSI escapes. The
        // message string mirrors what `costroid-core` builds for a detected Cursor.
        let mut summary = priced_now();
        summary.providers = vec![ProviderStatus {
            provider: ProviderId::Cursor,
            status: ProviderStatusKind::Detected,
            files: 1,
            usage_events: 0,
            focus_rows: 0,
            limit_windows: 0,
            message: Some(
                "BETA - model Composer 2.5 Fast (composer-2.5), logged in; \
                 usage unavailable - no sanctioned source; quota unavailable - no sanctioned source"
                    .to_string(),
            ),
        }];

        let output = render_now(&summary, RenderOptions::plain());
        assert!(
            output.contains(
                "provider cursor detected: BETA - model Composer 2.5 Fast (composer-2.5), logged in"
            ),
            "plain now should render the cursor detected note: {output}"
        );
        assert!(output.contains("usage unavailable - no sanctioned source"));
        assert!(output.contains("quota unavailable - no sanctioned source"));
        assert!(
            !output.contains('\u{1b}'),
            "plain output must not contain ANSI escapes"
        );
        assert!(
            output.is_ascii(),
            "plain output must be pure ASCII: {output}"
        );
    }

    #[test]
    fn plain_mode_output_is_pure_ascii() {
        // Plain mode is the accessibility floor (screen readers, dumb pipes, non-UTF-8
        // terminals), so every Costroid-generated byte in it must be ASCII.
        // Provider-supplied names (models, projects) pass through verbatim — the
        // fixtures are ASCII, so a failure here means a Costroid string regressed.
        let outputs = [
            render_now(&all_arms_now(), RenderOptions::plain()),
            render_now(&priced_now(), RenderOptions::plain()),
            render_now(&subscription_only_now(), RenderOptions::plain()),
            render_trends(&priced_trends(), RenderOptions::plain()),
            render_statusline(&priced_now(), RenderOptions::plain()),
            render_statusline(&subscription_only_now(), RenderOptions::plain()),
            render_frontier(&used_gpt(), RenderOptions::plain()),
            render_frontier(&bench_view_for(&[]), RenderOptions::plain()),
            render_providers(
                &provider_capabilities_fixture(),
                &provider_statuses_for_tab(),
                RenderOptions::plain(),
            ),
            render_models(&models_view_fixture(), RenderOptions::plain()),
            render_models(&empty_models_view(), RenderOptions::plain()),
            render_history(&history_rows_fixture(), RenderOptions::plain()),
            render_history(&[], RenderOptions::plain()),
            render_budget(&budget_view_fixture(), RenderOptions::plain()),
            render_budget(&empty_budget_view(), RenderOptions::plain()),
            render_forecast(&forecast_view_projected_fixture(), RenderOptions::plain()),
            render_forecast(
                &forecast_view_insufficient_fixture(),
                RenderOptions::plain(),
            ),
            render_forecast(
                &forecast_view_eta_unavailable_fixture(),
                RenderOptions::plain(),
            ),
            render_anomalies(&anomalies_view_flagged_fixture(), RenderOptions::plain()),
            render_anomalies(&anomalies_view_collapse_fixture(), RenderOptions::plain()),
            render_anomalies(
                &anomalies_view_suppressed_multiples_fixture(),
                RenderOptions::plain(),
            ),
            render_anomalies(&anomalies_view_clean_fixture(), RenderOptions::plain()),
            render_anomalies(
                &anomalies_view_insufficient_fixture(),
                RenderOptions::plain(),
            ),
            render_anomalies(&anomalies_view_no_usage_fixture(), RenderOptions::plain()),
            // Alerts (T17): the inline banner, the `alerts` list (active + clear), the off state.
            render_now_with_alerts(&all_arms_now(), &alerts_fixture(), RenderOptions::plain()),
            render_alerts(&alerts_fixture(), RenderOptions::plain()),
            render_alerts(&[], RenderOptions::plain()),
            render_alerts_off(RenderOptions::plain()),
        ];
        for output in outputs {
            assert!(
                output.is_ascii(),
                "plain output must be pure ASCII: {output}"
            );
        }
    }

    #[test]
    fn snapshot_now_subscription_only_has_explicit_empty_api_state() {
        insta::assert_snapshot!(render_now(
            &subscription_only_now(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_trends_braille_with_ansi() {
        insta::assert_snapshot!(render_trends(
            &priced_trends(),
            RenderOptions::braille(true)
        ));
    }

    #[test]
    fn snapshot_trends_braille() {
        insta::assert_snapshot!(render_trends(
            &priced_trends(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_trends_ascii() {
        insta::assert_snapshot!(render_trends(&priced_trends(), RenderOptions::ascii(false)));
    }

    #[test]
    fn snapshot_trends_plain() {
        insta::assert_snapshot!(render_trends(&priced_trends(), RenderOptions::plain()));
    }

    #[test]
    fn snapshot_providers_braille() {
        insta::assert_snapshot!(render_providers(
            &provider_capabilities_fixture(),
            &provider_statuses_for_tab(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_providers_ascii() {
        insta::assert_snapshot!(render_providers(
            &provider_capabilities_fixture(),
            &provider_statuses_for_tab(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_providers_plain() {
        insta::assert_snapshot!(render_providers(
            &provider_capabilities_fixture(),
            &provider_statuses_for_tab(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn providers_render_is_honest_and_cursor_is_detected_never_coming_soon() {
        let output = render_providers(
            &provider_capabilities_fixture(),
            &provider_statuses_for_tab(),
            RenderOptions::plain(),
        );
        // Author-written DataSource/AuthMethod copy.
        assert!(output.contains("api cost: from local logs"));
        assert!(
            output.contains("quota: from the statusLine capture; run setup-statusline (5h, wk)")
        );
        assert!(output.contains("auth: no login required"));
        // Codex's quota is local, with both windows.
        assert!(output.contains("quota: from local logs (5h, wk)"));
        // Cursor: detected (never Missing/"coming soon"), both unavailable lanes honest.
        assert!(output.contains("cursor (detected):"));
        assert!(output.contains("api cost: no sanctioned source"));
        assert!(output.contains("quota: no sanctioned source"));
        assert!(!output.contains("coming soon"));
        // Detection health: the missing Codex carries its note; the available Claude none.
        assert!(output.contains("note: no local data found"));
    }

    #[test]
    fn providers_document_is_monochrome() {
        // The Providers tab is informational, so amber/red (Warn/Critical, reserved for the
        // near-limit/over-budget state) must never appear — bold (Strong) headers are an
        // allowed non-color cue, mirroring `frontier_document_is_monochrome`.
        let doc = render_providers_document(
            &provider_capabilities_fixture(),
            &provider_statuses_for_tab(),
            RenderOptions::braille(true),
        );
        for line in &doc.lines {
            for span in &line.spans {
                assert!(
                    !matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical),
                    "providers tab must be monochrome (amber/red are reserved): {span:?}"
                );
            }
        }
    }

    fn models_view_fixture() -> ModelsView {
        // gpt-5.5: on a benchmark frontier, with a computed equal-volume re-pricing delta
        // (a cheaper target) — the spend + tokens + standing + repricing all-arms case.
        let on_frontier = OverlayModel {
            model_id: "gpt-5.5".to_string(),
            raw_model: "gpt-5.5".to_string(),
            billed_cost: Decimal::new(1234, 2),
            tokens: costroid_core::TokenTotals {
                input: 1_000,
                output: 2_000,
                cache_read: 500,
                cache_write: 0,
            },
            appearances: vec![costroid_core::OverlayAppearance {
                benchmark_name: "swe-bench".to_string(),
                score_pct: Decimal::new(72, 0),
                standing: FrontierStanding::OnFrontier,
            }],
            repricing: vec![RepricingDelta {
                target_model_id: "claude-haiku-4".to_string(),
                target_label: "claude haiku 4".to_string(),
                delta_usd: Decimal::new(-400, 2),
                status: RepricingStatus::Computed,
                on_frontier_in: vec!["swe-bench".to_string()],
            }],
            fully_priced: true,
        };
        // claude-opus-4: benchmarked but dominated; partial pricing (a missing-price row) —
        // exercises the dominated standing + the honest pricing-coverage badge.
        let dominated = OverlayModel {
            model_id: "claude-opus-4".to_string(),
            raw_model: "claude-opus-4".to_string(),
            billed_cost: Decimal::new(880, 2),
            tokens: costroid_core::TokenTotals::default(),
            appearances: vec![costroid_core::OverlayAppearance {
                benchmark_name: "swe-bench".to_string(),
                score_pct: Decimal::new(70, 0),
                standing: FrontierStanding::Dominated {
                    by: "gpt-5.5".to_string(),
                },
            }],
            repricing: Vec::new(),
            fully_priced: false,
        };
        ModelsView {
            generated_at: utc(2026, 6, 2, 9, 0),
            // Pre-sorted by spend desc, as `models_view` emits them.
            models: vec![
                ModelRow {
                    model: "gpt-5.5".to_string(),
                    totals: totals(1234, 3, 0, 0),
                    overlay: Some(on_frontier),
                },
                ModelRow {
                    model: "claude-opus-4".to_string(),
                    totals: totals(880, 2, 1, 0),
                    overlay: Some(dominated),
                },
                // mystery-model: NOT on any benchmark (no overlay match) — the gap case.
                ModelRow {
                    model: "mystery-model".to_string(),
                    totals: totals(210, 3, 0, 0),
                    overlay: None,
                },
            ],
            no_api_usage: false,
            disclaimer: costroid_core::BenchDisclaimer {
                note: "~ cost-only comparison at equal token volume; not a quality claim.",
                pricing_as_of: "2026-05-01".to_string(),
            },
            providers: Vec::new(),
        }
    }

    fn empty_models_view() -> ModelsView {
        ModelsView {
            generated_at: utc(2026, 6, 2, 9, 0),
            models: Vec::new(),
            no_api_usage: true,
            disclaimer: costroid_core::BenchDisclaimer {
                note: "~ cost-only comparison at equal token volume; not a quality claim.",
                pricing_as_of: "2026-05-01".to_string(),
            },
            providers: Vec::new(),
        }
    }

    #[test]
    fn snapshot_models_braille() {
        insta::assert_snapshot!(render_models(
            &models_view_fixture(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_models_ascii() {
        insta::assert_snapshot!(render_models(
            &models_view_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_models_plain() {
        insta::assert_snapshot!(render_models(
            &models_view_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_models_no_api_usage() {
        insta::assert_snapshot!(render_models(&empty_models_view(), RenderOptions::plain()));
    }

    #[test]
    fn models_render_shows_spend_tokens_and_standing_unbenchmarked_is_a_gap() {
        let output = render_models(&models_view_fixture(), RenderOptions::plain());
        // Spend is ALWAYS an estimate (the `~` hedge).
        assert!(output.contains("gpt-5.5: spent ~$12.34"));
        // Token mix is surfaced.
        assert!(output.contains("tokens: 10 in / 20 out / 30 cache"));
        // Frontier standing per benchmark.
        assert!(output.contains("frontier: swe-bench 72% - on frontier"));
        assert!(output.contains("frontier: swe-bench 70% - off (dominated by gpt-5.5)"));
        // Equal-volume re-pricing, cost-only (INFORM, never PRESCRIBE).
        assert!(output.contains("claude-haiku-4 costs about ~$4.00 less at equal volume"));
        assert!(!output.to_lowercase().contains("switch to"));
        // Partial pricing is surfaced honestly, never hidden.
        assert!(output.contains("claude-opus-4: spent ~$8.80 (partial pricing)"));
        // An un-benchmarked model is a GAP, never a guessed standing.
        assert!(output.contains("mystery-model: spent ~$2.10"));
        assert!(output.contains("frontier: not benchmarked"));
        // The cost-only hedge note is footnoted.
        assert!(output.contains("cost-only comparison at equal token volume"));
    }

    #[test]
    fn models_document_is_monochrome() {
        // The Models tab is advisory, so amber/red (Warn/Critical, reserved for the
        // near-limit/over-budget state) must never appear — bold (Strong) spend is an allowed
        // non-color cue, mirroring `frontier_document_is_monochrome`.
        let doc = render_models_document(&models_view_fixture(), RenderOptions::braille(true));
        for line in &doc.lines {
            for span in &line.spans {
                assert!(
                    !matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical),
                    "models tab must be monochrome (amber/red are reserved): {span:?}"
                );
            }
        }
    }

    // ----- history surface (T13) -----

    /// One FOCUS meter row for the History fixtures, priced like production then overwritten
    /// with a known cost — mirrors the tui.rs `sample_record` helper. `tokens` lands on
    /// `x_ConsumedTokens` (the raw count History reads); `cents` on `billed_cost`.
    fn history_record(
        model: &str,
        when: DateTime<Utc>,
        token_type: costroid_focus::TokenType,
        tokens: u64,
        cents: i64,
        access: costroid_focus::FocusAccessPath,
    ) -> FocusRecord {
        let input = costroid_focus::UnpricedUsage {
            timestamp: when,
            tool: "codex".to_string(),
            model: model.to_string(),
            token_type,
            token_count: tokens,
            project: Some("alpha-app".to_string()),
            access_path: access,
            service_name: "OpenAI API".to_string(),
            service_provider_name: "OpenAI".to_string(),
            host_provider_name: "OpenAI".to_string(),
            invoice_issuer_name: "OpenAI".to_string(),
            billing_currency: costroid_focus::DEFAULT_BILLING_CURRENCY.to_string(),
        };
        let mut record = match FocusRecord::unpriced_usage(input) {
            Ok(record) => record,
            Err(error) => panic!("history fixture record should be valid: {error}"),
        };
        let cost = Decimal::new(cents, 2);
        record.billed_cost = cost;
        record.effective_cost = cost;
        record.x_pricing_status = "priced".to_string();
        record
    }

    /// A two-lane fixture: a newer API turn (priced) + an older subscription turn (no per-token
    /// bill), so the snapshots prove newest-first ordering and the api-only cost column.
    fn history_rows_fixture() -> Vec<FocusRecord> {
        vec![
            // Deliberately oldest first in source order, to prove the render sorts newest-first.
            history_record(
                "claude-sonnet-4",
                utc(2026, 6, 2, 9, 0),
                costroid_focus::TokenType::Output,
                500_000,
                0,
                costroid_focus::FocusAccessPath::Subscription,
            ),
            history_record(
                "gpt-5.5",
                utc(2026, 6, 2, 10, 30),
                costroid_focus::TokenType::Output,
                1_000_000,
                1234,
                costroid_focus::FocusAccessPath::Api,
            ),
        ]
    }

    #[test]
    fn snapshot_history_braille() {
        insta::assert_snapshot!(render_history(
            &history_rows_fixture(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_history_ascii() {
        insta::assert_snapshot!(render_history(
            &history_rows_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_history_plain() {
        insta::assert_snapshot!(render_history(
            &history_rows_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_history_empty() {
        insta::assert_snapshot!(render_history(&[], RenderOptions::plain()));
    }

    #[test]
    fn history_lists_records_newest_first_with_raw_usage_and_api_only_cost() {
        let output = render_history(&history_rows_fixture(), RenderOptions::plain());

        // Newest-first: the 10:30 API turn precedes the 09:00 subscription turn.
        let index_of = |needle: &str| match output.find(needle) {
            Some(at) => at,
            None => panic!("expected `{needle}` in history output: {output}"),
        };
        assert!(
            index_of("gpt-5.5") < index_of("claude-sonnet-4"),
            "records render newest-first: {output}"
        );

        // Usage comes from x_ConsumedTokens (the raw count), never a nulled ConsumedQuantity.
        assert!(output.contains("1,000,000 output"));
        assert!(output.contains("500,000 output"));

        // Cost is shown ONLY for API rows, always estimated (the `~` hedge); a subscription
        // turn carries the access-path label but no per-token dollar figure.
        assert!(output.contains("api  ~$12.34"));
        assert!(output.contains("claude-sonnet-4  500,000 output  subscription"));
        assert!(!output.contains("subscription  ~$"));

        // The count/scope header and the unchanged-export pointer are present.
        assert!(output.contains("scope: 2 records, newest first (all time)"));
        assert!(output.contains("costroid export --format json|csv"));
    }

    #[test]
    fn history_empty_list_renders_without_panicking() {
        let output = render_history(&[], RenderOptions::braille(false));
        assert!(output.contains("scope: 0 records, newest first (all time)"));
        assert!(output.contains("no usage recorded yet"));
    }

    #[test]
    fn history_document_is_monochrome() {
        // The History tab is informational, so amber/red (Warn/Critical, reserved for the
        // near-limit state) must never appear — the bold (Strong) model is an allowed cue.
        let doc = render_history_document(&history_rows_fixture(), RenderOptions::braille(true));
        for line in &doc.lines {
            for span in &line.spans {
                assert!(
                    !matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical),
                    "history tab must be monochrome (amber/red are reserved): {span:?}"
                );
            }
        }
    }

    // ----- budget surface (T14) -----

    fn budget_row_fixture(
        scope: BudgetScope,
        spent: i64,
        target: i64,
        fraction: f64,
        over: Option<i64>,
        pace: BudgetPace,
    ) -> BudgetRow {
        BudgetRow {
            scope,
            target_usd: Decimal::new(target, 2),
            spent_usd: Decimal::new(spent, 2),
            fraction,
            over_by_usd: over.map(|cents| Decimal::new(cents, 2)),
            pace,
        }
    }

    /// A budget view with an over-budget tool, a near-budget total, a comfortable tool, and a
    /// flat-fee tool withheld from comparison — so the snapshots prove the OVER cue, the
    /// amber/red-with-text states, the pace line, and the §170 excluded-tool note in one fixture.
    fn budget_view_fixture() -> BudgetView {
        BudgetView {
            generated_at: utc(2026, 6, 16, 12, 0),
            rows: vec![
                budget_row_fixture(
                    BudgetScope::Tool("codex".to_string()),
                    6_000,
                    5_000,
                    1.2,
                    Some(1_000),
                    BudgetPace::OverBudget,
                ),
                budget_row_fixture(
                    BudgetScope::Total,
                    8_400,
                    10_000,
                    0.84,
                    None,
                    BudgetPace::AheadOfPace,
                ),
                budget_row_fixture(
                    BudgetScope::Tool("claude-code".to_string()),
                    1_500,
                    6_000,
                    0.25,
                    None,
                    BudgetPace::OnTrack,
                ),
            ],
            excluded_tools: vec![BudgetExcludedTool {
                tool: "cursor".to_string(),
                reason: BudgetExclusion::FlatFeeSubscription,
            }],
            no_budget_set: false,
            spent_total_usd: Decimal::new(8_400, 2),
            month_elapsed_fraction: 0.5,
        }
    }

    fn empty_budget_view() -> BudgetView {
        BudgetView {
            generated_at: utc(2026, 6, 16, 12, 0),
            rows: Vec::new(),
            excluded_tools: Vec::new(),
            no_budget_set: true,
            spent_total_usd: Decimal::ZERO,
            month_elapsed_fraction: 0.5,
        }
    }

    #[test]
    fn snapshot_budget_braille() {
        insta::assert_snapshot!(render_budget(
            &budget_view_fixture(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_budget_ascii() {
        insta::assert_snapshot!(render_budget(
            &budget_view_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_budget_plain() {
        insta::assert_snapshot!(render_budget(
            &budget_view_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_budget_no_budget_set() {
        insta::assert_snapshot!(render_budget(&empty_budget_view(), RenderOptions::plain()));
    }

    #[test]
    fn budget_over_by_below_a_cent_renders_less_than_a_cent_not_zero() {
        // A real sub-cent overshoot (core's strict `spent > target`): `format_money` rounds it to
        // "~$0.00", so `format_over_by` shows the honest "<$0.01" instead — guarding the
        // self-contradictory "!! OVER, over by ~$0.00".
        assert_eq!(format_over_by(&Decimal::new(3, 4)), "<$0.01"); // $0.0003 over
        assert_eq!(format_over_by(&Decimal::new(4, 3)), "<$0.01"); // $0.004 over
                                                                   // A whole-cent or larger overshoot still uses the ~-hedged dollar amount.
        assert_eq!(format_over_by(&Decimal::new(1, 2)), "~$0.01"); // $0.01
        assert_eq!(format_over_by(&Decimal::new(1_000, 2)), "~$10.00"); // $10.00
    }

    #[test]
    fn budget_over_row_renders_over_cue_and_overshoot_amount() {
        let output = render_budget(&budget_view_fixture(), RenderOptions::plain());
        // The over-cap state spells out OVER (a non-color cue) + the dollar overshoot.
        assert!(
            output.contains("codex: ~$60.00 / ~$50.00 budget (120%)"),
            "{output}"
        );
        assert!(output.contains("!! OVER, over by ~$10.00"), "{output}");
        // A comfortable budget shows no alarm cue.
        assert!(
            output.contains("claude-code: ~$15.00 / ~$60.00 budget (25%)"),
            "{output}"
        );
        assert!(
            !output.contains("claude-code: ~$15.00 / ~$60.00 budget (25%) !"),
            "{output}"
        );
        // The pace cue is present.
        assert!(
            output.contains("pace: 120% used vs 50% of month elapsed (over budget)"),
            "{output}"
        );
    }

    #[test]
    fn budget_flat_fee_tool_gets_no_dollar_comparison() {
        let output = render_budget(&budget_view_fixture(), RenderOptions::plain());
        assert!(
            output.contains("cursor: flat-fee subscription - no $ budget applies (not API-billed)"),
            "{output}"
        );
        // No $ comparison line for the flat-fee tool.
        assert!(
            !output.contains("cursor: ~$"),
            "flat-fee tool must not show a $ budget: {output}"
        );
    }

    #[test]
    fn budget_exactly_at_budget_reads_at_budget_not_over() {
        // The exactly-100% boundary: spent == target (fraction 1.0, over_by None). The row must
        // read "at budget" (Critical), NEVER "OVER" or "over by ~$0.00" — the cue, the missing
        // over-by line, and a non-over pace must agree (the budget_state boundary fix).
        let view = BudgetView {
            generated_at: utc(2026, 6, 16, 12, 0),
            rows: vec![budget_row_fixture(
                BudgetScope::Tool("codex".to_string()),
                5_000,
                5_000,
                1.0,
                None,
                BudgetPace::AheadOfPace,
            )],
            excluded_tools: Vec::new(),
            no_budget_set: false,
            spent_total_usd: Decimal::new(5_000, 2),
            month_elapsed_fraction: 0.5,
        };
        let output = render_budget(&view, RenderOptions::plain());
        assert!(
            output.contains("codex: ~$50.00 / ~$50.00 budget (100%) !! at budget"),
            "{output}"
        );
        assert!(
            !output.contains("OVER"),
            "exactly-at-budget must not say OVER: {output}"
        );
        assert!(
            !output.contains("over by"),
            "exactly-at-budget has no overshoot: {output}"
        );
    }

    #[test]
    fn budget_not_api_billed_tool_gets_no_dollar_comparison_or_subscription_claim() {
        // A budgeted tool with only unclassified (UnknownAccess) usage gets the honest
        // "not API-billed" note — no $ comparison, and (unlike the subscription case) no
        // "subscription" assertion we can't back up.
        let view = BudgetView {
            generated_at: utc(2026, 6, 16, 12, 0),
            rows: Vec::new(),
            excluded_tools: vec![BudgetExcludedTool {
                tool: "codex".to_string(),
                reason: BudgetExclusion::NotApiBilled,
            }],
            no_budget_set: false,
            spent_total_usd: Decimal::ZERO,
            month_elapsed_fraction: 0.5,
        };
        let output = render_budget(&view, RenderOptions::plain());
        assert!(
            output.contains("codex: no API-billed usage - a $ budget tracks API spend only"),
            "{output}"
        );
        assert!(!output.contains("codex: ~$"), "no $ comparison: {output}");
        assert!(
            !output.contains("subscription"),
            "no unbacked subscription claim: {output}"
        );
    }

    #[test]
    fn budget_empty_state_points_to_config_file() {
        let output = render_budget(&empty_budget_view(), RenderOptions::plain());
        assert!(
            output.contains("no budget set - set targets in ~/.config/costroid/config.toml"),
            "{output}"
        );
        // The copy-paste schema is shown so the user knows the format.
        assert!(output.contains("[budget]"));
        assert!(output.contains("total_monthly_usd = 100.00"));
        assert!(output.contains("[budget.per_tool]"));
    }

    #[test]
    fn budget_over_state_pairs_color_with_a_textual_cue() {
        // The Budget tab is the ONE tab allowed amber/red — but color is NEVER alone. Where a
        // span is styled Warn/Critical, the same visual line must carry a non-color cue (!/!!/OVER).
        let doc = render_budget_document(&budget_view_fixture(), RenderOptions::braille(true));
        let mut saw_colored = false;
        for line in &doc.lines {
            let colored = line
                .spans
                .iter()
                .any(|span| matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical));
            if colored {
                saw_colored = true;
                let text: String = line
                    .spans
                    .iter()
                    .map(|span| span.content.as_str())
                    .collect();
                assert!(
                    text.contains('!'),
                    "a colored budget line must also carry a non-color cue: {text:?}"
                );
            }
        }
        assert!(
            saw_colored,
            "the over/near fixture should exercise an amber/red state"
        );
    }

    // ----- Alerts (T17) -----

    /// One of each alert class/level — a CRITICAL quota, an over-budget, a WARN quota — ordered
    /// critical-tier first, exactly as `active_alerts` would emit them.
    fn alerts_fixture() -> Vec<Alert> {
        vec![
            Alert::Quota {
                tool: ProviderId::ClaudeCode,
                kind: LimitKind::FiveHour,
                level: AlertLevel::Critical,
                fraction: 0.97,
                reset_in_seconds: 2_460, // 41m
            },
            Alert::Budget {
                scope: BudgetScope::Tool("codex".to_string()),
                spent_usd: Decimal::new(6_000, 2),
                target_usd: Decimal::new(5_000, 2),
                over_by_usd: Decimal::new(1_000, 2),
            },
            Alert::Quota {
                tool: ProviderId::ClaudeCode,
                kind: LimitKind::Weekly,
                level: AlertLevel::Warn,
                fraction: 0.82,
                reset_in_seconds: 187_200, // 2d 4h
            },
        ]
    }

    #[test]
    fn render_thresholds_are_the_one_core_source_never_forked() {
        // The meter/budget WARN/CRITICAL fractions ALIAS the core consts, and the alert detector's
        // defaults are those same consts — so the meter color, the budget state, and the alert that
        // fires can never drift to different numbers (the T17 "one source, not a forked set" rule).
        assert_eq!(WARN_FRACTION, costroid_core::ALERT_WARN_FRACTION);
        assert_eq!(CRITICAL_FRACTION, costroid_core::ALERT_CRITICAL_FRACTION);
        let defaults = costroid_core::AlertThresholds::default();
        assert_eq!(WARN_FRACTION, defaults.quota_warn_fraction);
        assert_eq!(CRITICAL_FRACTION, defaults.quota_critical_fraction);
    }

    #[test]
    fn snapshot_alerts_now_banner_braille() {
        insta::assert_snapshot!(render_now_with_alerts(
            &priced_now(),
            &alerts_fixture(),
            RenderOptions::braille(true)
        ));
    }

    #[test]
    fn snapshot_alerts_now_banner_ascii() {
        insta::assert_snapshot!(render_now_with_alerts(
            &priced_now(),
            &alerts_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_alerts_now_banner_plain() {
        insta::assert_snapshot!(render_now_with_alerts(
            &priced_now(),
            &alerts_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn alerts_banner_empty_is_byte_identical_to_plain_now() {
        // The off/clear state: no active alert => no banner => the now view is unchanged.
        for options in [
            RenderOptions::plain(),
            RenderOptions::braille(false),
            RenderOptions::ascii(false),
        ] {
            assert_eq!(
                render_now_with_alerts(&priced_now(), &[], options),
                render_now(&priced_now(), options),
                "an empty alert slice must leave the now view unchanged"
            );
        }
    }

    #[test]
    fn snapshot_alerts_command_plain() {
        insta::assert_snapshot!(render_alerts(&alerts_fixture(), RenderOptions::plain()));
    }

    #[test]
    fn snapshot_alerts_command_braille() {
        insta::assert_snapshot!(render_alerts(
            &alerts_fixture(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn alerts_command_clear_state_is_honest() {
        let output = render_alerts(&[], RenderOptions::plain());
        assert!(output.contains("no active alerts"), "{output}");
        assert!(output.is_ascii(), "{output}");
    }

    #[test]
    fn alerts_command_off_state_points_at_config() {
        let output = render_alerts_off(RenderOptions::plain());
        assert!(output.contains("alerts are off"), "{output}");
        assert!(
            output.contains("~/.config/costroid/config.toml"),
            "{output}"
        );
        assert!(output.contains("[alerts]"), "{output}");
        assert!(output.contains("enabled = true"), "{output}");
        assert!(output.is_ascii(), "{output}");
    }

    #[test]
    fn quota_alert_copy_uses_quota_extension_framing_never_money() {
        // Voice rule: a quota alert frames the limit/quota, NEVER dollars ("save money").
        let quota = Alert::Quota {
            tool: ProviderId::ClaudeCode,
            kind: LimitKind::Weekly,
            level: AlertLevel::Warn,
            fraction: 0.82,
            reset_in_seconds: 187_200,
        };
        let sentence = alert_sentence(&quota);
        assert_eq!(sentence, "claude code weekly limit at 82%, resets in 2d 4h");
        assert!(
            !sentence.contains('$'),
            "quota copy must not use money framing: {sentence}"
        );
    }

    #[test]
    fn budget_alert_copy_is_dollars() {
        let budget = Alert::Budget {
            scope: BudgetScope::Total,
            spent_usd: Decimal::new(11_000, 2),
            target_usd: Decimal::new(10_000, 2),
            over_by_usd: Decimal::new(1_000, 2),
        };
        assert_eq!(
            alert_sentence(&budget),
            "total budget over by ~$10.00, spent ~$110.00 of ~$100.00"
        );
    }

    #[test]
    fn forecast_alert_copy_is_framed_as_a_projection() {
        // Advisory (T17b): the copy says "projected", never asserts a present overrun, and every $
        // figure is `~`-hedged (a local estimate).
        let forecast = Alert::Forecast {
            projected_month_usd: Decimal::new(15_000, 2),
            target_usd: Decimal::new(10_000, 2),
            projected_over_by_usd: Decimal::new(5_000, 2),
        };
        let sentence = alert_sentence(&forecast);
        assert_eq!(
            sentence,
            "total budget projected over by ~$50.00, ~$150.00 projected of ~$100.00"
        );
        assert!(
            sentence.contains("projected"),
            "forecast copy must read as a projection: {sentence}"
        );
        assert!(sentence.is_ascii(), "{sentence}");
    }

    #[test]
    fn spend_spike_alert_copy_cites_the_norm() {
        // Advisory (T17b): "~Nx your $Y norm" when the multiple reads honestly, both figures hedged.
        let spike = Alert::SpendSpike {
            date: anomaly_date(2026, 6, 16),
            value_usd: Decimal::new(2_000, 2),
            baseline_median_usd: Decimal::new(250, 2),
            magnitude: Some(Decimal::new(80, 1)), // 8.0x
        };
        let sentence = alert_sentence(&spike);
        assert_eq!(
            sentence,
            "daily spend spike: ~$20.00 on Jun 16, ~8.0x your ~$2.50 norm"
        );
        assert!(sentence.is_ascii(), "{sentence}");
    }

    #[test]
    fn spend_spike_alert_copy_is_descriptive_when_the_median_displays_zero() {
        // A "~Nx your $0.00 norm" would be self-contradictory — fall back to "well above" (mirrors
        // the Anomalies tab honesty guard).
        let spike = Alert::SpendSpike {
            date: anomaly_date(2026, 6, 16),
            value_usd: Decimal::new(500, 2),
            baseline_median_usd: Decimal::ZERO,
            magnitude: None,
        };
        let sentence = alert_sentence(&spike);
        assert_eq!(
            sentence,
            "daily spend spike: ~$5.00 on Jun 16, well above your ~$0.00 norm"
        );
    }

    #[test]
    fn advisory_alerts_are_non_color_cued_and_ascii_in_plain() {
        // Once opted in, the advisory alerts render like any alert: a distinct spelled-out plain
        // cue (never color alone) and pure ASCII.
        let advisory = vec![
            Alert::Forecast {
                projected_month_usd: Decimal::new(15_000, 2),
                target_usd: Decimal::new(10_000, 2),
                projected_over_by_usd: Decimal::new(5_000, 2),
            },
            Alert::SpendSpike {
                date: anomaly_date(2026, 6, 16),
                value_usd: Decimal::new(2_000, 2),
                baseline_median_usd: Decimal::new(250, 2),
                magnitude: Some(Decimal::new(80, 1)),
            },
        ];
        // Distinct plain cues, neither colliding with the hard-crossing cues.
        assert_eq!(alert_plain_cue(&advisory[0]), " (projected over budget)");
        assert_eq!(alert_plain_cue(&advisory[1]), " (spend spike)");
        // Neither is critical-tier (advisory = the lighter heads-up tier).
        assert!(!advisory[0].is_critical() && !advisory[1].is_critical());
        let plain = render_alerts(&advisory, RenderOptions::plain());
        assert!(plain.contains("(projected over budget)"), "{plain}");
        assert!(plain.contains("(spend spike)"), "{plain}");
        assert!(
            plain.is_ascii(),
            "plain advisory output must be ASCII: {plain}"
        );
    }

    #[test]
    fn alert_check_line_and_exit_code() {
        // No alerts: exit 0, no line (the caller prints nothing — a clear run is silent).
        assert_eq!(alerts_check_exit_code(&[]), 0);
        assert_eq!(alert_check_line(&[]), "");
        // One alert: exit 1, the sentence verbatim, ASCII.
        let one = vec![alerts_fixture().remove(0)];
        assert_eq!(alerts_check_exit_code(&one), 1);
        assert_eq!(
            alert_check_line(&one),
            "costroid: claude code 5-hour limit at 97%, resets in 41m"
        );
        // Several: exit 1, a count + the most-pressing headline; always pure ASCII.
        let several = alerts_fixture();
        assert_eq!(alerts_check_exit_code(&several), 1);
        let line = alert_check_line(&several);
        assert!(line.contains("3 active alerts"), "{line}");
        assert!(
            line.contains("most pressing: claude code 5-hour limit at 97%"),
            "{line}"
        );
        assert!(line.is_ascii(), "the cron line must be pure ASCII: {line}");
    }

    #[test]
    fn alerts_banner_pairs_color_with_a_textual_cue() {
        // Like Budget: amber/red is allowed, but a colored line ALWAYS carries a `!`/`!!` cue.
        let mut doc = StyledDocument::new();
        push_alert_banner(&mut doc, &alerts_fixture(), RenderOptions::braille(true));
        let mut saw_colored = false;
        for line in &doc.lines {
            let colored = line
                .spans
                .iter()
                .any(|span| matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical));
            if colored {
                saw_colored = true;
                let text: String = line
                    .spans
                    .iter()
                    .map(|span| span.content.as_str())
                    .collect();
                assert!(
                    text.contains('!'),
                    "a colored alert line must carry a non-color cue: {text:?}"
                );
            }
        }
        assert!(
            saw_colored,
            "the fixture should exercise an amber/red alert state"
        );
    }

    // ----- Forecast tab (T15) -----

    fn forecast_day(year: i32, month: u32, day: u32, cents: i64) -> ForecastDay {
        ForecastDay {
            date: match NaiveDate::from_ymd_opt(year, month, day) {
                Some(date) => date,
                None => panic!("test date should be valid"),
            },
            spent_usd: Decimal::new(cents, 2),
        }
    }

    /// A projected forecast: June 16 (UTC), 16 of 30 days elapsed, ~$37.50 projected, with one
    /// of each quota outcome (projected-hit Friday, resets-first, ETA-unavailable).
    fn forecast_view_projected_fixture() -> ForecastView {
        ForecastView {
            generated_at: utc(2026, 6, 16, 12, 0),
            no_api_usage: false,
            spend: SpendForecast::Projected {
                projected_month_usd: Decimal::new(3_750, 2),
                spend_to_date_usd: Decimal::new(2_000, 2),
                days_elapsed: 16,
                days_in_month: 30,
            },
            daily_actuals: vec![
                forecast_day(2026, 6, 5, 500),
                forecast_day(2026, 6, 10, 1_000),
                forecast_day(2026, 6, 14, 500),
            ],
            quota_etas: vec![
                QuotaEta {
                    tool: ProviderId::ClaudeCode,
                    kind: LimitKind::Weekly,
                    // 2026-06-19 is a Friday — pins the card's "~Friday" headline.
                    outcome: QuotaEtaOutcome::ProjectedHit {
                        at: utc(2026, 6, 19, 8, 0),
                        fraction: 0.85,
                    },
                },
                QuotaEta {
                    tool: ProviderId::ClaudeCode,
                    kind: LimitKind::FiveHour,
                    outcome: QuotaEtaOutcome::ResetsFirst {
                        resets_at: utc(2026, 6, 16, 14, 0),
                        fraction: 0.2,
                    },
                },
                QuotaEta {
                    tool: ProviderId::Codex,
                    kind: LimitKind::Weekly,
                    outcome: QuotaEtaOutcome::Unavailable {
                        reason: QuotaEtaUnavailable::ReadingNotProjectable,
                    },
                },
            ],
        }
    }

    /// Below the 3-day floor: only 2 of 30 days elapsed, so the projection is suppressed.
    fn forecast_view_insufficient_fixture() -> ForecastView {
        ForecastView {
            generated_at: utc(2026, 6, 2, 12, 0),
            no_api_usage: false,
            spend: SpendForecast::InsufficientData {
                spend_to_date_usd: Decimal::new(500, 2),
                days_elapsed: 2,
                days_in_month: 30,
                min_days: 3,
            },
            daily_actuals: vec![forecast_day(2026, 6, 1, 500)],
            quota_etas: vec![QuotaEta {
                tool: ProviderId::Codex,
                kind: LimitKind::Weekly,
                outcome: QuotaEtaOutcome::ResetsFirst {
                    resets_at: utc(2026, 6, 5, 0, 0),
                    fraction: 0.1,
                },
            }],
        }
    }

    /// Every quota window degraded to a typed "ETA unavailable" — no API usage either.
    fn forecast_view_eta_unavailable_fixture() -> ForecastView {
        ForecastView {
            generated_at: utc(2026, 6, 16, 12, 0),
            no_api_usage: true,
            spend: SpendForecast::Projected {
                projected_month_usd: Decimal::ZERO,
                spend_to_date_usd: Decimal::ZERO,
                days_elapsed: 16,
                days_in_month: 30,
            },
            daily_actuals: Vec::new(),
            quota_etas: vec![
                QuotaEta {
                    tool: ProviderId::ClaudeCode,
                    kind: LimitKind::Weekly,
                    outcome: QuotaEtaOutcome::Unavailable {
                        reason: QuotaEtaUnavailable::ReadingNotProjectable,
                    },
                },
                QuotaEta {
                    tool: ProviderId::Codex,
                    kind: LimitKind::FiveHour,
                    outcome: QuotaEtaOutcome::Unavailable {
                        reason: QuotaEtaUnavailable::WindowJustStarted,
                    },
                },
            ],
        }
    }

    #[test]
    fn snapshot_forecast_braille() {
        insta::assert_snapshot!(render_forecast(
            &forecast_view_projected_fixture(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_forecast_ascii() {
        insta::assert_snapshot!(render_forecast(
            &forecast_view_projected_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_forecast_plain() {
        insta::assert_snapshot!(render_forecast(
            &forecast_view_projected_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_forecast_insufficient_data_plain() {
        insta::assert_snapshot!(render_forecast(
            &forecast_view_insufficient_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_forecast_eta_unavailable_plain() {
        insta::assert_snapshot!(render_forecast(
            &forecast_view_eta_unavailable_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_forecast_no_usage_ascii() {
        // Pins the no-API-usage VISUAL surface (the default TTY): the header carries NO dollar
        // figure — never a fabricated `~$0.00` above "nothing to forecast yet" (§12.21).
        insta::assert_snapshot!(render_forecast(
            &forecast_view_eta_unavailable_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn forecast_projected_line_is_hedged_and_names_a_weekday() {
        // The plain-surviving actual-vs-projected distinction: a `projected ~$X by <date>` line
        // and a per-window `projected to hit ~<weekday>` line, both hedged `(estimated)`.
        let output = render_forecast(&forecast_view_projected_fixture(), RenderOptions::plain());
        assert!(
            output.contains("projected ~$37.50 by Jun 30 (estimated)"),
            "{output}"
        );
        assert!(
            output.contains("spend so far ~$20.00 over 16 of 30 days (estimated)"),
            "{output}"
        );
        assert!(
            output.contains("claude code weekly: projected to hit ~Friday (UTC, estimated)"),
            "{output}"
        );
        assert!(
            output.contains("claude code 5h: resets before you hit it (estimated)"),
            "{output}"
        );
        assert!(
            output.contains("codex weekly: ETA unavailable (no fresh verified usage reading)"),
            "{output}"
        );
    }

    #[test]
    fn forecast_below_floor_shows_insufficient_data_not_a_projection() {
        let output = render_forecast(
            &forecast_view_insufficient_fixture(),
            RenderOptions::plain(),
        );
        assert!(
            output.contains("insufficient data to project - 2 of 30 days elapsed (need 3+)"),
            "{output}"
        );
        // No fabricated month-end projection below the floor.
        assert!(!output.contains("projected ~$"), "{output}");
    }

    #[test]
    fn forecast_no_api_usage_renders_empty_state() {
        let output = render_forecast(
            &forecast_view_eta_unavailable_fixture(),
            RenderOptions::plain(),
        );
        assert!(
            output.contains("no API usage recorded - nothing to forecast yet"),
            "{output}"
        );
        assert!(
            output.contains("codex 5h: ETA unavailable (window just started)"),
            "{output}"
        );
        // render-1 regression guard: the VISUAL (default-TTY) surface must NOT fabricate a
        // `~$0.00` header above the empty-state body — the no-usage header carries no figure.
        let visual = render_forecast(
            &forecast_view_eta_unavailable_fixture(),
            RenderOptions::ascii(false),
        );
        assert!(
            !visual.contains("$0.00"),
            "no-usage visual header must carry no fabricated $0.00: {visual}"
        );
        assert!(
            visual.contains("no API usage recorded - nothing to forecast yet"),
            "{visual}"
        );
    }

    #[test]
    fn forecast_document_is_monochrome() {
        // The Forecast tab is advisory, so amber/red (Warn/Critical, reserved for the
        // near-limit/over-budget meter state) must never appear — bold (Strong) is the only
        // allowed non-color cue, mirroring `models_document_is_monochrome`.
        for view in [
            forecast_view_projected_fixture(),
            forecast_view_insufficient_fixture(),
            forecast_view_eta_unavailable_fixture(),
        ] {
            let doc = render_forecast_document(&view, RenderOptions::braille(true));
            for line in &doc.lines {
                for span in &line.spans {
                    assert!(
                        !matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical),
                        "forecast tab must be monochrome (amber/red are reserved): {span:?}"
                    );
                }
            }
        }
    }

    // ----- Anomalies tab (T16) -----

    fn anomaly_date(year: i32, month: u32, day: u32) -> NaiveDate {
        match NaiveDate::from_ymd_opt(year, month, day) {
            Some(date) => date,
            None => panic!("test date should be valid"),
        }
    }

    /// Two anomalies vs a 14-day baseline over 12 days of history: a spend spike (~$20 vs a $2.50
    /// median) and a model-mix shift (gpt-5.5 surged to 70% from a 20% median share).
    fn anomalies_view_flagged_fixture() -> AnomaliesView {
        AnomaliesView {
            generated_at: utc(2026, 6, 16, 12, 0),
            history_days: 12,
            min_history_days: 7,
            baseline_days: 14,
            enough_history: true,
            no_usage: false,
            anomalies: vec![
                Anomaly {
                    signal: AnomalySignal::SpendSpike {
                        date: anomaly_date(2026, 6, 16),
                    },
                    value: Decimal::new(2_000, 2),
                    baseline_median: Decimal::new(250, 2),
                    deviation: Decimal::new(1_750, 2),
                    magnitude: Some(Decimal::new(80, 1)),
                    baseline_days: 12,
                },
                Anomaly {
                    signal: AnomalySignal::ModelMixShift {
                        model: "gpt-5.5".to_string(),
                    },
                    value: Decimal::new(70, 2),
                    baseline_median: Decimal::new(20, 2),
                    deviation: Decimal::new(50, 2),
                    magnitude: Some(Decimal::new(35, 1)),
                    baseline_days: 12,
                },
            ],
        }
    }

    /// A model that COLLAPSED (today 0% from a 50% median) — exercises the `down from` phrasing.
    /// (The surge-with-no-median and displayed-zero/`~1.0x` suppression branches are covered by
    /// `anomalies_suppress_misleading_multiples` below.)
    fn anomalies_view_collapse_fixture() -> AnomaliesView {
        AnomaliesView {
            generated_at: utc(2026, 6, 16, 12, 0),
            history_days: 9,
            min_history_days: 7,
            baseline_days: 14,
            enough_history: true,
            no_usage: false,
            anomalies: vec![Anomaly {
                signal: AnomalySignal::ModelMixShift {
                    model: "claude-opus-4.7".to_string(),
                },
                value: Decimal::ZERO,
                baseline_median: Decimal::new(50, 2),
                deviation: Decimal::new(50, 2),
                magnitude: Some(Decimal::ZERO),
                baseline_days: 9,
            }],
        }
    }

    /// Enough history, nothing anomalous — the honest "in line with your norm" clean state.
    fn anomalies_view_clean_fixture() -> AnomaliesView {
        AnomaliesView {
            generated_at: utc(2026, 6, 16, 12, 0),
            history_days: 10,
            min_history_days: 7,
            baseline_days: 14,
            enough_history: true,
            no_usage: false,
            anomalies: Vec::new(),
        }
    }

    /// Below the 7-day floor — the honest insufficient-history state (no callouts).
    fn anomalies_view_insufficient_fixture() -> AnomaliesView {
        AnomaliesView {
            generated_at: utc(2026, 6, 16, 12, 0),
            history_days: 3,
            min_history_days: 7,
            baseline_days: 14,
            enough_history: false,
            no_usage: false,
            anomalies: Vec::new(),
        }
    }

    /// No usage recorded at all (`history_days == 0`) — the TRANSIENT zero-state, distinct from the
    /// 1..6-day "not enough history yet" thin-history line. After T16b this is NOT permanent: a
    /// subscription-only user is covered once they accrue enough token-days.
    fn anomalies_view_no_usage_fixture() -> AnomaliesView {
        AnomaliesView {
            generated_at: utc(2026, 6, 16, 12, 0),
            history_days: 0,
            min_history_days: 7,
            baseline_days: 14,
            enough_history: false,
            no_usage: true,
            anomalies: Vec::new(),
        }
    }

    #[test]
    fn snapshot_anomalies_no_usage_plain() {
        insta::assert_snapshot!(render_anomalies(
            &anomalies_view_no_usage_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn anomalies_no_usage_is_a_transient_zero_state_not_a_permanent_no_coverage() {
        // (T16b test #7) After T16b the model-mix counts ALL lanes, so a subscription-only user is
        // no longer permanently uncovered. The zero-state must read as TRANSIENT (it fills in as
        // usage accrues), never the retired permanent "no API-billed usage" / "API-lane only"
        // framing, and never the thin-history "0 of 7 days" line.
        for options in [RenderOptions::plain(), RenderOptions::ascii(false)] {
            let zero = render_anomalies(&anomalies_view_no_usage_fixture(), options);
            assert!(zero.contains("no usage recorded yet"), "{zero}");
            assert!(zero.contains("need a few days of history"), "{zero}");
            assert!(!zero.contains("no API-billed usage"), "{zero}");
            assert!(!zero.contains("API-lane only"), "{zero}");
            assert!(!zero.contains("0 of 7 days"), "{zero}");
            // A populated view (callouts present, no_usage == false) is NOT in the zero-state
            // branch: a subscription-only user with history DOES get callouts.
            let flagged = render_anomalies(&anomalies_view_flagged_fixture(), options);
            assert!(!flagged.contains("no usage recorded yet"), "{flagged}");
            assert!(flagged.contains("model mix shift"), "{flagged}");
        }
    }

    #[test]
    fn snapshot_anomalies_braille() {
        insta::assert_snapshot!(render_anomalies(
            &anomalies_view_flagged_fixture(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_anomalies_ascii() {
        insta::assert_snapshot!(render_anomalies(
            &anomalies_view_flagged_fixture(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_anomalies_plain() {
        insta::assert_snapshot!(render_anomalies(
            &anomalies_view_flagged_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_anomalies_clean_plain() {
        insta::assert_snapshot!(render_anomalies(
            &anomalies_view_clean_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_anomalies_insufficient_history_plain() {
        insta::assert_snapshot!(render_anomalies(
            &anomalies_view_insufficient_fixture(),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn anomalies_callouts_are_hedged_and_name_the_compared_window() {
        // The proactive, non-alarmist voice: each callout is `~`-hedged, `(estimated)`-tagged,
        // names the compared N-day window, and carries a NON-COLOR marker that survives `--plain`.
        let output = render_anomalies(&anomalies_view_flagged_fixture(), RenderOptions::plain());
        assert!(
            output.contains(
                "* spend spike: ~$20.00 on Jun 16, ~8.0x your ~$2.50 12-day median (estimated)"
            ),
            "{output}"
        );
        assert!(
            output.contains(
                "* model mix shift: gpt-5.5 at 70% of tokens, ~3.5x your 20% 12-day median (estimated)"
            ),
            "{output}"
        );
        // The header right-hand label counts the callouts (visual surface).
        let braille = render_anomalies(
            &anomalies_view_flagged_fixture(),
            RenderOptions::braille(false),
        );
        assert!(braille.contains("2 flagged"), "{braille}");
    }

    #[test]
    fn anomalies_collapse_reads_down_from_the_norm() {
        let output = render_anomalies(&anomalies_view_collapse_fixture(), RenderOptions::plain());
        assert!(
            output.contains(
                "* model mix shift: claude-opus-4.7 at 0% of tokens, down from your 50% 9-day median (estimated)"
            ),
            "{output}"
        );
    }

    /// A populated view that exercises the three "suppress the misleading multiple" render paths:
    /// (a) a spend spike off a `$0.00` median (`magnitude: None` — the median==0 honesty path);
    /// (b) a model surge off a sub-half-percent median that DISPLAYS as `0%` (finding #1 — a
    ///     `magnitude: Some` whose displayed baseline is zero); and
    /// (c) a spend spike whose multiple rounds to `1.0x` on a high-spend tight history (finding #4).
    fn anomalies_view_suppressed_multiples_fixture() -> AnomaliesView {
        AnomaliesView {
            generated_at: utc(2026, 6, 16, 12, 0),
            history_days: 8,
            min_history_days: 7,
            baseline_days: 14,
            enough_history: true,
            no_usage: false,
            anomalies: vec![
                // (a) spend spike, $0.00 median -> magnitude None -> "well above" (no multiple).
                Anomaly {
                    signal: AnomalySignal::SpendSpike {
                        date: anomaly_date(2026, 6, 16),
                    },
                    value: Decimal::new(500, 2),
                    baseline_median: Decimal::ZERO,
                    deviation: Decimal::new(500, 2),
                    magnitude: None,
                    baseline_days: 8,
                },
                // (b) model surge from a 0.3% median (displays "0%") with a finite multiple ->
                //     "up from" (the multiple is suppressed so it never reads "~150x your 0%").
                Anomaly {
                    signal: AnomalySignal::ModelMixShift {
                        model: "gpt-5.5".to_string(),
                    },
                    value: Decimal::new(45, 2),
                    baseline_median: Decimal::new(3, 3), // 0.003 = 0.3% -> "0%"
                    deviation: Decimal::new(447, 3),
                    magnitude: Some(Decimal::from(150)),
                    baseline_days: 8,
                },
                // (c) spend spike whose multiple rounds to 1.0x over a $50 median -> "well above".
                Anomaly {
                    signal: AnomalySignal::SpendSpike {
                        date: anomaly_date(2026, 6, 15),
                    },
                    value: Decimal::new(5_120, 2),
                    baseline_median: Decimal::new(5_000, 2),
                    deviation: Decimal::new(120, 2),
                    magnitude: Some(Decimal::new(10, 1)), // 1.0x
                    baseline_days: 8,
                },
            ],
        }
    }

    #[test]
    fn anomalies_suppress_misleading_multiples() {
        // Every callout must read honestly: no multiple over a displayed-zero baseline, and no
        // bare "~1.0x" — the descriptive phrasing is used instead. None of these lines may contain
        // an "x your" multiple clause.
        let output = render_anomalies(
            &anomalies_view_suppressed_multiples_fixture(),
            RenderOptions::plain(),
        );
        assert!(
            output.contains(
                "* spend spike: ~$5.00 on Jun 16, well above your ~$0.00 8-day median (estimated)"
            ),
            "magnitude None spend spike must read 'well above', not a multiple: {output}"
        );
        assert!(
            output.contains(
                "* model mix shift: gpt-5.5 at 45% of tokens, up from your 0% 8-day median (estimated)"
            ),
            "a surge off a displayed-0% median must read 'up from', never '~150.0x your 0%': {output}"
        );
        assert!(
            output.contains("* spend spike: ~$51.20 on Jun 15, well above your ~$50.00 8-day median (estimated)"),
            "a ~1.0x bump must read 'well above', not the misleading '~1.0x': {output}"
        );
        // The self-contradictory shapes must NEVER appear.
        assert!(
            !output.contains("x your 0%"),
            "no multiple over a displayed 0%: {output}"
        );
        assert!(
            !output.contains("x your ~$0.00"),
            "no multiple over a displayed $0.00: {output}"
        );
        assert!(
            !output.contains("~1.0x"),
            "no bare ~1.0x multiple: {output}"
        );
    }

    #[test]
    fn anomalies_clean_and_insufficient_states_are_honest() {
        let clean = render_anomalies(&anomalies_view_clean_fixture(), RenderOptions::plain());
        assert!(
            clean.contains("no anomalies - usage in line with your 10-day norm (estimated)"),
            "{clean}"
        );
        let thin = render_anomalies(
            &anomalies_view_insufficient_fixture(),
            RenderOptions::plain(),
        );
        assert!(
            thin.contains("not enough history yet - 3 of 7 days (estimated)"),
            "{thin}"
        );
        // The deferred quota-burn signal is disclosed on every state, never faked.
        assert!(thin.contains("quota burn-rate anomalies need multi-day quota history"));
    }

    #[test]
    fn anomalies_document_is_monochrome() {
        // The Anomalies tab is advisory, so amber/red (Warn/Critical) must never appear — the
        // non-color cue is the `◆`/`*` marker, never color (mirrors `forecast_document_is_monochrome`).
        for view in [
            anomalies_view_flagged_fixture(),
            anomalies_view_collapse_fixture(),
            anomalies_view_suppressed_multiples_fixture(),
            anomalies_view_clean_fixture(),
            anomalies_view_insufficient_fixture(),
        ] {
            let doc = render_anomalies_document(&view, RenderOptions::braille(true));
            for line in &doc.lines {
                for span in &line.spans {
                    assert!(
                        !matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical),
                        "anomalies tab must be monochrome (amber/red are reserved): {span:?}"
                    );
                }
            }
        }
    }

    #[cfg(feature = "connect")]
    #[test]
    fn connection_lane_renders_state_without_key_material_and_folds_ascii() {
        use costroid_core::GEMINI_UNAVAILABLE_MESSAGE;

        let connections = vec![
            ConnectionEntry {
                vendor: "anthropic".to_string(),
                state: ConnectionState::Connected {
                    org: Some("Acme (org-123)".to_string()),
                },
            },
            ConnectionEntry {
                vendor: "openai".to_string(),
                state: ConnectionState::NotConnected,
            },
            ConnectionEntry {
                vendor: "gemini".to_string(),
                state: ConnectionState::Unavailable(GEMINI_UNAVAILABLE_MESSAGE.to_string()),
            },
        ];
        let capabilities = provider_capabilities_fixture();
        let statuses = provider_statuses_for_tab();

        // Braille (UTF-8 TTY): keeps the em-dash glyph; shows org label, connected/not, and
        // the pinned Gemini message verbatim — and never any key material.
        let braille_opts = RenderOptions::braille(false);
        let mut braille = render_providers_document(&capabilities, &statuses, braille_opts);
        push_provider_connection_lane(&mut braille, &connections, braille_opts);
        let braille = braille.render(braille_opts);
        assert!(braille.contains("connections (your own usage API keys)"));
        assert!(braille.contains("connected — organization Acme (org-123)"));
        assert!(braille.contains("openai     not connected"));
        assert!(braille.contains(GEMINI_UNAVAILABLE_MESSAGE));

        // Plain + Ascii fold to pure ASCII (em-dash -> '-'), even with the pinned message.
        for options in [RenderOptions::plain(), RenderOptions::ascii(false)] {
            let mut doc = render_providers_document(&capabilities, &statuses, options);
            push_provider_connection_lane(&mut doc, &connections, options);
            let rendered = doc.render(options);
            assert!(
                rendered.is_ascii(),
                "connection lane must be pure ASCII: {rendered}"
            );
            assert!(rendered.contains("connected - organization Acme (org-123)"));
            assert!(rendered.contains("unavailable - no sanctioned static-key usage API"));
        }
    }

    #[test]
    fn snapshot_statusline_braille_with_ansi() {
        insta::assert_snapshot!(render_statusline(
            &priced_now(),
            RenderOptions::braille(true)
        ));
    }

    #[test]
    fn snapshot_statusline_braille() {
        insta::assert_snapshot!(render_statusline(
            &priced_now(),
            RenderOptions::braille(false)
        ));
    }

    #[test]
    fn snapshot_statusline_ascii() {
        insta::assert_snapshot!(render_statusline(
            &priced_now(),
            RenderOptions::ascii(false)
        ));
    }

    #[test]
    fn snapshot_statusline_plain() {
        insta::assert_snapshot!(render_statusline(&priced_now(), RenderOptions::plain()));
    }

    #[test]
    fn snapshot_statusline_plain_empty_api() {
        insta::assert_snapshot!(render_statusline(
            &subscription_only_now(),
            RenderOptions::plain()
        ));
    }

    // ----- frontier surface -----

    fn frontier_event(
        model: &str,
        access: costroid_providers::AccessPath,
        input: u64,
        output: u64,
    ) -> costroid_providers::UsageEvent {
        costroid_providers::UsageEvent {
            tool: costroid_providers::ProviderId::Codex,
            model: model.to_string(),
            timestamp: utc(2026, 6, 2, 9, 0),
            input_tokens: input,
            output_tokens: output,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            project: Some("/work/proj".to_string()),
            access_path: access,
        }
    }

    fn bench_view_for(events: &[costroid_providers::UsageEvent]) -> BenchView {
        let focus_rows = match costroid_core::focus_records_from_usage(events) {
            Ok(rows) => rows,
            Err(err) => panic!("events should price: {err}"),
        };
        let snapshot = costroid_core::EngineSnapshot {
            generated_at: utc(2026, 6, 2, 9, 0),
            usage_events: Vec::new(),
            focus_rows,
            limit_windows: Vec::new(),
            providers: Vec::new(),
            capabilities: Vec::new(),
        };
        match costroid_core::bench_view(&snapshot) {
            Ok(view) => view,
            Err(err) => panic!("bench view should build: {err}"),
        }
    }

    fn used_gpt() -> BenchView {
        bench_view_for(&[frontier_event(
            "gpt-5.5",
            costroid_providers::AccessPath::Api,
            1_000_000,
            1_000_000,
        )])
    }

    #[test]
    fn snapshot_frontier_plain() {
        insta::assert_snapshot!(render_frontier(&used_gpt(), RenderOptions::plain()));
    }

    #[test]
    fn snapshot_frontier_plain_no_api() {
        insta::assert_snapshot!(render_frontier(
            &bench_view_for(&[]),
            RenderOptions::plain()
        ));
    }

    #[test]
    fn snapshot_frontier_braille() {
        insta::assert_snapshot!(render_frontier(&used_gpt(), RenderOptions::braille(true)));
    }

    #[test]
    fn plain_frontier_has_no_ansi() {
        let output = render_frontier(&used_gpt(), RenderOptions::plain());
        assert!(
            !output.contains('\u{1b}'),
            "plain frontier must not contain ANSI escapes: {output}"
        );
    }

    #[test]
    fn braille_scatter_maps_known_points() {
        // Top-left point lands in cell 0 (dot 1 = ⠁); bottom-right in cell 1 (dot 8 = ⢀).
        let top_left = PlotPoint {
            x: 0.0,
            y: 100.0,
            on_frontier: false,
        };
        let bottom_right = PlotPoint {
            x: 10.0,
            y: 0.0,
            on_frontier: false,
        };
        assert_eq!(
            braille_scatter(&[top_left, bottom_right], 2, 1, false),
            vec!["⠁⢀".to_string()]
        );

        // A degenerate axis (all same x) must not panic and keeps the grid shape.
        let same_x = vec![
            PlotPoint {
                x: 5.0,
                y: 1.0,
                on_frontier: false,
            },
            PlotPoint {
                x: 5.0,
                y: 2.0,
                on_frontier: false,
            },
        ];
        let rows = braille_scatter(&same_x, 3, 2, false);
        assert_eq!(rows.len(), 2);
        assert!(rows.iter().all(|row| row.chars().count() == 3));
    }

    #[test]
    fn frontier_document_is_monochrome() {
        let doc = render_frontier_document(&used_gpt(), RenderOptions::braille(true));
        for line in &doc.lines {
            for span in &line.spans {
                assert!(
                    !matches!(span.style, SemanticStyle::Warn | SemanticStyle::Critical),
                    "frontier must be monochrome (amber/red are reserved): {span:?}"
                );
            }
        }
    }

    #[test]
    fn frontier_insight_uses_advisory_voice() {
        let line = frontier_insight_line(&used_gpt());
        assert!(
            line.starts_with(''),
            "insight should use the ◆ marker: {line}"
        );
        assert!(
            line.contains("(estimated)") || line.contains('~'),
            "insight should hedge: {line}"
        );
        let lower = line.to_lowercase();
        assert!(
            !lower.contains("switch to"),
            "insight must not prescribe: {line}"
        );
        assert!(
            !lower.contains("you should"),
            "insight must not prescribe: {line}"
        );
        assert!(plain_frontier_insight_line(&used_gpt()).starts_with("insight:"));
    }

    #[test]
    fn frontier_no_api_states_nothing_to_compare() {
        let output = render_frontier(&bench_view_for(&[]), RenderOptions::plain());
        assert!(output.contains("no API-billed usage to compare"));
        // Reference frontier still renders both benchmarks with their dominance verdicts.
        assert!(output.contains("dominated by gpt-5.5"));
    }

    // ---- reconciliation surface (T10c) --------------------------------------

    #[track_caller]
    fn dec(literal: &str) -> Decimal {
        match Decimal::from_str_exact(literal) {
            Ok(value) => value,
            Err(err) => panic!("bad fixture decimal {literal:?}: {err:?}"),
        }
    }

    fn usd(literal: &str) -> UsdAmount {
        UsdAmount::from_usd(dec(literal))
    }

    fn naive(year: i32, month: u32, day: u32) -> NaiveDate {
        match NaiveDate::from_ymd_opt(year, month, day) {
            Some(date) => date,
            None => panic!("bad fixture date"),
        }
    }

    fn local_with(entries: &[(NaiveDate, &str, &str)]) -> LocalCostEstimate {
        let mut estimate = LocalCostEstimate::new();
        for (date, model, dollars) in entries {
            if let Err(err) = estimate.add(*date, model, usd(dollars)) {
                panic!("fixture add failed: {err:?}");
            }
        }
        estimate
    }

    fn available(days: Vec<VendorCostDay>, caveats: CostReportCaveats) -> CostReportOutcome {
        CostReportOutcome::Available(VendorCostReport { days, caveats })
    }

    /// A vendor cost day from line items (panicking on the impossible money-overflow path —
    /// the workspace lints forbid `unwrap`/`expect` even in tests).
    fn vendor_day(date: NaiveDate, items: Vec<CostLineItem>) -> VendorCostDay {
        match VendorCostDay::from_line_items(date, items) {
            Ok(day) => day,
            Err(err) => panic!("fixture vendor day failed: {err:?}"),
        }
    }

    fn line_item(model: &str, dollars: &str, confidence: AmountConfidence) -> CostLineItem {
        CostLineItem {
            label: model.to_string(),
            amount: usd(dollars),
            model: Some(model.to_string()),
            cost_type: Some("tokens".to_string()),
            service_tier: Some("standard".to_string()),
            confidence,
        }
    }

    /// An Anthropic-shaped reconciliation exercising every honest state: an over-estimate
    /// day with a per-model split, a local day the vendor report doesn't cover (typed
    /// absence, never $0), and a model the vendor billed but Costroid never saw (a real
    /// local $0). Carries the Priority-Tier caveat.
    fn anthropic_reconciliation() -> CostReconciliation {
        let d_covered = naive(2026, 6, 14);
        let d_uncovered = naive(2026, 6, 13);
        let local = local_with(&[
            (d_covered, "claude-opus-4-8", "3.00"),
            (d_covered, "claude-sonnet-4-6", "1.20"),
            (d_uncovered, "claude-opus-4-8", "1.00"),
        ]);
        let outcome = available(
            vec![vendor_day(
                d_covered,
                vec![
                    line_item("claude-opus-4-8", "3.00", AmountConfidence::Exact),
                    line_item("claude-sonnet-4-6", "1.00", AmountConfidence::Exact),
                    line_item("claude-ghost-9", "0.50", AmountConfidence::Exact),
                ],
            )],
            CostReportCaveats {
                priority_tier_absent: true,
                per_model_derived_best_effort: false,
            },
        );
        reconcile_cost(&local, &outcome)
    }

    /// An OpenAI-shaped reconciliation: a best-effort per-model figure (marked + footnoted)
    /// and an under-estimate.
    fn openai_reconciliation() -> CostReconciliation {
        let day = naive(2026, 6, 14);
        let local = local_with(&[(day, "gpt-5.5", "1.00")]);
        let outcome = available(
            vec![vendor_day(
                day,
                vec![line_item(
                    "gpt-5.5",
                    "1.50",
                    AmountConfidence::DerivedBestEffort,
                )],
            )],
            CostReportCaveats {
                priority_tier_absent: false,
                per_model_derived_best_effort: true,
            },
        );
        reconcile_cost(&local, &outcome)
    }

    /// A not-connected reconciliation: the report is unavailable, but the local estimate
    /// still surfaces day by day beside the typed reason (never a fabricated delta).
    fn not_connected_reconciliation() -> CostReconciliation {
        let local = local_with(&[(naive(2026, 6, 14), "claude-opus-4-8", "2.00")]);
        reconcile_cost(
            &local,
            &CostReportOutcome::Unavailable(VendorReportUnavailable::NotConnected),
        )
    }

    /// Gemini: a first-class unavailable with no local usage — the pinned message, no delta.
    fn gemini_reconciliation() -> CostReconciliation {
        reconcile_cost(
            &LocalCostEstimate::new(),
            &CostReportOutcome::Unavailable(VendorReportUnavailable::NoSanctionedStaticKeyApi),
        )
    }

    /// Exercises three honest states the other fixtures don't: a model the vendor billed
    /// **$0** (variance shown, percentage undefined → "(vs $0 billed)"); a locally-estimated
    /// model the covered day does **not** attribute (`ModelNotInReport`); and a genuinely
    /// non-zero **sub-cent** variance (whose dollar magnitude rounds below a cent).
    fn mixed_states_reconciliation() -> CostReconciliation {
        let d = naive(2026, 6, 14);
        let local = local_with(&[
            (d, "billed-zero", "1.00"),
            (d, "unattributed", "0.40"),
            (d, "sub-cent", "0.001"),
        ]);
        let outcome = available(
            vec![vendor_day(
                d,
                vec![
                    line_item("billed-zero", "0", AmountConfidence::Exact),
                    line_item("sub-cent", "0.002", AmountConfidence::Exact),
                ],
            )],
            CostReportCaveats::default(),
        );
        reconcile_cost(&local, &outcome)
    }

    const WINDOW: &str = "2026-06-08 to 2026-06-14 (UTC, completed days)";

    #[test]
    fn snapshot_reconcile_anthropic_braille() {
        insta::assert_snapshot!(render_reconciliation(
            "anthropic",
            WINDOW,
            &anthropic_reconciliation(),
            RenderOptions::braille(false),
        ));
    }

    #[test]
    fn snapshot_reconcile_anthropic_ascii() {
        insta::assert_snapshot!(render_reconciliation(
            "anthropic",
            WINDOW,
            &anthropic_reconciliation(),
            RenderOptions::ascii(false),
        ));
    }

    #[test]
    fn snapshot_reconcile_anthropic_plain() {
        insta::assert_snapshot!(render_reconciliation(
            "anthropic",
            WINDOW,
            &anthropic_reconciliation(),
            RenderOptions::plain(),
        ));
    }

    #[test]
    fn snapshot_reconcile_openai_plain() {
        insta::assert_snapshot!(render_reconciliation(
            "openai",
            WINDOW,
            &openai_reconciliation(),
            RenderOptions::plain(),
        ));
    }

    #[test]
    fn snapshot_reconcile_not_connected_plain() {
        insta::assert_snapshot!(render_reconciliation(
            "openai",
            WINDOW,
            &not_connected_reconciliation(),
            RenderOptions::plain(),
        ));
    }

    #[test]
    fn snapshot_reconcile_gemini_plain() {
        insta::assert_snapshot!(render_reconciliation(
            "gemini",
            WINDOW,
            &gemini_reconciliation(),
            RenderOptions::plain(),
        ));
    }

    #[test]
    fn snapshot_reconcile_mixed_states_plain() {
        insta::assert_snapshot!(render_reconciliation(
            "openai",
            WINDOW,
            &mixed_states_reconciliation(),
            RenderOptions::plain(),
        ));
    }

    #[test]
    fn reconcile_renders_the_zero_billed_unattributed_and_subcent_states() {
        let output = render_reconciliation(
            "openai",
            WINDOW,
            &mixed_states_reconciliation(),
            RenderOptions::plain(),
        );
        // A model the vendor billed $0 → the dollar variance stands; the percentage is
        // undefined (never a divide-by-zero or a fabricated %).
        assert!(
            output.contains("+$1.00 over (vs $0 billed)"),
            "zero-billed model: {output}"
        );
        // A locally-estimated model a covered day doesn't attribute → typed text, no $0.
        assert!(output.contains("not attributed by the vendor"));
        // A genuinely non-zero sub-cent variance never reads as a misleading "$0.00".
        assert!(
            output.contains("<$0.01 under (-50.0%)"),
            "sub-cent variance: {output}"
        );
        assert!(
            !output.contains("$0.00 under") && !output.contains("$0.00 over"),
            "no misleading $0.00 direction cell: {output}"
        );
    }

    #[test]
    fn reconcile_renders_honest_states_in_plain() {
        let output = render_reconciliation(
            "anthropic",
            WINDOW,
            &anthropic_reconciliation(),
            RenderOptions::plain(),
        );
        // Local figure labeled an estimate; invoice shown un-tilded.
        assert!(output.contains("est ~$4.20"));
        // Signed variance carries the over/under direction as TEXT (never color alone).
        assert!(
            output.contains("over"),
            "expected an over-estimate row: {output}"
        );
        // Exact match renders "exact", not "+$0.00".
        assert!(output.contains("exact"));
        // Typed vendor-side absence renders as text, NEVER a fabricated $0.
        assert!(output.contains("report doesn't cover this day"));
        assert!(!output.contains("$0.00 under") && !output.contains("inv $0.00 "));
        // A vendor-billed model Costroid never saw → a REAL local $0 against the billed figure.
        assert!(output.contains("claude-ghost-9"));
        assert!(output.contains("est ~$0.00"));
        // The Priority-Tier caveat survives onto the screen.
        assert!(output.contains("Priority-Tier spend isn't in this report"));
    }

    #[test]
    fn reconcile_openai_marks_and_footnotes_best_effort() {
        let output = render_reconciliation(
            "openai",
            WINDOW,
            &openai_reconciliation(),
            RenderOptions::plain(),
        );
        // The under-estimate is signed + worded.
        assert!(output.contains("under"));
        // The best-effort per-model row is marked and footnoted.
        assert!(output.contains(" *"));
        assert!(output.contains("OpenAI per-model figures are best-effort"));
    }

    #[test]
    fn reconcile_not_connected_surfaces_estimate_and_remediation() {
        let output = render_reconciliation(
            "openai",
            WINDOW,
            &not_connected_reconciliation(),
            RenderOptions::plain(),
        );
        assert!(output.contains("vendor invoice unavailable: connect openai first"));
        // The local estimate still surfaces (never hidden behind the unavailable invoice).
        assert!(output.contains("est ~$2.00"));
        // No fabricated delta against a missing invoice.
        assert!(!output.contains("over") && !output.contains("under"));
    }

    #[test]
    fn reconcile_gemini_uses_the_pinned_unavailable_message() {
        let output = render_reconciliation(
            "gemini",
            WINDOW,
            &gemini_reconciliation(),
            RenderOptions::plain(),
        );
        // Plain folds the message's em-dash to ASCII, so compare the folded pinned string.
        assert!(output.contains(&costroid_core::GEMINI_UNAVAILABLE_MESSAGE.replace('', "-")));
        assert!(output.contains("No local usage recorded"));
    }

    #[test]
    fn reconcile_ascii_and_plain_output_is_pure_ascii() {
        // The accessibility floor: Ascii (non-UTF-8 terminals) and Plain (screen readers)
        // must be pure ASCII — the em-dash subtitle, the absence "—", and any reason-message
        // em-dash all fold.
        for recon in [
            anthropic_reconciliation(),
            openai_reconciliation(),
            not_connected_reconciliation(),
            gemini_reconciliation(),
            mixed_states_reconciliation(),
        ] {
            let ascii =
                render_reconciliation("anthropic", WINDOW, &recon, RenderOptions::ascii(false));
            assert!(
                ascii.is_ascii(),
                "ascii reconcile must be pure ASCII: {ascii}"
            );
            let plain = render_reconciliation("anthropic", WINDOW, &recon, RenderOptions::plain());
            assert!(
                plain.is_ascii(),
                "plain reconcile must be pure ASCII: {plain}"
            );
            // Plain is the accessibility floor — no ANSI escapes either.
            assert!(
                !plain.contains('\u{1b}'),
                "plain reconcile must carry no ANSI escapes: {plain}"
            );
        }
    }
}