auth-cloudflare 0.0.1

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

use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;

use auth_cloudflare::auth::{AuthProvider, ACCOUNT_ENV, TOKEN_ENV};
use auth_cloudflare::cache::{
	cache_dir_for_account, cache_is_stale, read_catalog_cache, write_catalog_cache, CatalogCacheMeta,
};
use auth_cloudflare::catalog::{ModelRecord, FALLBACK_MODELS};
use auth_cloudflare::config::{Config, SecretString};
use auth_cloudflare::error::CloudflareError;
use auth_cloudflare::fetch::{fetch_catalog_from_api, FETCH_TIMEOUT};
use auth_cloudflare::policy::ModelPolicy;
use auth_cloudflare::schema::{VersionInfo, CATALOG_SCHEMA_VERSION};
use auth_cloudflare::health;
use auth_cloudflare::verify::{self, SuiteKind};
use auth_cloudflare::{DEFAULT_MODEL, VERSION};

/// Live catalog fetcher - injectable for hermetic CLI tests (the production
/// path is `fetch_catalog_from_api`; tests substitute a canned fetcher so no
/// unit test ever touches the network).
type FetchCatalog =
	fn(account_id: &str, token: &SecretString, timeout: Duration) -> Result<serde_json::Value, CloudflareError>;

// Credential resolution: the CLI resolves full credentials through the
// core's `config.rs` (`Config::from_env`) only for the live-fetch commands
// (`catalog refresh`, and the cache-miss live path of `catalog get|list|
// export|inspect`); the token is held by `SecretString` and consumed only
// by `fetch_catalog_from_api` for the Bearer header. The token-free
// `ResolvedConfig` mirror below stays the source for everything that must
// NOT see the token (doctor, cache paths, staleness).

/// Exit code - command succeeded; health checks passed.
const EXIT_OK: i32 = 0;
/// Exit code - operational error: malformed args, I/O, unexpected failure.
const EXIT_OPERATIONAL: i32 = 1;
/// Exit code - credentials missing or invalid.
const EXIT_CREDENTIALS: i32 = 2;
/// Exit code - remote Cloudflare API failure.
const EXIT_REMOTE_API: i32 = 3;
/// Exit code - live API unavailable; stale cache successfully used.
const EXIT_STALE_CACHE: i32 = 4;
/// Exit code - requested model not found / catalog has no eligible model.
const EXIT_NO_ELIGIBLE_MODEL: i32 = 5;
/// Exit code - conformance suite ran but failed acceptance criteria.
const EXIT_CONFORMANCE: i32 = 6;
/// Exit code - unsafe configuration / secret-leak risk detected.
const EXIT_UNSAFE_CONFIG: i32 = 7;

/// How old a cached catalog may be before `catalog get` reports it stale
/// (and exits 4 - stale cache successfully used, feedback 02).
const CACHE_MAX_AGE: Duration = Duration::from_secs(6 * 3600);

/// Per-request budget for one live tool-loop run (ureq agent timeout).
const TOOL_LOOP_TIMEOUT: Duration = Duration::from_secs(90);

/// Canonical env vars (config.rs contract, feedback 03/06).
const ACCOUNT_ID_ENV: &str = "AUTH_CLOUDFLARE_ACCOUNT_ID";
const API_TOKEN_ENV: &str = "AUTH_CLOUDFLARE_API_TOKEN";
const BASE_URL_ENV: &str = "AUTH_CLOUDFLARE_WORKERS_AI_BASE_URL";
const CACHE_DIR_ENV: &str = "AUTH_CLOUDFLARE_CACHE_DIR";
const CONFIG_ENV: &str = "AUTH_CLOUDFLARE_CONFIG";
const LEGACY_HERMES_TOKEN_ENV: &str = "HERMES_CUSTOM_API_CLOUDFLARE_COM_API_KEY";
/// Expected Cloudflare account ID shape (config.rs contract).
const ACCOUNT_ID_LEN: usize = 32;
/// Default config file name under `$HERMES_HOME/auth-cloudflare/`.
const CONFIG_FILE_NAME: &str = "config.json";

/// Optional override for the `catalog export` output directory (dev/test
/// knob; defaults to the current working directory).
const EXPORT_DIR_ENV: &str = "AUTH_CLOUDFLARE_EXPORT_DIR";

const USAGE: &str = "\
auth-cloudflare - Cloudflare Workers AI auth provider CLI (v{version})

Usage:
  auth-cloudflare version [--format json]
  auth-cloudflare doctor [--format json]
  auth-cloudflare catalog get [--format json]
  auth-cloudflare catalog list [--format json]
  auth-cloudflare catalog refresh [--format json]
  auth-cloudflare catalog export yaml|markdown
  auth-cloudflare catalog diff [--format json]
  auth-cloudflare model inspect <model-id> [--format json]
  auth-cloudflare model verify <model-id> [--suite smoke] [--format json]
  auth-cloudflare model health [--format json]
  auth-cloudflare policy get [--format json]
  auth-cloudflare help

Exit codes (feedback 02, binding):
  0 success
  1 operational error (malformed args, I/O, unexpected failure)
  2 credentials missing or invalid
  3 remote Cloudflare API failure
  4 live API unavailable; stale cache successfully used
  5 requested model not found / no eligible model
  6 conformance suite ran but failed acceptance criteria
  7 unsafe configuration / secret-leak risk detected

Environment (core precedence, feedback 03/06):
  AUTH_CLOUDFLARE_ACCOUNT_ID, AUTH_CLOUDFLARE_API_TOKEN,
  AUTH_CLOUDFLARE_WORKERS_AI_BASE_URL, AUTH_CLOUDFLARE_CACHE_DIR,
  AUTH_CLOUDFLARE_CONFIG, AUTH_CLOUDFLARE_EXPORT_DIR (export target dir)
  AUTH_CLOUDFLARE_LIVE_TESTS=1 (opens the live gate for 'model verify';
  paid inference is refused unless the value is exactly the digit 1)
  AUTH_CLOUDFLARE_MAX_COST_USD=<budget> (optional conformance budget;
  reported as cost_estimate_usd in the run report, documented but never
  enforced)
  Legacy aliases: CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_API_TOKEN,
  HERMES_CUSTOM_API_CLOUDFLARE_COM_API_KEY
";

/// One parsed CLI invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Command {
	Version,
	Doctor,
	CatalogGet,
	CatalogList,
	CatalogRefresh,
	CatalogExport { format: ExportFormat },
	CatalogDiff,
	ModelInspect { model_id: String },
	ModelVerify { model_id: String, suite: SuiteKind, recommended: bool },
	ModelHealth,
	PolicyGet,
	Help,
}

/// Export document formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExportFormat {
	Yaml,
	Markdown,
}

fn main() {
	let args: Vec<String> = std::env::args().skip(1).collect();
	let code = run(&args, &mut std::io::stdout(), &mut std::io::stderr());
	std::process::exit(code);
}

/// Execute a CLI invocation; returns the process exit code (0-7).
///
/// JSON contract output goes to `out` (stdout); human diagnostics and usage
/// go to `err` (stderr). This is the unit-testable entry point - it never
/// calls `std::process::exit`. The live fetcher is injectable (tests pass a
/// canned fetcher; the binary uses `fetch_catalog_from_api`).
fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
	run_with_fetch(args, out, err, fetch_catalog_from_api)
}

/// [`run`] with an explicit fetcher - the test seam for hermetic CLI tests.
fn run_with_fetch(args: &[String], out: &mut dyn Write, err: &mut dyn Write, fetch: FetchCatalog) -> i32 {
	let (command, format) = match parse_args(args) {
		Ok(parsed) => parsed,
		Err(message) => {
			let _ = writeln!(err, "auth-cloudflare: {message}");
			let _ = writeln!(err, "{}", USAGE.replace("{version}", VERSION));
			return EXIT_OPERATIONAL;
		},
	};
	if let Some(format) = format {
		if format != "json" {
			let _ = writeln!(
				err,
				"auth-cloudflare: unsupported --format {format}: this command only supports --format json"
			);
			return EXIT_OPERATIONAL;
		}
	}
	execute(command, out, err, fetch)
}

/// Parse args into a command. `--format <value>` / `--format=<value>`,
/// `--suite <value>` / `--suite=<value>` and `--recommended` may appear
/// anywhere; everything else is positional. Returns a usage error message on
/// malformed/unknown input.
fn parse_args(args: &[String]) -> Result<(Command, Option<String>), String> {
	let mut format: Option<String> = None;
	let mut suite: Option<String> = None;
	let mut recommended = false;
	let mut positional: Vec<String> = Vec::new();
	let mut iter = args.iter();
	while let Some(arg) = iter.next() {
		if arg == "--format" {
			let Some(value) = iter.next() else {
				return Err("--format requires a value (e.g. --format json)".to_string());
			};
			format = Some(value.clone());
		} else if let Some(value) = arg.strip_prefix("--format=") {
			format = Some(value.to_string());
		} else if arg == "--suite" {
			let Some(value) = iter.next() else {
				return Err("--suite requires a value (e.g. --suite smoke)".to_string());
			};
			suite = Some(value.clone());
		} else if let Some(value) = arg.strip_prefix("--suite=") {
			suite = Some(value.to_string());
		} else if arg == "--recommended" {
			recommended = true;
		} else {
			positional.push(arg.clone());
		}
	}

	let command = match positional.as_slice() {
		[] => return Err("no command given".to_string()),
		[word] if word == "help" || word == "--help" || word == "-h" => Command::Help,
		[word] if word == "version" => Command::Version,
		[word] if word == "doctor" => Command::Doctor,
		[first, rest @ ..] if first == "catalog" => match rest {
			[sub] if sub == "get" => Command::CatalogGet,
			[sub] if sub == "list" => Command::CatalogList,
			[sub] if sub == "refresh" => Command::CatalogRefresh,
			[sub] if sub == "diff" => Command::CatalogDiff,
			[sub, export_format] if sub == "export" => {
				Command::CatalogExport { format: parse_export_format(export_format)? }
			},
			[sub] if sub == "export" => return Err("catalog export requires a format: yaml|markdown".to_string()),
			_ => return Err(format!("unknown catalog subcommand: {}", positional.join(" "))),
		},
		[first, rest @ ..] if first == "model" => match rest {
			[sub, model_id] if sub == "inspect" => Command::ModelInspect { model_id: model_id.clone() },
			[sub] if sub == "inspect" => {
				return Err(
					"model inspect requires a model id, e.g. model inspect @cf/deepseek-ai/deepseek-v4-flash-0731"
						.to_string(),
				);
			},
			[sub, model_id] if sub == "verify" => Command::ModelVerify {
				model_id: model_id.clone(),
				suite: SuiteKind::parse(suite.as_deref())?,
				recommended,
			},
			[sub] if sub == "verify" && recommended => Command::ModelVerify {
				model_id: DEFAULT_MODEL.to_string(),
				suite: SuiteKind::parse(suite.as_deref())?,
				recommended,
			},
			[sub] if sub == "verify" => {
				return Err(
						"model verify requires a model id (or --recommended), e.g. model verify @cf/deepseek-ai/deepseek-v4-flash-0731 [--suite smoke]"
							.to_string(),
					);
			},
			[sub] if sub == "health" => Command::ModelHealth,
			_ => return Err(format!("unknown model subcommand: {}", positional.join(" "))),
		},
		[first, rest @ ..] if first == "policy" => match rest {
			[sub] if sub == "get" => Command::PolicyGet,
			_ => return Err(format!("unknown policy subcommand: {}", positional.join(" "))),
		},
		_ => return Err(format!("unknown command: {}", positional.join(" "))),
	};
	// --suite / --recommended are model-verify flags; anywhere else they are
	// a usage error.
	if suite.is_some() && !matches!(command, Command::ModelVerify { .. }) {
		return Err("--suite is only valid with 'model verify'".to_string());
	}
	if recommended && !matches!(command, Command::ModelVerify { .. }) {
		return Err("--recommended is only valid with 'model verify'".to_string());
	}
	Ok((command, format))
}

fn parse_export_format(value: &str) -> Result<ExportFormat, String> {
	match value {
		"yaml" | "yml" => Ok(ExportFormat::Yaml),
		"markdown" | "md" => Ok(ExportFormat::Markdown),
		other => Err(format!("unsupported export format {other}: use yaml or markdown")),
	}
}

/// Dispatch a parsed command; returns the exit code.
fn execute(command: Command, out: &mut dyn Write, err: &mut dyn Write, fetch: FetchCatalog) -> i32 {
	match command {
		Command::Help => {
			let _ = writeln!(out, "{}", USAGE.replace("{version}", VERSION));
			EXIT_OK
		},
		Command::Version => {
			let (code, value) = version_json();
			emit_json(out, err, &value, code)
		},
		Command::Doctor => {
			let (code, value) = doctor_json();
			emit_json(out, err, &value, code)
		},
		Command::CatalogGet => {
			let (code, value) = catalog_get_json(fetch);
			emit_json(out, err, &value, code)
		},
		Command::CatalogList => {
			let (code, value) = catalog_list_json(fetch);
			emit_json(out, err, &value, code)
		},
		Command::CatalogRefresh => {
			let (code, value) = catalog_refresh_json(fetch, err);
			emit_json(out, err, &value, code)
		},
		Command::CatalogExport { format } => catalog_export(format, fetch, out, err),
		Command::CatalogDiff => {
			let (code, value) = catalog_diff_json();
			emit_json(out, err, &value, code)
		},
		Command::ModelInspect { model_id } => {
			let (code, value) = model_inspect_json(fetch, &model_id);
			emit_json(out, err, &value, code)
		},
		Command::ModelVerify { model_id, suite, recommended } => {
			let (code, value) = model_verify_json(&model_id, suite, recommended, err);
			emit_json(out, err, &value, code)
		},
		Command::ModelHealth => {
			let (code, value) = model_health_json();
			emit_json(out, err, &value, code)
		},
		Command::PolicyGet => {
			let (code, value) = policy_get_json();
			emit_json(out, err, &value, code)
		},
	}
}

/// Print a JSON contract document to stdout (pretty, trailing newline) and a
/// human hint to stderr for non-zero exits.
fn emit_json(out: &mut dyn Write, err: &mut dyn Write, value: &serde_json::Value, code: i32) -> i32 {
	match serde_json::to_string_pretty(value) {
		Ok(json) => {
			let _ = writeln!(out, "{json}");
			if code != EXIT_OK {
				if let Some(message) = value.get("error").and_then(|e| e.as_str()) {
					let _ = writeln!(err, "auth-cloudflare: {message} (exit {code})");
				}
			}
		},
		Err(error) => {
			let _ = writeln!(err, "auth-cloudflare: failed to serialize JSON output: {error}");
			return EXIT_OPERATIONAL;
		},
	}
	code
}

// ---------------------------------------------------------------------------
// version
// ---------------------------------------------------------------------------

/// Feedback-06 version contract - `VersionInfo::current()` serialized.
fn version_json() -> (i32, serde_json::Value) {
	(
		EXIT_OK,
		serde_json::to_value(VersionInfo::current()).expect("VersionInfo serializes"),
	)
}

// ---------------------------------------------------------------------------
// doctor
// ---------------------------------------------------------------------------

/// Feedback-06 doctor contract - never performs a network or paid inference
/// request (feedback 03). The token value never appears anywhere in the
/// output; account id is redacted as `624acc…9f84` (feedback 06).
///
/// Exit codes: 0 ok · 2 credentials missing/invalid · 7 unsafe config
/// (config file carries an `api_token` VALUE - feedback 02 forbids that).
fn doctor_json() -> (i32, serde_json::Value) {
	let resolved = resolve_config();
	let account_id = resolved.account_id.clone();
	let account_configured = account_id.is_some();
	let token_configured = resolved.token_configured;
	let unsafe_config = detect_unsafe_config(&resolved.config_path);

	let (redacted, base_url, cache_dir) = match &account_id {
		Some(id) => {
			let redacted = redact_account_id(id);
			let base_url = match &resolved.base_url_override {
				// Explicit override is user configuration, not a secret -
				// show it as-is.
				Some(url) => Some(url.clone()),
				// Derived endpoint - account id redacted.
				None => Some(AuthProvider::new(id).base_url().replace(id.as_str(), "<redacted>")),
			};
			(Some(redacted), base_url, resolved.cache_dir.clone())
		},
		None => (None, None, None),
	};

	let (cache_present, cache_age) = match &cache_dir {
		Some(dir) => match read_catalog_cache(dir) {
			Ok(Some((meta, _))) => (true, cache_age_seconds(&meta)),
			_ => (false, 0),
		},
		None => (false, 0),
	};

	let status = if account_configured && token_configured && !unsafe_config {
		"ok"
	} else {
		"error"
	};
	let exit = if unsafe_config {
		EXIT_UNSAFE_CONFIG
	} else if !account_configured || !token_configured {
		EXIT_CREDENTIALS
	} else {
		EXIT_OK
	};

	let value = serde_json::json!({
		"status": status,
		"account_id": {
			"configured": account_configured,
			"redacted": redacted,
		},
		"api_token": {
			"configured": token_configured,
			"value_redacted": true,
		},
		"endpoint": {
			"base_url": base_url,
		},
		"catalog_cache": {
			"present": cache_present,
			"age_seconds": cache_age,
		},
	});
	(exit, value)
}

// ---------------------------------------------------------------------------
// token-free configuration resolution (mirrors config.rs, no lib.rs edits)
// ---------------------------------------------------------------------------

/// Non-secret configuration resolved for the CLI. The API token VALUE is
/// deliberately never resolved into this binary - only its presence - so no
/// credential can leak through any code path, error, or serialization.
struct ResolvedConfig {
	/// Validated account id (exactly 32 ASCII hex digits), when resolvable.
	account_id: Option<String>,
	/// Whether an API token is present (canonical → legacy → file-named var).
	token_configured: bool,
	/// Account-scoped cache directory: override, file value, or derived
	/// `$HERMES_HOME/cache/auth-cloudflare/<slug>/`.
	cache_dir: Option<PathBuf>,
	/// Explicit base-url override, when configured.
	base_url_override: Option<String>,
	/// Resolved user config file path (for unsafe-config detection).
	config_path: PathBuf,
}

/// Resolve configuration through the exact config.rs precedence chain
/// (canonical `AUTH_CLOUDFLARE_*` → legacy `CLOUDFLARE_*` aliases → user
/// config file). The account id is validated for shape; whitespace-only
/// values count as missing.
fn resolve_config() -> ResolvedConfig {
	let config_path = env_nonempty(CONFIG_ENV)
		.map(PathBuf::from)
		.unwrap_or_else(|| hermes_home().join("auth-cloudflare").join(CONFIG_FILE_NAME));
	let file = read_config_file(&config_path);

	let account_id = env_nonempty(ACCOUNT_ID_ENV)
		.or_else(|| env_nonempty(ACCOUNT_ENV))
		.or_else(|| file.account_id.clone())
		.filter(|value| is_valid_account_id(value));

	let token_configured = env_nonempty(API_TOKEN_ENV)
		.or_else(|| env_nonempty(TOKEN_ENV))
		.or_else(|| env_nonempty(LEGACY_HERMES_TOKEN_ENV))
		.or_else(|| file.api_token_env.as_deref().and_then(env_nonempty))
		.is_some();

	let base_url_override = env_nonempty(BASE_URL_ENV).or_else(|| file.base_url.clone());

	let cache_dir = env_nonempty(CACHE_DIR_ENV)
		.map(PathBuf::from)
		.or_else(|| file.cache_dir.map(PathBuf::from))
		.or_else(|| account_id.as_ref().map(|id| cache_dir_for_account(&AuthProvider::new(id))));

	ResolvedConfig { account_id, token_configured, cache_dir, base_url_override, config_path }
}

/// Non-secret user config file (JSON) - same shape as config.rs's
/// FileConfig. A stray `api_token` VALUE is ignored by serde here (it is
/// flagged separately by `detect_unsafe_config`).
#[derive(Default, serde::Deserialize)]
struct ConfigFile {
	account_id: Option<String>,
	base_url: Option<String>,
	cache_dir: Option<String>,
	api_token_env: Option<String>,
}

/// Read the config file; missing/unreadable/malformed files resolve to an
/// empty config (never an error - matches config.rs).
fn read_config_file(path: &Path) -> ConfigFile {
	let Ok(raw) = std::fs::read_to_string(path) else {
		return ConfigFile::default();
	};
	serde_json::from_str(&raw).unwrap_or_default()
}

/// Read a non-empty (after trim) environment variable, if present.
fn env_nonempty(name: &str) -> Option<String> {
	std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
}

/// Cloudflare account ids are 32 ASCII hex digits (config.rs contract).
fn is_valid_account_id(value: &str) -> bool {
	value.len() == ACCOUNT_ID_LEN && value.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Resolve `$HERMES_HOME`, falling back to `~/.hermes` (config.rs contract).
fn hermes_home() -> PathBuf {
	env_nonempty("HERMES_HOME")
		.map(PathBuf::from)
		.unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "~".to_string())).join(".hermes"))
}

/// True when the user config file carries an `api_token` VALUE. The config
/// file may only name the env var holding the token (feedback 02); a literal
/// secret value in the file is an unsafe-config/secret-leak risk (exit 7).
fn detect_unsafe_config(path: &Path) -> bool {
	let Ok(raw) = std::fs::read_to_string(path) else {
		return false;
	};
	let Ok(value) = serde_json::from_str::<serde_json::Value>(&raw) else {
		return false;
	};
	match value.get("api_token") {
		Some(serde_json::Value::String(token)) => !token.trim().is_empty(),
		_ => false,
	}
}

/// Redact an account id as first-6 chars + ellipsis + last-4 chars
/// (`624acc…9f84` pattern, feedback 06). The account id is operational
/// metadata, not a secret - this is display hygiene for the endpoint URL.
fn redact_account_id(id: &str) -> String {
	let chars: Vec<char> = id.chars().collect();
	let n = chars.len();
	if n >= 10 {
		let head: String = chars[..6].iter().collect();
		let tail: String = chars[n - 4..].iter().collect();
		format!("{head}…{tail}")
	} else if n >= 4 {
		let head: String = chars[..2].iter().collect();
		let tail: String = chars[n - 2..].iter().collect();
		format!("{head}…{tail}")
	} else if n >= 2 {
		let head: String = chars[..1].iter().collect();
		format!("{head}…")
	} else {
		"…".to_string()
	}
}

/// Cache age in whole seconds since `fetched_at` (0 when absent/unparseable,
/// clamped at 0 - a future timestamp is not a negative age).
fn cache_age_seconds(meta: &CatalogCacheMeta) -> u64 {
	match chrono::DateTime::parse_from_rfc3339(&meta.fetched_at) {
		Ok(fetched_at) => chrono::Utc::now().signed_duration_since(fetched_at).num_seconds().max(0) as u64,
		Err(_) => 0,
	}
}

// ---------------------------------------------------------------------------
// catalog resolution (cache-first, offline-safe)
// ---------------------------------------------------------------------------

/// Resolved catalog data - one source of truth for `catalog get|list|export`
/// and `model inspect`.
struct ResolvedCatalog {
	/// `live` | `cache` | `fallback` - where the records came from.
	source: &'static str,
	/// `fresh` | `stale` | `none` (feedback 06 `cache_status`).
	cache_status: &'static str,
	/// RFC 3339 timestamp: the cache's `fetched_at`, fetch time for live, or
	/// now for fallback.
	fetched_at: String,
	/// Normalized model records.
	records: Vec<ModelRecord>,
}

/// Resolve the catalog: cache-first, live fetch when the cache is absent,
/// bundled `FALLBACK_MODELS` last. Never panics; the live fetch is skipped
/// whenever credentials do not resolve (fallback).
fn resolve_catalog_data(fetch: FetchCatalog) -> ResolvedCatalog {
	let resolved_config = resolve_config();
	// The cache dir is only meaningful with a valid account id (the derived
	// default is account-scoped); an override without credentials is not
	// trusted for catalog reads.
	let cache_dir = resolved_config.cache_dir.filter(|_| resolved_config.account_id.is_some());

	// 1. Cache present and usable -> serve it (fresh or stale, exit code
	//    decided by the caller).
	if let Some(dir) = &cache_dir {
		if let Ok(Some((meta, payload))) = read_catalog_cache(dir) {
			let records = records_from_payload(&payload);
			if !records.is_empty() {
				let stale = cache_is_stale(&meta, CACHE_MAX_AGE);
				return ResolvedCatalog {
					source: "cache",
					cache_status: if stale { "stale" } else { "fresh" },
					fetched_at: meta.fetched_at,
					records,
				};
			}
		}
	}

	// 2. No usable cache -> live fetch when full credentials resolve.
	if let Some((account_id, token)) = live_credentials() {
		if let Ok(payload) = fetch(&account_id, &token, FETCH_TIMEOUT) {
			let records = records_from_payload(&payload);
			if !records.is_empty() {
				let fetched_at = chrono::Utc::now().to_rfc3339();
				if let Some(dir) = &cache_dir {
					let meta = CatalogCacheMeta {
						schema_version: CATALOG_SCHEMA_VERSION,
						fetched_at: fetched_at.clone(),
						source: "cloudflare-workers-ai".to_string(),
						model_count: records.len(),
						account_fingerprint: AuthProvider::new(&account_id).cache_slug(),
					};
					// Best-effort: a cache write failure must not fail the
					// command - the live data is still served this run.
					let _ = write_catalog_cache(dir, &meta, &payload);
				}
				return ResolvedCatalog { source: "live", cache_status: "fresh", fetched_at, records };
			}
		}
	}

	// 3. Final offline fallback (source "fallback", cache_status "none").
	ResolvedCatalog {
		source: "fallback",
		cache_status: "none",
		fetched_at: chrono::Utc::now().to_rfc3339(),
		records: fallback_records(),
	}
}

/// Resolve full live-fetch credentials (validated account id + token) via
/// the core's `Config`; `None` when they do not resolve.
fn live_credentials() -> Option<(String, SecretString)> {
	let config = Config::from_env().ok()?;
	Some((config.account_id().to_string(), config.api_token().clone()))
}

/// Normalize an OpenRouter-format payload into model records.
fn records_from_payload(payload: &serde_json::Value) -> Vec<ModelRecord> {
	match payload.get("data").and_then(|data| data.as_array()) {
		Some(items) => items.iter().filter_map(ModelRecord::from_openrouter).collect(),
		None => Vec::new(),
	}
}

/// Build records for the bundled fallback list. Only id/name are
/// synthesized; pricing/context stay `None` (honest "no data" - never
/// invented Cloudflare fields) and capabilities come from the core's own
/// marker-based inference, so no classification logic is duplicated here.
fn fallback_records() -> Vec<ModelRecord> {
	let data: Vec<serde_json::Value> = FALLBACK_MODELS
		.iter()
		.map(|id| serde_json::json!({ "id": id, "name": display_name_from_id(id) }))
		.collect();
	records_from_payload(&serde_json::json!({ "data": data }))
}

/// Derive a display name from an id (`@cf/deepseek-ai/deepseek-v4-flash-0731`
/// → `DeepSeek V4 Flash 0731`). Pure display heuristics - never policy.
fn display_name_from_id(id: &str) -> String {
	let rest = id.strip_prefix("@cf/").unwrap_or(id);
	let model = rest.split('/').next_back().unwrap_or(rest);
	let mut out = String::new();
	let mut capitalize_next = true;
	let mut previous_was_digit = false;
	for ch in model.chars() {
		if ch == '-' || ch == '_' {
			out.push(' ');
			capitalize_next = true;
			previous_was_digit = false;
		} else if capitalize_next || previous_was_digit {
			out.extend(ch.to_uppercase());
			capitalize_next = false;
			previous_was_digit = ch.is_ascii_digit();
		} else {
			out.push(ch);
			previous_was_digit = ch.is_ascii_digit();
		}
	}
	out.split_whitespace()
		.map(|word| match word {
			// Brand casing where generic capitalization is wrong.
			"Deepseek" => "DeepSeek".to_string(),
			"Openai" => "OpenAI".to_string(),
			"Glm" => "GLM".to_string(),
			other => other.to_string(),
		})
		.collect::<Vec<_>>()
		.join(" ")
}

/// The feedback-06 per-model object shared by `catalog get`, `catalog
/// refresh`, and `model inspect`: id, display_name, status,
/// primary_agent_eligible, context_tokens, pricing_per_million {input,
/// cached_input, output}, capabilities {chat, tools, reasoning}.
fn model_json(record: &ModelRecord, policy: &ModelPolicy) -> serde_json::Value {
	serde_json::json!({
		"id": record.id,
		"display_name": record.display_name,
		"status": policy.status_for(&record.id),
		"primary_agent_eligible": policy.is_primary_agent_eligible(&record.id),
		"context_tokens": record.limits.context_tokens,
		"pricing_per_million": {
			"input": record.pricing.input,
			"cached_input": record.pricing.cached_input,
			"output": record.pricing.output,
		},
		"capabilities": {
			"chat": record.capabilities.chat,
			"tools": record.capabilities.tools,
			"reasoning": record.capabilities.reasoning,
		},
	})
}

/// The feedback-06 catalog envelope: schema_version, source, fetched_at,
/// cache_status, default_model, model_count, experimental_included,
/// deprecated_included, models. Used by `catalog get` (provenance
/// source `live`|`cache`|`fallback`) and `catalog refresh` (source
/// `cloudflare-workers-ai` - the catalog origin).
fn catalog_document(
	source: &str,
	cache_status: &str,
	fetched_at: String,
	records: &[ModelRecord],
) -> serde_json::Value {
	let policy = ModelPolicy::default_policy();
	let models: Vec<serde_json::Value> = records.iter().map(|record| model_json(record, &policy)).collect();
	serde_json::json!({
		"schema_version": CATALOG_SCHEMA_VERSION,
		"source": source,
		"fetched_at": fetched_at,
		"cache_status": cache_status,
		"default_model": DEFAULT_MODEL,
		"model_count": records.len(),
		"experimental_included": true,
		"deprecated_included": false,
		"models": models,
	})
}

// ---------------------------------------------------------------------------
// catalog get / list / refresh / diff / export, model inspect, policy get
// ---------------------------------------------------------------------------

/// Feedback-06 `catalog get` envelope. Cache-first: exit 0 fresh/live/
/// fallback, exit 4 when the cache is stale (live API unavailable, stale
/// cache successfully used). A live fetch is attempted only when no usable
/// cache exists; on live failure the bundled fallback is served (exit 0,
/// cache_status "none").
fn catalog_get_json(fetch: FetchCatalog) -> (i32, serde_json::Value) {
	let resolved = resolve_catalog_data(fetch);
	let exit = match resolved.cache_status {
		"stale" => EXIT_STALE_CACHE,
		_ => EXIT_OK,
	};
	let value = catalog_document(resolved.source, resolved.cache_status, resolved.fetched_at, &resolved.records);
	(exit, value)
}

/// `catalog list` - the same resolution as `catalog get`, but models is an
/// ordered list of model ids (picker order).
fn catalog_list_json(fetch: FetchCatalog) -> (i32, serde_json::Value) {
	let resolved = resolve_catalog_data(fetch);
	let models: Vec<String> = resolved.records.iter().map(|record| record.id.clone()).collect();
	let exit = match resolved.cache_status {
		"stale" => EXIT_STALE_CACHE,
		_ => EXIT_OK,
	};
	let value = serde_json::json!({
		"schema_version": CATALOG_SCHEMA_VERSION,
		"source": resolved.source,
		"cache_status": resolved.cache_status,
		"default_model": DEFAULT_MODEL,
		"model_count": models.len(),
		"experimental_included": true,
		"deprecated_included": false,
		"models": models,
	});
	(exit, value)
}

/// `catalog refresh` - live-first: typed `/ai/models/search` GET, cache
/// written on success (exit 0). On remote failure: serve a stale cache with
/// exit 4 (a fresh cache is still served with exit 0 - it is not stale), or
/// exit 3 with a typed error JSON when no cache exists.
fn catalog_refresh_json(fetch: FetchCatalog, err: &mut dyn Write) -> (i32, serde_json::Value) {
	let config = match Config::from_env() {
		Ok(config) => config,
		Err(error) => {
			return (
				EXIT_CREDENTIALS,
				serde_json::json!({
					"status": "error",
					"error": error.to_string(),
					"exit_code": EXIT_CREDENTIALS,
				}),
			);
		},
	};
	let account_id = config.account_id().to_string();
	let cache_dir = config.cache_dir();

	match fetch(&account_id, config.api_token(), FETCH_TIMEOUT) {
		Ok(payload) => {
			let records = records_from_payload(&payload);
			if records.is_empty() {
				// A live payload with no usable records is a remote failure
				// (invalid model payload - feedback 01 taxonomy).
				return refresh_failure(&CloudflareError::NoDataArray, &cache_dir, err);
			}
			let fetched_at = chrono::Utc::now().to_rfc3339();
			let meta = CatalogCacheMeta {
				schema_version: CATALOG_SCHEMA_VERSION,
				fetched_at: fetched_at.clone(),
				source: "cloudflare-workers-ai".to_string(),
				model_count: records.len(),
				account_fingerprint: AuthProvider::new(&account_id).cache_slug(),
			};
			if let Err(write_error) = write_catalog_cache(&cache_dir, &meta, &payload) {
				let _ = writeln!(
					err,
					"auth-cloudflare: warning: catalog refreshed but cache write failed: {write_error}"
				);
			}
			(
				EXIT_OK,
				catalog_document("cloudflare-workers-ai", "fresh", fetched_at, &records),
			)
		},
		Err(error) => refresh_failure(&error, &cache_dir, err),
	}
}

/// Shared refresh failure path: serve the account cache when one exists
/// (exit 4 when stale - "stale cache successfully used", feedback 02 exit
/// table; exit 0 when the cache is still fresh), else exit 3 with the typed
/// error JSON.
fn refresh_failure(error: &CloudflareError, cache_dir: &Path, err: &mut dyn Write) -> (i32, serde_json::Value) {
	if let Ok(Some((meta, payload))) = read_catalog_cache(cache_dir) {
		let records = records_from_payload(&payload);
		if !records.is_empty() {
			let stale = cache_is_stale(&meta, CACHE_MAX_AGE);
			let cache_status = if stale { "stale" } else { "fresh" };
			let exit = if stale { EXIT_STALE_CACHE } else { EXIT_OK };
			let _ = writeln!(
				err,
				"auth-cloudflare: live catalog fetch failed ({error}); serving {cache_status} cache (exit {exit})"
			);
			return (
				exit,
				catalog_document("cloudflare-workers-ai", cache_status, meta.fetched_at, &records),
			);
		}
	}
	(
		EXIT_REMOTE_API,
		serde_json::json!({
			"status": "error",
			"error": error.to_string(),
			"exit_code": EXIT_REMOTE_API,
		}),
	)
}

/// `catalog diff` - cache snapshot vs the bundled fallback list. Exit 1 when
/// there is no cache to diff against.
fn catalog_diff_json() -> (i32, serde_json::Value) {
	let resolved = resolve_config();
	let cache_dir = resolved.cache_dir.filter(|_| resolved.account_id.is_some());
	let Some(cache_dir) = cache_dir else {
		return (
			EXIT_OPERATIONAL,
			serde_json::json!({
				"status": "error",
				"error": "no account credentials resolved - cannot locate an account-scoped catalog cache to diff",
				"exit_code": EXIT_OPERATIONAL,
			}),
		);
	};
	let (meta, payload) = match read_catalog_cache(&cache_dir) {
		Ok(Some(found)) => found,
		Ok(None) => {
			return (
				EXIT_OPERATIONAL,
				serde_json::json!({
					"status": "error",
					"error": "no catalog cache present to diff against; run 'catalog refresh' to seed the cache",
					"exit_code": EXIT_OPERATIONAL,
				}),
			);
		},
		Err(error) => {
			return (
				EXIT_OPERATIONAL,
				serde_json::json!({
					"status": "error",
					"error": format!("catalog cache unreadable: {error}"),
					"exit_code": EXIT_OPERATIONAL,
				}),
			);
		},
	};

	let cache_ids: std::collections::BTreeSet<String> =
		records_from_payload(&payload).iter().map(|record| record.id.clone()).collect();
	let fallback_ids: std::collections::BTreeSet<String> = FALLBACK_MODELS.iter().map(|id| (*id).to_string()).collect();

	let added: Vec<String> = fallback_ids.difference(&cache_ids).cloned().collect();
	let removed: Vec<String> = cache_ids.difference(&fallback_ids).cloned().collect();
	let common = cache_ids.intersection(&fallback_ids).count();

	(
		EXIT_OK,
		serde_json::json!({
			"schema_version": CATALOG_SCHEMA_VERSION,
			"baseline": {
				"source": "cache",
				"fetched_at": meta.fetched_at,
				"model_count": cache_ids.len(),
			},
			"comparison": {
				"source": "fallback",
				"model_count": fallback_ids.len(),
			},
			"added": added,
			"removed": removed,
			"common_count": common,
		}),
	)
}

/// `catalog export yaml|markdown` - derive generated docs from the same
/// cache/live/fallback records (feedback 01: generated docs must derive from
/// the canonical catalog, never be hand-maintained duplicates). Writes
/// `catalog.generated.yaml` / `catalog.generated.md` into the export dir
/// (`AUTH_CLOUDFLARE_EXPORT_DIR`, default cwd).
fn catalog_export(format: ExportFormat, fetch: FetchCatalog, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
	let resolved = resolve_catalog_data(fetch);
	let policy = ModelPolicy::default_policy();
	let export_dir = std::env::var(EXPORT_DIR_ENV)
		.ok()
		.filter(|v| !v.trim().is_empty())
		.map(PathBuf::from)
		.unwrap_or_else(|| PathBuf::from("."));
	let (file_name, contents) = match format {
		ExportFormat::Yaml => (
			"catalog.generated.yaml",
			export_yaml(&resolved.records, resolved.source, &resolved.fetched_at, &policy),
		),
		ExportFormat::Markdown => (
			"catalog.generated.md",
			export_markdown(&resolved.records, resolved.source, &resolved.fetched_at, &policy),
		),
	};
	let path = export_dir.join(file_name);
	if let Err(error) = std::fs::write(&path, contents) {
		let _ = writeln!(err, "auth-cloudflare: failed to write {}: {error}", path.display());
		return EXIT_OPERATIONAL;
	}
	let _ = writeln!(
		out,
		"wrote {} ({} models, source: {}, cache_status: {})",
		path.display(),
		resolved.records.len(),
		resolved.source,
		resolved.cache_status
	);
	EXIT_OK
}

/// `model inspect <id>` - the feedback-06 per-model object plus its source.
/// Exit 5 when the id is not in the catalog (feedback 02: no eligible model).
fn model_inspect_json(fetch: FetchCatalog, model_id: &str) -> (i32, serde_json::Value) {
	let resolved = resolve_catalog_data(fetch);
	let policy = ModelPolicy::default_policy();
	let Some(record) = resolved.records.iter().find(|record| record.id == model_id) else {
		return (
			EXIT_NO_ELIGIBLE_MODEL,
			serde_json::json!({
				"status": "error",
				"error": format!("model '{model_id}' not found in catalog"),
				"model_id": model_id,
				"exit_code": EXIT_NO_ELIGIBLE_MODEL,
			}),
		);
	};
	let mut value = model_json(record, &policy);
	value["source"] = serde_json::Value::String(resolved.source.to_string());
	// Surface a delivery-degraded warning (feedback 01) when the account
	// health store has a Degraded/Failing conformance record for this model.
	// Advisory only - never changes the exit code or the model value shape.
	if let Some(warning) = degraded_model_warning(model_id) {
		value["warning"] = serde_json::Value::String(warning);
	}
	(EXIT_OK, value)
}

// ---------------------------------------------------------------------------
// model verify / model health (Phase-3 conformance smoke suite, task sa-0)
// ---------------------------------------------------------------------------

/// One completed conformance run, type-erased across suites so the CLI
/// dispatcher can share the gate/credential/error plumbing while keeping
/// each suite's own report shape.
enum RunOutcome {
	Smoke(Box<verify::SmokeRunReport>),
	ToolLoop(Box<auth_cloudflare::tool_loop::ToolLoopOutcome>),
}

/// `model verify <id> [--suite smoke|tool-loop] [--recommended]` - runs a
/// live conformance suite (`crate::verify` / `crate::tool_loop`) against the
/// model id **exactly as given**: the catalog is never consulted, so a model
/// absent from the catalog is still verified. `--recommended` substitutes
/// [`DEFAULT_MODEL`].
///
/// Exit contract (feedback 02):
/// - `0` all three checks passed (the run is persisted into `model-health.json`);
/// - `1` the live gate is closed (`AUTH_CLOUDFLARE_LIVE_TESTS` != `1`) - the
///   gate check precedes credential resolution and any fetch;
/// - `2` credentials missing;
/// - `3` the live API was unreachable at send time (remote Cloudflare API
///   failure - the run errored before completing);
/// - `6` the suite ran to completion and at least one check failed.
///
/// A model-health.json persistence failure is a warning on stderr, never a
/// verdict change (same best-effort precedent as `catalog refresh`).
fn model_verify_json(
	model_id: &str,
	suite: SuiteKind,
	recommended: bool,
	err: &mut dyn Write,
) -> (i32, serde_json::Value) {
	let model_id = if recommended { DEFAULT_MODEL } else { model_id };
	let suite_name = suite.as_str();
	let gate = if verify::live_tests_enabled() { "open" } else { "closed" };
	// Gate first: a closed gate refuses with exit 1 without resolving
	// credentials and without touching the network.
	if gate == "closed" {
		return (
			EXIT_OPERATIONAL,
			serde_json::json!({
				"model_id": model_id,
				"suite": suite_name,
				"gate": "closed",
				"status": "error",
				"error": "live tests disabled (set AUTH_CLOUDFLARE_LIVE_TESTS=1 to allow paid inference)",
				"passed": false,
				"exit_code": EXIT_OPERATIONAL,
			}),
		);
	}
	let config = match Config::from_env() {
		Ok(config) => config,
		Err(error) => {
			return (
				EXIT_CREDENTIALS,
				serde_json::json!({
					"model_id": model_id,
					"suite": suite_name,
					"gate": "open",
					"status": "error",
					"error": error.to_string(),
					"passed": false,
					"exit_code": EXIT_CREDENTIALS,
				}),
			);
		},
	};
	let result: Result<RunOutcome, CloudflareError> = match suite {
		SuiteKind::Smoke => {
			verify::run_smoke_suite(&config, model_id).map(|report| RunOutcome::Smoke(Box::new(report)))
		},
		SuiteKind::ToolLoop => {
			let base_url = match config.base_url() {
				Ok(url) => url,
				Err(error) => {
					return (
						EXIT_CREDENTIALS,
						serde_json::json!({
							"model_id": model_id,
							"suite": suite_name,
							"gate": gate,
							"status": "error",
							"error": error.to_string(),
							"passed": false,
							"exit_code": EXIT_CREDENTIALS,
						}),
					);
				},
			};
			auth_cloudflare::tool_loop::run_tool_loop(
				config.account_id(),
				config.api_token(),
				&base_url,
				model_id,
				TOOL_LOOP_TIMEOUT,
			)
			.map(|outcome| RunOutcome::ToolLoop(Box::new(outcome)))
		},
	};
	match result {
		Ok(RunOutcome::Smoke(report)) => {
			// Persist the account-scoped health store after the run; a local
			// write failure must not mask the conformance verdict.
			let dir = config.cache_dir();
			if let Err(error) = verify::save_verification(&dir, &report.verification) {
				let _ = writeln!(err, "auth-cloudflare: warning: model-health.json persistence failed: {error}");
			}
			let exit = if report.passed { EXIT_OK } else { EXIT_CONFORMANCE };
			let mut value = serde_json::to_value(&report).expect("SmokeRunReport serializes");
			value["gate"] = serde_json::Value::String(gate.to_string());
			value["exit_code"] = serde_json::json!(exit);
			(exit, value)
		},
		Ok(RunOutcome::ToolLoop(report)) => {
			// The tool-loop verification carries multi_turn_tool_success_rate
			// for the picker; persist it alongside the smoke records.
			let verification = verify::verification_from_tool_loop(model_id, &report);
			let dir = config.cache_dir();
			if let Err(error) = verify::save_verification(&dir, &verification) {
				let _ = writeln!(err, "auth-cloudflare: warning: model-health.json persistence failed: {error}");
			}
			let exit = if report.converged { EXIT_OK } else { EXIT_CONFORMANCE };
			let mut value = serde_json::to_value(&report).expect("ToolLoopOutcome serializes");
			value["verification"] = serde_json::to_value(&verification).expect("verification serializes");
			value["gate"] = serde_json::Value::String(gate.to_string());
			value["exit_code"] = serde_json::json!(exit);
			(exit, value)
		},
		Err(CloudflareError::MissingEnv { env_var, .. }) if env_var == verify::LIVE_TESTS_ENV => {
			// Defense-in-depth: the suite itself refused a closed gate.
			(
				EXIT_OPERATIONAL,
				serde_json::json!({
					"model_id": model_id,
					"suite": suite_name,
					"gate": gate,
					"status": "error",
					"error": "live tests disabled (set AUTH_CLOUDFLARE_LIVE_TESTS=1 to allow paid inference)",
					"passed": false,
					"exit_code": EXIT_OPERATIONAL,
				}),
			)
		},
		Err(error) => {
			// A send-phase transport failure means the live API was
			// unreachable - exit 3 (remote Cloudflare API failure), not a
			// conformance verdict.
			(
				EXIT_REMOTE_API,
				serde_json::json!({
					"model_id": model_id,
					"suite": suite_name,
					"gate": gate,
					"status": "error",
					"error": error.to_string(),
					"passed": false,
					"exit_code": EXIT_REMOTE_API,
				}),
			)
		},
	}
}

/// `model health` - prints the account-scoped health store
/// (`model-health.json` under the cache dir). Exit 2 when credentials are
/// missing; exit 0 with empty records when the store is absent; exit 1 when
/// a present store file is corrupt.
fn model_health_json() -> (i32, serde_json::Value) {
	let resolved = resolve_config();
	if resolved.account_id.is_none() || !resolved.token_configured {
		return (
			EXIT_CREDENTIALS,
			serde_json::json!({
				"status": "error",
				"error": "credentials missing: export AUTH_CLOUDFLARE_ACCOUNT_ID and AUTH_CLOUDFLARE_API_TOKEN (or the legacy CLOUDFLARE_* aliases)",
				"exit_code": EXIT_CREDENTIALS,
			}),
		);
	}
	let Some(cache_dir) = resolved.cache_dir else {
		return (
			EXIT_OPERATIONAL,
			serde_json::json!({
				"status": "error",
				"error": "no account-scoped cache directory resolved",
				"exit_code": EXIT_OPERATIONAL,
			}),
		);
	};
	match verify::load_health_store(&cache_dir) {
		Ok(store) => (
			EXIT_OK,
			serde_json::json!({
				"status": "ok",
				"version": store.version,
				"updated_at": store.updated_at.to_rfc3339(),
				"records": serde_json::to_value(&store.records).expect("records serialize"),
				"exit_code": EXIT_OK,
			}),
		),
		Err(error) => (
			EXIT_OPERATIONAL,
			serde_json::json!({
				"status": "error",
				"error": error.to_string(),
				"exit_code": EXIT_OPERATIONAL,
			}),
		),
	}
}

/// `policy get` - the core's bundled policy document, serialized as-is. When
/// the account health store records any Degraded/Failing verification, a
/// top-level `warnings` array surfaces each one (model_id + message) without
/// altering the policy shape itself.
fn policy_get_json() -> (i32, serde_json::Value) {
	let policy = ModelPolicy::default_policy();
	let mut value = serde_json::to_value(policy).expect("ModelPolicy serializes");
	if let Some(store) = load_health_store_best_effort() {
		let warnings: Vec<serde_json::Value> = store
			.records
			.values()
			.filter_map(|verification| {
				degraded_warning(verification).map(|message| {
					serde_json::json!({
						"model_id": verification.model_id,
						"message": message,
					})
				})
			})
			.collect();
		if !warnings.is_empty() {
			value["warnings"] = serde_json::Value::Array(warnings);
		}
	}
	(EXIT_OK, value)
}

// ---------------------------------------------------------------------------
// health-store warnings (model inspect / policy get, feedback 01)
// ---------------------------------------------------------------------------

/// Load the account-scoped health store (`model-health.json`) best-effort:
/// `None` when no cache dir resolves or the store is absent/corrupt.
/// Surfacing a delivery-degraded warning is advisory and must never change a
/// command's exit contract.
fn load_health_store_best_effort() -> Option<verify::HealthStore> {
	let cache_dir = resolve_config().cache_dir?;
	verify::load_health_store(&cache_dir).ok()
}

/// Token-free feedback-01 delivery warning for a model whose most recent
/// conformance verification is Degraded or Failing. Mirrors
/// `health::health_warning`'s shape (names the model and the recommended
/// stable alternative) but is keyed off the conformance-level
/// [`health::ModelVerification`] signal. `None` for Passing/Untested/Expired
/// or absent records - nothing to surface.
fn degraded_warning(verification: &health::ModelVerification) -> Option<String> {
	let degraded = matches!(
		verification.status,
		health::VerificationStatus::Degraded | health::VerificationStatus::Failing
	);
	if !degraded {
		return None;
	}
	let alternative = health::recommended_stable_alternative(&verification.model_id);
	let alternative = if alternative.is_empty() { DEFAULT_MODEL } else { alternative };
	Some(format!(
		"model {} delivery is degraded (verification status: {}); recommended stable alternative: {}",
		verification.model_id,
		enum_str(&verification.status),
		alternative
	))
}

/// Warning for one model id, or `None` when the health store has no
/// Degraded/Failing record for it (or no store at all).
fn degraded_model_warning(model_id: &str) -> Option<String> {
	let store = load_health_store_best_effort()?;
	let verification = store.get(model_id)?;
	degraded_warning(verification)
}

// ---------------------------------------------------------------------------
// export document builders (hand-rolled; no serde_yaml dependency)
// ---------------------------------------------------------------------------

/// `catalog.generated.yaml` - user-copyable Hermes fragment (feedback 02
/// shape), derived from the same records as `catalog get`.
fn export_yaml(records: &[ModelRecord], source: &str, fetched_at: &str, policy: &ModelPolicy) -> String {
	let mut s = String::new();
	s.push_str("# GENERATED FILE - do not edit by hand.\n");
	s.push_str(&format!("# Source: Cloudflare Workers AI catalog ({source})\n"));
	s.push_str(&format!("# Refreshed: {fetched_at}\n"));
	s.push_str("# Plugin policy: model-policy.yaml\n");
	s.push_str("# Verification: model-health.json\n");
	s.push_str("\nmodels:\n");
	for record in records {
		let status = policy.status_for(&record.id);
		let status_str = enum_str(&status);
		let marker: String = if record.id == DEFAULT_MODEL {
			"DEFAULT".to_string()
		} else {
			status_str.clone()
		};
		s.push_str(&format!("	# {marker} | {}\n", record.display_name));
		s.push_str(&format!("	# Status: {status_str}\n"));
		match record.limits.context_tokens {
			Some(tokens) => s.push_str(&format!("	# Context: {tokens} tokens\n")),
			None => s.push_str("	# Context: unknown\n"),
		}
		let price = |value: Option<f64>| match value {
			Some(v) => format!("${v:.2}/M"),
			None => "unknown".to_string(),
		};
		s.push_str(&format!(
			"	# Price: {} input; {} cached input; {} output\n",
			price(record.pricing.input),
			price(record.pricing.cached_input),
			price(record.pricing.output)
		));
		s.push_str(&format!("	# Tools: {}\n", enum_str(&record.capabilities.tools)));
		s.push_str(&format!("	# Reasoning: {}\n", enum_str(&record.capabilities.reasoning)));
		s.push_str(&format!("	- \"{}\"\n", record.id));
	}
	s
}

/// `catalog.generated.md` - summary + model table (feedback 02 shape).
fn export_markdown(records: &[ModelRecord], source: &str, fetched_at: &str, policy: &ModelPolicy) -> String {
	let eligible = records
		.iter()
		.filter(|record| policy.is_primary_agent_eligible(&record.id))
		.count();
	let mut s = String::new();
	s.push_str("# Cloudflare Workers AI catalog\n\n");
	s.push_str(&format!("Generated: {fetched_at}\n"));
	s.push_str(&format!("Plugin: {VERSION}\n"));
	s.push_str(&format!("Catalog: {source}\n"));
	s.push_str(&format!("Cache age: {} seconds\n", doc_cache_age_seconds(fetched_at)));
	s.push_str(&format!("Models found: {}\n", records.len()));
	s.push_str(&format!("Primary-agent eligible: {eligible}\n\n"));
	s.push_str("| Model | Status | Context | Input/M | Cached/M | Output/M | Tools | Reasoning |\n");
	s.push_str("| --- | --- | ---: | ---: | ---: | ---: | --- | --- |\n");
	for record in records {
		let status_str = enum_str(&policy.status_for(&record.id));
		let context = record
			.limits
			.context_tokens
			.map(|tokens| format!("{tokens}"))
			.unwrap_or_else(|| "-".to_string());
		let price = |value: Option<f64>| match value {
			Some(v) => format!("${v:.2}"),
			None => "-".to_string(),
		};
		s.push_str(&format!(
			"| {} | {} | {} | {} | {} | {} | {} | {} |\n",
			record.display_name,
			status_str,
			context,
			price(record.pricing.input),
			price(record.pricing.cached_input),
			price(record.pricing.output),
			enum_str(&record.capabilities.tools),
			enum_str(&record.capabilities.reasoning)
		));
	}
	s
}

/// snake_case string for a serde-serializable enum (uses the same serde
/// vocabulary as the JSON contract - never a hand-written duplicate).
fn enum_str<T: serde::Serialize>(value: &T) -> String {
	serde_json::to_value(value)
		.ok()
		.and_then(|value| value.as_str().map(str::to_string))
		.unwrap_or_else(|| "unknown".to_string())
}

/// Seconds between `fetched_at` and now for the generated docs header.
fn doc_cache_age_seconds(fetched_at: &str) -> u64 {
	match chrono::DateTime::parse_from_rfc3339(fetched_at) {
		Ok(timestamp) => chrono::Utc::now().signed_duration_since(timestamp).num_seconds().max(0) as u64,
		Err(_) => 0,
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use auth_cloudflare::auth::{ACCOUNT_ENV, TOKEN_ENV};

	/// Every env var the CLI or core reads, saved/restored for isolation.
	const ALL_VARS: &[&str] = &[
		"AUTH_CLOUDFLARE_ACCOUNT_ID",
		"AUTH_CLOUDFLARE_API_TOKEN",
		"AUTH_CLOUDFLARE_WORKERS_AI_BASE_URL",
		"AUTH_CLOUDFLARE_CACHE_DIR",
		"AUTH_CLOUDFLARE_CONFIG",
		"AUTH_CLOUDFLARE_EXPORT_DIR",
		"AUTH_CLOUDFLARE_LIVE_TESTS",
		"AUTH_CLOUDFLARE_MAX_COST_USD",
		"CLOUDFLARE_ACCOUNT_ID",
		"CLOUDFLARE_API_TOKEN",
		"HERMES_CUSTOM_API_CLOUDFLARE_COM_API_KEY",
		"HERMES_HOME",
		"HOME",
	];

	/// Synthetic Cloudflare-shaped account id (32 hex digits) - never real.
	const ACCOUNT: &str = "0123456789abcdef0123456789abcdef";
	/// Synthetic token - never a real credential.
	const TOKEN: &str = "cfut_test_synthetic_token_0001";

	/// `std::env` is process-global and tests run in parallel - serialize env
	/// mutation through a static mutex and restore prior values after.
	static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

	fn with_env<F, R>(vars: &[(&str, Option<&str>)], f: F) -> R
	where
		F: FnOnce() -> R,
	{
		let _guard = ENV_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
		let saved: Vec<(String, Option<String>)> = ALL_VARS
			.iter()
			.map(|key| ((*key).to_string(), std::env::var(key).ok()))
			.collect();
		for key in ALL_VARS {
			std::env::remove_var(key);
		}
		for (key, value) in vars {
			match value {
				Some(value) => std::env::set_var(key, value),
				None => std::env::remove_var(key),
			}
		}
		let result = f();
		for (key, value) in saved {
			match value {
				Some(value) => std::env::set_var(&key, value),
				None => std::env::remove_var(&key),
			}
		}
		result
	}

	/// Unique scratch dir per test - tests run in parallel.
	fn scratch_dir(name: &str) -> PathBuf {
		std::env::temp_dir().join(format!("auth-cloudflare-cli-test-{}-{name}", std::process::id()))
	}

	/// Run the CLI, returning (exit code, parsed stdout JSON or empty object).
	fn run_json(args: &[&str]) -> (i32, serde_json::Value) {
		let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
		let mut out: Vec<u8> = Vec::new();
		let mut err: Vec<u8> = Vec::new();
		let code = run(&owned, &mut out, &mut err);
		let value = serde_json::from_slice(&out).unwrap_or_else(|_| serde_json::json!({}));
		(code, value)
	}

	/// Run the CLI, returning (exit code, raw stdout text).
	fn run_raw(args: &[&str]) -> (i32, String) {
		let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
		let mut out: Vec<u8> = Vec::new();
		let mut err: Vec<u8> = Vec::new();
		let code = run(&owned, &mut out, &mut err);
		(code, String::from_utf8_lossy(&out).to_string())
	}

	/// Run the CLI with an injected fetcher (hermetic live-fetch tests).
	fn run_json_with_fetch(args: &[&str], fetch: FetchCatalog) -> (i32, serde_json::Value) {
		let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
		let mut out: Vec<u8> = Vec::new();
		let mut err: Vec<u8> = Vec::new();
		let code = run_with_fetch(&owned, &mut out, &mut err, fetch);
		let value = serde_json::from_slice(&out).unwrap_or_else(|_| serde_json::json!({}));
		(code, value)
	}

	/// Run the CLI with an injected fetcher, returning raw stdout.
	fn run_raw_with_fetch(args: &[&str], fetch: FetchCatalog) -> (i32, String) {
		let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
		let mut out: Vec<u8> = Vec::new();
		let mut err: Vec<u8> = Vec::new();
		let code = run_with_fetch(&owned, &mut out, &mut err, fetch);
		(code, String::from_utf8_lossy(&out).to_string())
	}

	/// Canned successful fetcher: a small OpenRouter-format live payload.
	fn fetch_ok(
		_account_id: &str,
		_token: &SecretString,
		_timeout: Duration,
	) -> Result<serde_json::Value, CloudflareError> {
		Ok(serde_json::json!({
			"data": [
				{
					"id": DEFAULT_MODEL,
					"name": "DeepSeek V4 Flash 0731",
					"context_length": 1_310_720,
					"pricing": { "prompt": "0.00000044", "completion": "0.00000132" },
				},
				{ "id": "@cf/moonshotai/kimi-k2.7-code", "name": "Kimi K2.7 Code" },
			]
		}))
	}

	/// Canned failing fetcher: a transport-style remote failure.
	fn fetch_err(
		_account_id: &str,
		_token: &SecretString,
		_timeout: Duration,
	) -> Result<serde_json::Value, CloudflareError> {
		Err(CloudflareError::Http("simulated network failure".to_string()))
	}

	/// Seed the account-scoped cache for the synthetic account/token env.
	fn seed_cache(fetched_at: &str, model_ids: &[&str]) {
		let dir = cache_dir_for_account(&AuthProvider::new(ACCOUNT));
		let data: Vec<serde_json::Value> = model_ids
			.iter()
			.map(|id| serde_json::json!({ "id": id, "name": display_name_from_id(id) }))
			.collect();
		let payload = serde_json::json!({ "data": data });
		let meta = CatalogCacheMeta {
			schema_version: CATALOG_SCHEMA_VERSION,
			fetched_at: fetched_at.to_string(),
			source: "cloudflare-workers-ai".to_string(),
			model_count: model_ids.len(),
			account_fingerprint: "0123456789abcdef".to_string(),
		};
		auth_cloudflare::cache::write_catalog_cache(&dir, &meta, &payload).expect("seed cache");
	}

	/// A minimal valid verification record for health-store tests.
	fn verification_record(model_id: &str, status: health::VerificationStatus) -> health::ModelVerification {
		health::ModelVerification {
			model_id: model_id.to_string(),
			latest_run_at: Some(chrono::Utc::now()),
			expires_at: None,
			suite_version: health::CONFORMANCE_SUITE_VERSION.to_string(),
			runner_version: "test".to_string(),
			status,
			agent_eligible: true,
			confidence: health::VerificationConfidence::SmokeTested,
			total_runs: 3,
			successful_runs: 3,
			text_completion_success_rate: Some(1.0),
			stream_completion_success_rate: Some(1.0),
			single_tool_success_rate: Some(1.0),
			multi_turn_tool_success_rate: None,
			structured_output_success_rate: None,
			median_latency_ms: Some(100),
			p95_latency_ms: None,
			total_failures: 0,
			timeout_failures: 0,
			transport_failures: 0,
			provider_5xx_failures: 0,
			malformed_response_failures: 0,
			malformed_tool_call_failures: 0,
			tool_loop_failures: 0,
			last_failure: None,
		}
	}

	/// Seed the account-scoped health store for the synthetic account/token env.
	fn seed_health_store(records: &[(&str, health::VerificationStatus)]) {
		let dir = cache_dir_for_account(&AuthProvider::new(ACCOUNT));
		let mut store = verify::HealthStore::new();
		for (model_id, status) in records {
			store.upsert(verification_record(model_id, *status));
		}
		verify::save_health_store(&dir, &store).expect("seed health store");
	}

	// ------------------------------------------------------------------
	// arg parsing
	// ------------------------------------------------------------------

	#[test]
	fn parses_every_command() {
		let cases: &[(&[&str], Command)] = &[
			(&["version"], Command::Version),
			(&["version", "--format", "json"], Command::Version),
			(&["--format", "json", "version"], Command::Version),
			(&["doctor", "--format=json"], Command::Doctor),
			(&["catalog", "get", "--format", "json"], Command::CatalogGet),
			(&["catalog", "list"], Command::CatalogList),
			(&["catalog", "refresh", "--format", "json"], Command::CatalogRefresh),
			(
				&["catalog", "export", "yaml"],
				Command::CatalogExport { format: ExportFormat::Yaml },
			),
			(
				&["catalog", "export", "markdown"],
				Command::CatalogExport { format: ExportFormat::Markdown },
			),
			(&["catalog", "diff", "--format", "json"], Command::CatalogDiff),
			(
				&["model", "inspect", "@cf/deepseek-ai/deepseek-v4-flash-0731", "--format", "json"],
				Command::ModelInspect { model_id: "@cf/deepseek-ai/deepseek-v4-flash-0731".to_string() },
			),
			(&["policy", "get", "--format", "json"], Command::PolicyGet),
		];
		for (args, expected) in cases {
			let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
			let (command, format) = parse_args(&owned).unwrap_or_else(|e| panic!("{args:?} should parse: {e}"));
			assert_eq!(&command, expected, "args {args:?}");
			let _ = format;
		}
	}

	#[test]
	fn unknown_command_is_a_parse_error() {
		let owned = vec!["frobnicate".to_string()];
		assert!(parse_args(&owned).is_err(), "unknown command must fail parsing");
		let owned = vec!["catalog".to_string(), "fly".to_string()];
		assert!(parse_args(&owned).is_err());
		let owned = vec!["model".to_string(), "inspect".to_string()];
		assert!(parse_args(&owned).is_err(), "inspect without id must fail");
	}

	#[test]
	fn unknown_command_exits_1() {
		with_env(&[], || {
			assert_eq!(run_raw(&["frobnicate"]).0, EXIT_OPERATIONAL);
		});
	}

	#[test]
	fn bad_format_flag_exits_1() {
		with_env(&[], || {
			assert_eq!(run_raw(&["version", "--format", "xml"]).0, EXIT_OPERATIONAL);
		});
	}

	#[test]
	fn bad_export_format_exits_1() {
		with_env(&[], || {
			assert_eq!(run_raw(&["catalog", "export", "toml"]).0, EXIT_OPERATIONAL);
		});
	}

	#[test]
	fn help_exits_0() {
		with_env(&[], || {
			assert_eq!(run_raw(&["help"]).0, EXIT_OK);
			assert_eq!(run_raw(&["--help"]).0, EXIT_OK);
		});
	}

	// ------------------------------------------------------------------
	// version (feedback 06 exact shape)
	// ------------------------------------------------------------------

	#[test]
	fn version_json_exact_feedback_06_shape() {
		with_env(&[], || {
			let (code, value) = run_json(&["version", "--format", "json"]);
			assert_eq!(code, EXIT_OK);
			let object = value.as_object().expect("object");
			let keys: std::collections::BTreeSet<&str> = object.keys().map(String::as_str).collect();
			let expected: std::collections::BTreeSet<&str> = [
				"name",
				"package_version",
				"protocol_version",
				"catalog_schema_versions",
				"minimum_hermes_plugin_version",
			]
			.into_iter()
			.collect();
			assert_eq!(keys, expected);
			assert_eq!(value["name"], "auth-cloudflare");
			assert_eq!(value["package_version"], VERSION);
			assert_eq!(value["protocol_version"], 1);
			assert_eq!(value["catalog_schema_versions"], serde_json::json!([1]));
			assert_eq!(value["minimum_hermes_plugin_version"], "0.0.1");
		});
	}

	#[test]
	fn version_defaults_to_json() {
		with_env(&[], || {
			let (code, value) = run_json(&["version"]);
			assert_eq!(code, EXIT_OK);
			assert_eq!(value["name"], "auth-cloudflare");
		});
	}

	// ------------------------------------------------------------------
	// doctor (feedback 06 shape, redaction, exit codes)
	// ------------------------------------------------------------------

	#[test]
	fn doctor_redacts_token_and_account() {
		let home = scratch_dir("doctor-redact");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json(&["doctor", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["status"], "ok");
				assert_eq!(value["account_id"]["configured"], true);
				assert_eq!(value["account_id"]["redacted"], "012345…cdef");
				assert_eq!(value["api_token"]["configured"], true);
				assert_eq!(value["api_token"]["value_redacted"], true);
				assert_eq!(
					value["endpoint"]["base_url"],
					"https://api.cloudflare.com/client/v4/accounts/<redacted>/ai/v1"
				);
				assert_eq!(value["catalog_cache"]["present"], false);
				assert_eq!(value["catalog_cache"]["age_seconds"], 0);
				// The token value must never appear in ANY doctor output.
				let (_, raw) = run_raw(&["doctor", "--format", "json"]);
				assert!(!raw.contains(TOKEN), "doctor output must never contain the token: {raw}");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn doctor_missing_creds_exits_2() {
		with_env(&[], || {
			let (code, value) = run_json(&["doctor", "--format", "json"]);
			assert_eq!(code, EXIT_CREDENTIALS);
			assert_eq!(value["status"], "error");
			assert_eq!(value["account_id"]["configured"], false);
			assert_eq!(value["api_token"]["configured"], false);
			assert_eq!(value["api_token"]["value_redacted"], true);
			assert!(value["endpoint"]["base_url"].is_null(), "base_url omitted when account unset");
		});
	}

	#[test]
	fn doctor_token_only_missing_reports_account_configured() {
		with_env(&[(ACCOUNT_ENV, Some(ACCOUNT))], || {
			let (code, value) = run_json(&["doctor", "--format", "json"]);
			assert_eq!(code, EXIT_CREDENTIALS);
			assert_eq!(value["account_id"]["configured"], true);
			assert_eq!(value["api_token"]["configured"], false);
		});
	}

	#[test]
	fn doctor_detects_unsafe_config_exit_7() {
		let home = scratch_dir("doctor-unsafe");
		let _ = std::fs::remove_dir_all(&home);
		std::fs::create_dir_all(&home).expect("create scratch dir");
		let config_path = home.join("config.json");
		std::fs::write(
			&config_path,
			format!(r#"{{"account_id":"{ACCOUNT}","api_token":"cfut_leaked_value"}}"#),
		)
		.expect("write unsafe config");
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("AUTH_CLOUDFLARE_CONFIG", Some(config_path.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json(&["doctor", "--format", "json"]);
				assert_eq!(code, EXIT_UNSAFE_CONFIG);
				assert_eq!(value["status"], "error");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn doctor_shows_cache_present_and_age() {
		let home = scratch_dir("doctor-cache");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(&chrono::Utc::now().to_rfc3339(), &[DEFAULT_MODEL]);
				let (code, value) = run_json(&["doctor", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["catalog_cache"]["present"], true);
				assert!(value["catalog_cache"]["age_seconds"].as_u64().unwrap_or(u64::MAX) < 10);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn redact_account_id_patterns() {
		assert_eq!(redact_account_id("624acc1234567890abcdef123456789f84"), "624acc…9f84");
		assert_eq!(redact_account_id("abcdef"), "ab…ef");
		assert_eq!(redact_account_id("ab"), "a…");
		assert_eq!(redact_account_id(""), "…");
	}

	// ------------------------------------------------------------------
	// catalog get (cache-first, fallback, exit 4 stale)
	// ------------------------------------------------------------------

	#[test]
	fn catalog_get_cache_miss_falls_back_to_bundled_models() {
		with_env(&[], || {
			let (code, value) = run_json(&["catalog", "get", "--format", "json"]);
			assert_eq!(code, EXIT_OK);
			assert_eq!(value["schema_version"], 1);
			assert_eq!(value["source"], "fallback");
			assert_eq!(value["cache_status"], "none");
			assert_eq!(value["default_model"], DEFAULT_MODEL);
			let models = value["models"].as_array().expect("models array");
			assert!(!models.is_empty());
			assert_eq!(value["model_count"].as_u64(), Some(models.len() as u64));
			assert_eq!(value["experimental_included"], true);
			assert_eq!(value["deprecated_included"], false);
			assert_eq!(models[0]["id"], DEFAULT_MODEL);
			assert_eq!(models[0]["status"], "recommended");
			assert_eq!(models[0]["primary_agent_eligible"], true);
			assert!(
				models[0]["pricing_per_million"]["input"].is_null(),
				"fallback pricing is honestly null"
			);
		});
	}

	#[test]
	fn catalog_get_fresh_cache_served() {
		let home = scratch_dir("get-fresh");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(&chrono::Utc::now().to_rfc3339(), &[DEFAULT_MODEL]);
				let (code, value) = run_json(&["catalog", "get", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["source"], "cache");
				assert_eq!(value["cache_status"], "fresh");
				assert_eq!(value["models"][0]["id"], DEFAULT_MODEL);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn catalog_get_stale_cache_exits_4() {
		let home = scratch_dir("get-stale");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache("2016-01-01T00:00:00Z", &[DEFAULT_MODEL]);
				let (code, value) = run_json(&["catalog", "get", "--format", "json"]);
				assert_eq!(code, EXIT_STALE_CACHE);
				assert_eq!(value["source"], "cache");
				assert_eq!(value["cache_status"], "stale");
				assert_eq!(value["models"][0]["id"], DEFAULT_MODEL, "stale cache is still served");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn catalog_list_is_ordered_ids() {
		with_env(&[], || {
			let (code, value) = run_json(&["catalog", "list", "--format", "json"]);
			assert_eq!(code, EXIT_OK);
			let models = value["models"].as_array().expect("models array");
			assert!(!models.is_empty());
			assert!(models.iter().all(|m| m.is_string()));
			assert_eq!(models[0], DEFAULT_MODEL);
			assert_eq!(value["model_count"].as_u64(), Some(models.len() as u64));
			assert_eq!(value["experimental_included"], true);
			assert_eq!(value["deprecated_included"], false);
		});
	}

	// ------------------------------------------------------------------
	// catalog refresh (live-first: fetch, cache write, stale/typed fallback)
	// ------------------------------------------------------------------

	#[test]
	fn refresh_missing_creds_exits_2() {
		with_env(&[], || {
			let (code, value) = run_json_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_ok);
			assert_eq!(code, EXIT_CREDENTIALS);
			assert_eq!(value["status"], "error");
			assert_eq!(value["exit_code"], EXIT_CREDENTIALS);
			assert!(
				value["error"]
					.as_str()
					.expect("error string")
					.contains("AUTH_CLOUDFLARE_ACCOUNT_ID"),
				"missing-cred error names the exact env var"
			);
		});
	}

	#[test]
	fn refresh_live_success_exits_0_and_writes_cache() {
		let home = scratch_dir("refresh-live-ok");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_ok);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["schema_version"], 1);
				assert_eq!(value["source"], "cloudflare-workers-ai");
				assert_eq!(value["cache_status"], "fresh");
				assert_eq!(value["default_model"], DEFAULT_MODEL);
				let models = value["models"].as_array().expect("models array");
				assert_eq!(models.len(), 2);
				assert_eq!(value["model_count"], 2);
				assert_eq!(value["experimental_included"], true);
				assert_eq!(value["deprecated_included"], false);
				assert_eq!(models[0]["id"], DEFAULT_MODEL);
				assert_eq!(models[0]["status"], "recommended");
				assert_eq!(models[0]["pricing_per_million"]["input"], 0.44);
				assert_eq!(models[0]["capabilities"]["tools"], "confirmed");
				// The account cache was written with live provenance.
				let dir = cache_dir_for_account(&AuthProvider::new(ACCOUNT));
				let (meta, payload) = read_catalog_cache(&dir).expect("read cache").expect("cache written");
				assert_eq!(meta.source, "cloudflare-workers-ai");
				assert_eq!(meta.model_count, 2);
				assert_eq!(meta.account_fingerprint, AuthProvider::new(ACCOUNT).cache_slug());
				assert_eq!(payload["data"][0]["id"], DEFAULT_MODEL);
				// The token never appears in refresh stdout.
				let (_, raw) = run_raw_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_ok);
				assert!(!raw.contains(TOKEN), "refresh output must never contain the token: {raw}");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn refresh_remote_failure_no_cache_exits_3() {
		let home = scratch_dir("refresh-fail-nocache");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_err);
				assert_eq!(code, EXIT_REMOTE_API);
				assert_eq!(value["status"], "error");
				assert!(
					value["error"]
						.as_str()
						.expect("error string")
						.contains("simulated network failure")
				);
				assert_eq!(value["exit_code"], EXIT_REMOTE_API);
				let (_, raw) = run_raw_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_err);
				assert!(!raw.contains(TOKEN), "error output must never contain the token: {raw}");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn refresh_remote_failure_stale_cache_exits_4() {
		let home = scratch_dir("refresh-fail-stale");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache("2016-01-01T00:00:00Z", &[DEFAULT_MODEL]);
				let (code, value) = run_json_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_err);
				assert_eq!(code, EXIT_STALE_CACHE);
				assert_eq!(value["source"], "cloudflare-workers-ai");
				assert_eq!(value["cache_status"], "stale");
				assert_eq!(value["models"][0]["id"], DEFAULT_MODEL, "stale cache is still served");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn refresh_remote_failure_fresh_cache_still_exits_0() {
		let home = scratch_dir("refresh-fail-fresh");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(&chrono::Utc::now().to_rfc3339(), &[DEFAULT_MODEL]);
				let (code, value) = run_json_with_fetch(&["catalog", "refresh", "--format", "json"], fetch_err);
				assert_eq!(code, EXIT_OK, "a still-fresh cache is served, not discarded");
				assert_eq!(value["cache_status"], "fresh");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	// ------------------------------------------------------------------
	// catalog get live-fetch path (cache absent -> live -> fallback)
	// ------------------------------------------------------------------

	#[test]
	fn catalog_get_live_fetch_on_cache_miss() {
		let home = scratch_dir("get-live");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json_with_fetch(&["catalog", "get", "--format", "json"], fetch_ok);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["source"], "live");
				assert_eq!(value["cache_status"], "fresh");
				assert_eq!(value["models"][0]["id"], DEFAULT_MODEL);
				// The live result was cached for next time.
				let dir = cache_dir_for_account(&AuthProvider::new(ACCOUNT));
				assert!(
					read_catalog_cache(&dir).expect("read cache").is_some(),
					"live get seeds the cache"
				);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn catalog_get_live_failure_falls_back_to_bundled() {
		let home = scratch_dir("get-live-fail");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json_with_fetch(&["catalog", "get", "--format", "json"], fetch_err);
				assert_eq!(code, EXIT_OK, "live failure without cache falls back with exit 0");
				assert_eq!(value["source"], "fallback");
				assert_eq!(value["cache_status"], "none");
				assert_eq!(value["models"][0]["id"], DEFAULT_MODEL);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn catalog_list_live_fetch_on_cache_miss() {
		let home = scratch_dir("list-live");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json_with_fetch(&["catalog", "list", "--format", "json"], fetch_ok);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["source"], "live");
				let models = value["models"].as_array().expect("models array");
				assert_eq!(models[0], DEFAULT_MODEL);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn diff_without_cache_exits_1() {
		with_env(&[], || {
			let (code, value) = run_json(&["catalog", "diff", "--format", "json"]);
			assert_eq!(code, EXIT_OPERATIONAL);
			assert_eq!(value["status"], "error");
		});
	}

	#[test]
	fn diff_against_seeded_cache_reports_added_and_common() {
		let home = scratch_dir("diff");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(&chrono::Utc::now().to_rfc3339(), &[DEFAULT_MODEL]);
				let (code, value) = run_json(&["catalog", "diff", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["common_count"], 1);
				assert_eq!(value["added"].as_array().expect("added").len(), FALLBACK_MODELS.len() - 1);
				assert!(value["removed"].as_array().expect("removed").is_empty());
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn export_yaml_and_markdown_derive_from_catalog() {
		let home = scratch_dir("export");
		let _ = std::fs::remove_dir_all(&home);
		std::fs::create_dir_all(&home).expect("create scratch dir");
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
				(EXPORT_DIR_ENV, Some(home.to_str().unwrap())),
			],
			|| {
				// Seed a fresh cache so the export stays hermetic (no live fetch).
				seed_cache(&chrono::Utc::now().to_rfc3339(), &[DEFAULT_MODEL]);
				let (code, message) = run_raw(&["catalog", "export", "yaml"]);
				assert_eq!(code, EXIT_OK, "yaml export: {message}");
				let yaml = std::fs::read_to_string(home.join("catalog.generated.yaml")).expect("yaml file");
				assert!(yaml.contains("GENERATED FILE"));
				assert!(yaml.contains(DEFAULT_MODEL));

				let (code, message) = run_raw(&["catalog", "export", "markdown"]);
				assert_eq!(code, EXIT_OK, "markdown export: {message}");
				let md = std::fs::read_to_string(home.join("catalog.generated.md")).expect("md file");
				assert!(md.contains("Cloudflare Workers AI catalog"));
				assert!(md.contains("| Model | Status |"));
				// Markdown rows show display names; ids appear in YAML.
				assert!(md.contains("DeepSeek V4 Flash 0731"));
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	// ------------------------------------------------------------------
	// model inspect
	// ------------------------------------------------------------------

	#[test]
	fn model_inspect_found_offline() {
		with_env(&[], || {
			let (code, value) = run_json(&["model", "inspect", DEFAULT_MODEL, "--format", "json"]);
			assert_eq!(code, EXIT_OK);
			assert_eq!(value["id"], DEFAULT_MODEL);
			assert_eq!(value["source"], "fallback");
			assert_eq!(value["status"], "recommended");
		});
	}

	#[test]
	fn model_inspect_missing_exits_5() {
		with_env(&[], || {
			let (code, value) = run_json(&["model", "inspect", "@cf/unknown/not-in-catalog", "--format", "json"]);
			assert_eq!(code, EXIT_NO_ELIGIBLE_MODEL);
			assert_eq!(value["status"], "error");
		});
	}

	#[test]
	fn model_inspect_serves_experimental_from_cache() {
		let home = scratch_dir("inspect-cache");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(&chrono::Utc::now().to_rfc3339(), &["@cf/zai-org/glm-5.3-flash"]);
				let (code, value) = run_json(&["model", "inspect", "@cf/zai-org/glm-5.3-flash", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["source"], "cache");
				assert_eq!(value["status"], "experimental", "policy marks GLM-5.3 Flash experimental");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn model_inspect_degraded_record_surfaces_warning_with_alternative() {
		let home = scratch_dir("inspect-degraded");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(&chrono::Utc::now().to_rfc3339(), &["@cf/zai-org/glm-5.3-flash"]);
				seed_health_store(&[("@cf/zai-org/glm-5.3-flash", health::VerificationStatus::Degraded)]);
				let (code, value) = run_json(&["model", "inspect", "@cf/zai-org/glm-5.3-flash", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				let warning = value["warning"].as_str().expect("degraded model surfaces a warning field");
				assert!(
					warning.contains(DEFAULT_MODEL),
					"warning must name the stable alternative: {warning}"
				);
				assert!(
					warning.contains("@cf/zai-org/glm-5.3-flash"),
					"warning must name the degraded model: {warning}"
				);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn model_inspect_passing_or_absent_record_has_no_warning() {
		let home = scratch_dir("inspect-no-warning");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_cache(
					&chrono::Utc::now().to_rfc3339(),
					&[DEFAULT_MODEL, "@cf/moonshotai/kimi-k2.7-code"],
				);
				// A passing record surfaces nothing.
				seed_health_store(&[(DEFAULT_MODEL, health::VerificationStatus::Passing)]);
				let (code, value) = run_json(&["model", "inspect", DEFAULT_MODEL, "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert!(
					value.get("warning").is_none(),
					"passing record must not surface a warning: {value}"
				);
				// A model with no health record surfaces nothing.
				let (code, value) =
					run_json(&["model", "inspect", "@cf/moonshotai/kimi-k2.7-code", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert!(
					value.get("warning").is_none(),
					"absent record must not surface a warning: {value}"
				);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	// ------------------------------------------------------------------
	// model verify / model health (Phase-3 conformance smoke suite)
	// ------------------------------------------------------------------

	#[test]
	fn parses_model_verify_and_health_commands() {
		let cases: &[(&[&str], Command)] = &[
			(
				&["model", "verify", DEFAULT_MODEL],
				Command::ModelVerify {
					model_id: DEFAULT_MODEL.to_string(),
					suite: SuiteKind::Smoke,
					recommended: false,
				},
			),
			(
				&["model", "verify", DEFAULT_MODEL, "--suite", "smoke"],
				Command::ModelVerify {
					model_id: DEFAULT_MODEL.to_string(),
					suite: SuiteKind::Smoke,
					recommended: false,
				},
			),
			(
				&["model", "verify", DEFAULT_MODEL, "--suite=smoke", "--format", "json"],
				Command::ModelVerify {
					model_id: DEFAULT_MODEL.to_string(),
					suite: SuiteKind::Smoke,
					recommended: false,
				},
			),
			(
				&["model", "verify", DEFAULT_MODEL, "--suite", "tool-loop"],
				Command::ModelVerify {
					model_id: DEFAULT_MODEL.to_string(),
					suite: SuiteKind::ToolLoop,
					recommended: false,
				},
			),
			(
				&["model", "verify", "--recommended", "--suite", "tool-loop"],
				Command::ModelVerify {
					model_id: DEFAULT_MODEL.to_string(),
					suite: SuiteKind::ToolLoop,
					recommended: true,
				},
			),
			(
				&["model", "verify", "--recommended"],
				Command::ModelVerify {
					model_id: DEFAULT_MODEL.to_string(),
					suite: SuiteKind::Smoke,
					recommended: true,
				},
			),
			(&["model", "health", "--format", "json"], Command::ModelHealth),
		];
		for (args, expected) in cases {
			let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
			let (command, format) = parse_args(&owned).unwrap_or_else(|e| panic!("{args:?} should parse: {e}"));
			assert_eq!(&command, expected, "args {args:?}");
			let _ = format;
		}
	}

	#[test]
	fn unknown_suite_and_misplaced_suite_are_parse_errors() {
		let owned = vec![
			"model".to_string(),
			"verify".to_string(),
			DEFAULT_MODEL.to_string(),
			"--suite".to_string(),
			"bogus".to_string(),
		];
		assert!(parse_args(&owned).is_err(), "unknown suite must fail parsing");
		let owned = vec!["version".to_string(), "--suite".to_string(), "smoke".to_string()];
		assert!(parse_args(&owned).is_err(), "--suite outside model verify must fail parsing");
		let owned = vec!["model".to_string(), "verify".to_string(), "--suite".to_string()];
		assert!(parse_args(&owned).is_err(), "--suite without a value must fail parsing");
		let owned = vec!["version".to_string(), "--recommended".to_string()];
		assert!(
			parse_args(&owned).is_err(),
			"--recommended outside model verify must fail parsing"
		);
		let owned = vec!["model".to_string(), "verify".to_string()];
		assert!(
			parse_args(&owned).is_err(),
			"model verify without id or --recommended must fail parsing"
		);
	}

	#[test]
	fn model_verify_gate_closed_exits_1_without_network() {
		with_env(&[], || {
			let (code, value) = run_json(&["model", "verify", DEFAULT_MODEL, "--format", "json"]);
			assert_eq!(code, EXIT_OPERATIONAL);
			assert_eq!(value["status"], "error");
			assert_eq!(value["gate"], "closed");
			assert_eq!(
				value["error"],
				"live tests disabled (set AUTH_CLOUDFLARE_LIVE_TESTS=1 to allow paid inference)"
			);
			assert_eq!(value["exit_code"], EXIT_OPERATIONAL);
			assert_eq!(value["model_id"], DEFAULT_MODEL);
			assert_eq!(value["suite"], "smoke");
			// No credentials were resolved and no fetch happened: the gate
			// check precedes every other step.
		});
	}

	#[test]
	fn model_verify_gate_precedes_credentials() {
		let home = scratch_dir("verify-gate-first");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				// Credentials are present but the gate is closed -> exit 1,
				// never exit 2, and no network call is made.
				let (code, value) = run_json(&["model", "verify", DEFAULT_MODEL, "--format", "json"]);
				assert_eq!(code, EXIT_OPERATIONAL);
				assert_eq!(value["gate"], "closed");
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	#[test]
	fn model_health_missing_creds_exits_2() {
		with_env(&[], || {
			let (code, value) = run_json(&["model", "health", "--format", "json"]);
			assert_eq!(code, EXIT_CREDENTIALS);
			assert_eq!(value["status"], "error");
			assert_eq!(value["exit_code"], EXIT_CREDENTIALS);
		});
	}

	#[test]
	fn model_health_no_store_returns_empty_records() {
		let home = scratch_dir("health-empty");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				let (code, value) = run_json(&["model", "health", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				assert_eq!(value["status"], "ok");
				assert_eq!(value["records"], serde_json::json!({}));
				assert!(value["updated_at"].is_string());
				assert_eq!(value["exit_code"], EXIT_OK);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	// ------------------------------------------------------------------
	// policy get
	// ------------------------------------------------------------------

	#[test]
	fn policy_get_matches_core_policy() {
		with_env(&[], || {
			let (code, value) = run_json(&["policy", "get", "--format", "json"]);
			assert_eq!(code, EXIT_OK);
			assert_eq!(value["version"], "1");
			let models = value["models"].as_array().expect("models array");
			assert_eq!(models[0]["model_id"], DEFAULT_MODEL);
			assert_eq!(models[0]["status"], "recommended");
			assert_eq!(models[0]["default"], true);
			let guard = models
				.iter()
				.find(|m| m["model_id"] == "@cf/meta/llama-guard-3-8b")
				.expect("guard entry");
			assert_eq!(guard["status"], "hidden");
			assert_eq!(guard["primary_agent_eligible"], false);
		});
	}

	#[test]
	fn policy_get_warnings_array_populated_for_degraded() {
		let home = scratch_dir("policy-warnings");
		let _ = std::fs::remove_dir_all(&home);
		with_env(
			&[
				(ACCOUNT_ENV, Some(ACCOUNT)),
				(TOKEN_ENV, Some(TOKEN)),
				("HERMES_HOME", Some(home.to_str().unwrap())),
			],
			|| {
				seed_health_store(&[
					("@cf/zai-org/glm-5.3-flash", health::VerificationStatus::Failing),
					(DEFAULT_MODEL, health::VerificationStatus::Passing),
				]);
				let (code, value) = run_json(&["policy", "get", "--format", "json"]);
				assert_eq!(code, EXIT_OK);
				let warnings = value["warnings"].as_array().expect("warnings array present for degraded model");
				assert_eq!(warnings.len(), 1, "only the Failing model is warned: {value}");
				assert_eq!(warnings[0]["model_id"], "@cf/zai-org/glm-5.3-flash");
				let message = warnings[0]["message"].as_str().expect("message string");
				assert!(
					message.contains(DEFAULT_MODEL),
					"message must name the stable alternative: {message}"
				);
			},
		);
		let _ = std::fs::remove_dir_all(&home);
	}

	// ------------------------------------------------------------------
	// helpers
	// ------------------------------------------------------------------

	#[test]
	fn display_name_from_id_heuristics() {
		assert_eq!(
			display_name_from_id("@cf/deepseek-ai/deepseek-v4-flash-0731"),
			"DeepSeek V4 Flash 0731"
		);
		assert_eq!(display_name_from_id("@cf/zai-org/glm-5.3-flash"), "GLM 5.3 Flash");
		assert_eq!(display_name_from_id("plain-id"), "Plain Id");
	}

	#[test]
	fn unsafe_config_detection_ignores_missing_or_safe_files() {
		let home = scratch_dir("unsafe-detect");
		let _ = std::fs::remove_dir_all(&home);
		std::fs::create_dir_all(&home).expect("create scratch dir");
		assert!(!detect_unsafe_config(&home.join("missing.json")), "missing file is safe");
		let safe = home.join("safe.json");
		std::fs::write(&safe, r#"{"account_id":"0123456789abcdef0123456789abcdef"}"#).expect("write safe config");
		assert!(!detect_unsafe_config(&safe), "no api_token value is safe");
		let env_named = home.join("env-named.json");
		std::fs::write(&env_named, r#"{"api_token_env":"MY_CF_TOKEN_VAR"}"#).expect("write env-named config");
		assert!(!detect_unsafe_config(&env_named), "env-var NAME is allowed (feedback 02)");
		let leaked = home.join("leaked.json");
		std::fs::write(&leaked, r#"{"api_token":"cfut_leaked"}"#).expect("write leaked config");
		assert!(detect_unsafe_config(&leaked), "a literal token value is unsafe");
		let _ = std::fs::remove_dir_all(&home);
	}
}