coralogix-cli 0.1.37

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
use std::io::IsTerminal;
use std::path::PathBuf;

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

use anyhow::{bail, Context, Result};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};

use crate::keyring_store;
use crate::oauth;

/// How long (in days) a cached team console base URL (see
/// [`Profile::cached_console_url`]) stays fresh before it is re-resolved via
/// `GET /identity/whoami`. The team URL is effectively immutable, so the TTL
/// only exists to recover from a bad cache and to pick up the rare region
/// migration.
const CONSOLE_URL_CACHE_TTL_DAYS: i64 = 7;

/// Authentication method used by a profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthKind {
    /// Static Coralogix API key.  Default for legacy profiles that pre-date OAuth.
    #[default]
    ApiKey,
    /// OAuth 2.0 + OIDC browser login with automatic token refresh.
    OAuth,
}

impl AuthKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            AuthKind::ApiKey => "api_key",
            AuthKind::OAuth => "oauth",
        }
    }
}

/// Where API keys are stored for a profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialStorage {
    /// Store in the profile TOML file (plaintext, 0600 permissions).
    #[default]
    File,
    /// Store in the OS credential store (macOS Keychain, Windows Credential Manager, etc.)
    OsStore,
}

/// Output format for command results.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
    /// Human-readable text output (default).
    #[default]
    Text,
    /// Raw JSON output.
    Json,
    /// Token-aware, AI-agent-optimised TOON output.
    ///
    /// `agents` is accepted as a deprecated alias for backward compatibility
    /// (both on the `-o/--output` flag and in config/profile files).
    #[value(alias = "agents")]
    #[serde(alias = "agents")]
    Toon,
}

impl OutputFormat {
    pub fn as_str(&self) -> &'static str {
        match self {
            OutputFormat::Text => "text",
            OutputFormat::Json => "json",
            OutputFormat::Toon => "toon",
        }
    }
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Coralogix region, used to resolve the API endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Region {
    Us1,
    Us2,
    Us3,
    Eu1,
    Eu2,
    Ap1,
    Ap2,
    Ap3,
    Stg1,
    #[serde(untagged)]
    Custom(String),
}

impl Region {
    pub fn api_endpoint(&self) -> &str {
        match self {
            Region::Us1 => "https://api.us1.coralogix.com",
            Region::Us2 => "https://api.us2.coralogix.com",
            Region::Us3 => "https://api.us3.coralogix.com",
            Region::Eu1 => "https://api.eu1.coralogix.com",
            Region::Eu2 => "https://api.eu2.coralogix.com",
            Region::Ap1 => "https://api.ap1.coralogix.com",
            Region::Ap2 => "https://api.ap2.coralogix.com",
            Region::Ap3 => "https://api.ap3.coralogix.com",
            Region::Stg1 => "https://api.stg1.coralogix.net",
            Region::Custom(url) => url.as_str(),
        }
    }

    /// Browser-console host suffix for this region (no scheme or team label).
    ///
    /// `None` for custom endpoints, which have no standard app domain.
    pub fn app_url_template(&self) -> Option<&str> {
        match self {
            Region::Us1 => Some("app.coralogix.us"),
            Region::Us2 => Some("app.cx498.coralogix.com"),
            Region::Us3 => Some("app.us3.coralogix.com"),
            Region::Eu1 => Some("coralogix.com"),
            Region::Eu2 => Some("app.eu2.coralogix.com"),
            Region::Ap1 => Some("app.coralogix.in"),
            Region::Ap2 => Some("app.coralogixsg.com"),
            Region::Ap3 => Some("app.ap3.coralogix.com"),
            Region::Stg1 => Some("app.stg1.coralogix.net"),
            Region::Custom(_) => None,
        }
    }
}

impl std::fmt::Display for Region {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Region::Us1 => write!(f, "us1"),
            Region::Us2 => write!(f, "us2"),
            Region::Us3 => write!(f, "us3"),
            Region::Eu1 => write!(f, "eu1"),
            Region::Eu2 => write!(f, "eu2"),
            Region::Ap1 => write!(f, "ap1"),
            Region::Ap2 => write!(f, "ap2"),
            Region::Ap3 => write!(f, "ap3"),
            Region::Stg1 => write!(f, "stg1"),
            Region::Custom(s) => write!(f, "{s}"),
        }
    }
}

impl std::str::FromStr for Region {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        Ok(match s.to_lowercase().as_str() {
            "us1" => Region::Us1,
            "us2" => Region::Us2,
            "us3" => Region::Us3,
            "eu1" => Region::Eu1,
            "eu2" => Region::Eu2,
            "ap1" => Region::Ap1,
            "ap2" => Region::Ap2,
            "ap3" => Region::Ap3,
            "stg1" => Region::Stg1,
            other => Region::Custom(other.to_string()),
        })
    }
}

/// A shell completion script installed and tracked by `cx completions install`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ManagedCompletion {
    /// Shell name as a lowercase string, e.g. "zsh", "bash", "fish".
    pub shell: String,
    /// Absolute path to the installed completion file.
    pub path: PathBuf,
}

/// Top-level config file (~/.cx/config.toml).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Default profile to use when none is specified.
    #[serde(default = "default_profile")]
    pub default_profile: String,

    /// Default output format when `--output` is omitted.
    #[serde(default)]
    pub default_output_format: OutputFormat,

    /// Maximum serialized byte size of a non-aggregated Dataprime response
    /// that can be printed directly to stdout in `toon` mode. If the payload
    /// exceeds this limit the data is written to a temp file instead.
    /// Set to `-1` to disable the limit (always print directly).
    /// Default: 100 KiB (102400 bytes).
    #[serde(
        default = "default_max_dataprime_direct_output_size",
        with = "max_size_serde"
    )]
    pub max_dataprime_direct_output_size: Option<usize>,

    /// Directory used to store temporary result files when the output exceeds
    /// `max_dataprime_direct_output_size`. Defaults to `/tmp/` on Unix and
    /// the OS temp directory on Windows.
    #[serde(default = "default_temp_dir")]
    pub temp_dir: String,

    /// Whether to allow risky commands (iam, archive write operations).
    /// When false, write operations under these commands are hard-blocked.
    #[serde(default = "default_true")]
    pub allow_risky_commands: bool,

    /// Whether the Olly AI assistant (`olly ask`) is enabled.
    /// When false, `olly ask` is blocked.
    #[serde(default = "default_true")]
    pub olly_enabled: bool,

    /// When true, ALL write operations are blocked globally.
    /// Equivalent to always passing --read-only.
    #[serde(default)]
    pub read_only: bool,

    /// Default for `--strict-fields-validation` on logs, spans, and
    /// `dataprime query`: reject keypaths absent from the schema instead of
    /// running with a compile warning. Off by default, like the public API.
    #[serde(default)]
    pub strict_fields_validation: bool,

    /// When true, "View in Coralogix" console links (the stderr line) are
    /// suppressed for ALL invocations. Equivalent to always passing
    /// --no-console-link.
    #[serde(default)]
    pub no_console_link: bool,

    /// After a cx upgrade, refresh the global cx agent skills in the
    /// background (`cx skills install --global` with the recorded agents, or
    /// auto-detected agents when cx did not record the install). Only for
    /// global cx skills that are older than this cx, and only with `npx`.
    #[serde(default = "default_true")]
    pub auto_update_skills: bool,

    /// Shell completion scripts installed and tracked by `cx completions install`.
    /// Only files recorded here are touched by `cx completions refresh`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub managed_completions: Vec<ManagedCompletion>,
}

fn default_profile() -> String {
    "default".to_string()
}

fn default_true() -> bool {
    true
}

fn default_max_dataprime_direct_output_size() -> Option<usize> {
    Some(100 * 1024) // 100 KiB
}

/// `/tmp/` on Unix (unchanged, and what the docs say), the OS temp
/// directory on Windows, where `/tmp/` does not exist.
fn default_temp_dir() -> String {
    if cfg!(windows) {
        let mut dir = std::env::temp_dir().to_string_lossy().into_owned();
        if !dir.ends_with(std::path::MAIN_SEPARATOR) {
            dir.push(std::path::MAIN_SEPARATOR);
        }
        dir
    } else {
        "/tmp/".to_string()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            default_profile: default_profile(),
            default_output_format: OutputFormat::default(),
            max_dataprime_direct_output_size: default_max_dataprime_direct_output_size(),
            temp_dir: default_temp_dir(),
            allow_risky_commands: true,
            olly_enabled: true,
            read_only: false,
            strict_fields_validation: false,
            no_console_link: false,
            auto_update_skills: true,
            managed_completions: vec![],
        }
    }
}

/// Custom serde module that maps the integer -1 in TOML/JSON to `None`
/// (disabled) and any non-negative integer to `Some(n)`.
mod max_size_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S>(value: &Option<usize>, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(n) => (*n as i64).serialize(s),
            None => (-1i64).serialize(s),
        }
    }

    pub fn deserialize<'de, D>(de: D) -> Result<Option<usize>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let n = i64::deserialize(de)?;
        if n < 0 {
            Ok(None)
        } else {
            Ok(Some(n as usize))
        }
    }
}

/// OAuth token set persisted inline in the profile TOML when
/// `credential_storage = "file"`. Mirrors the keyring-backed layout used by
/// `oauth::store_tokens_keyring`.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct StoredOAuthTokens {
    pub access_token: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id_token: Option<String>,
    /// Unix timestamp (seconds). Absent when the IdP did not return `expires_in`;
    /// callers fall back to parsing the JWT `exp` claim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiry: Option<u64>,
}

/// Trim label values, drop empties, and drop duplicates (first occurrence wins).
/// Comparison is exact and case-sensitive.
pub fn normalize_labels<I, S>(values: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut out = Vec::new();
    for value in values {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() || out.iter().any(|existing| existing == trimmed) {
            continue;
        }
        out.push(trimmed.to_string());
    }
    out
}

/// Parse `--label` values that were given on purpose: the flag was passed at
/// least once, so a list that normalizes to nothing (`--label ""`, `--label ,`,
/// an unset shell variable) is a mistake, not "no filter".
pub fn parse_given_label_args<S: AsRef<str>>(values: &[S]) -> Result<Vec<String>> {
    let labels = parse_label_args(values);
    if labels.is_empty() && !values.is_empty() {
        bail!("--label needs at least one non-empty label.");
    }
    Ok(labels)
}

/// Parse repeatable `--label` values. Each value may itself be comma-separated
/// (`--label prod,eu` and `--label prod --label eu` are the same).
pub fn parse_label_args<I, S>(values: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut parts = Vec::new();
    for value in values {
        for part in value.as_ref().split(',') {
            parts.push(part.to_string());
        }
    }
    normalize_labels(parts)
}

/// True when `labels` and `wanted` share at least one label (exact match).
pub(crate) fn has_any_label(labels: &[String], wanted: &[String]) -> bool {
    wanted
        .iter()
        .any(|want| labels.iter().any(|have| have == want))
}

/// Message for a label selection that matched no profile, for example
/// `No profiles with label 'prod' or 'eu'.`
pub(crate) fn no_profiles_for_labels(labels: &[String]) -> String {
    let quoted: Vec<String> = labels.iter().map(|label| format!("'{label}'")).collect();
    match quoted.as_slice() {
        [] => "No profiles matched.".to_string(),
        [label] => format!("No profiles with label {label}."),
        [head @ .., last] => format!("No profiles with label {} or {last}.", head.join(", ")),
    }
}

/// Names of the profiles in `entries` that have any of `wanted`, in the
/// given order. `entries` pairs each profile name with its labels.
fn names_with_any_label(entries: &[(String, Vec<String>)], wanted: &[String]) -> Vec<String> {
    entries
        .iter()
        .filter(|(_, labels)| has_any_label(labels, wanted))
        .map(|(name, _)| name.clone())
        .collect()
}

/// Build the list of profiles a command runs against from the global
/// `--profile` and `--label` flags.
///
/// Explicit `--profile` names come first, in the order given. Every profile on
/// disk that has any of `labels` is appended after them, in `cx profiles list`
/// order, skipping names already selected. A profile that fails to load
/// cannot be matched; it is reported on stderr and left out, so the caller
/// sees that the label covers fewer profiles than it implies.
///
/// Returns an empty list when both inputs are empty, which callers treat as
/// "use the default profile". Errors when `labels` is non-empty and no
/// profile has any of them, so a typo never silently runs against nothing.
pub fn select_profile_names(profiles: &[String], labels: &[String]) -> Result<Vec<String>> {
    let mut selected: Vec<String> = profiles.to_vec();
    if labels.is_empty() {
        return Ok(selected);
    }
    // A profile that does not load cannot be matched. Say so instead of
    // silently running against fewer profiles than the label implies.
    let entries: Vec<(String, Vec<String>)> = list_profile_names()?
        .into_iter()
        .filter_map(|name| match load_profile(&name) {
            Ok(profile) => Some((name, profile.labels)),
            Err(error) => {
                eprintln!("warning: skipping profile '{name}' in the --label scan: {error}");
                None
            }
        })
        .collect();
    let matched = names_with_any_label(&entries, labels);
    if matched.is_empty() {
        bail!(
            "{} Run `cx profiles list` to see each profile's labels, \
             or `cx profiles add <name> --label <label>` to tag one.",
            no_profiles_for_labels(labels)
        );
    }
    // Any match wins, so a label that matches nothing does not stop the
    // command. Still say so: a typo next to a good label is easy to miss.
    for label in labels {
        if !entries.iter().any(|(_, have)| have.contains(label)) {
            eprintln!("warning: no profile has label '{label}'");
        }
    }
    for name in matched {
        if !selected.contains(&name) {
            selected.push(name);
        }
    }
    Ok(selected)
}

/// `labels` is the canonical key. When it is missing or normalizes to nothing,
/// a legacy `label = "prod"` string is loaded as a one-item list.
fn labels_from_file(label: Option<String>, labels: Option<Vec<String>>) -> Vec<String> {
    if let Some(labels) = labels {
        let normalized = normalize_labels(labels);
        if !normalized.is_empty() {
            return normalized;
        }
    }
    match label {
        Some(label) => normalize_labels([label]),
        None => Vec::new(),
    }
}

/// A named profile storing credentials and endpoint info.
///
/// `credential_storage` selects where secrets live for both auth modes:
///   - `"file"` (the value when the key is omitted, so existing profiles stay
///     file-based, and the setup default on Linux): API keys / OAuth tokens
///     are written inline in the TOML, which is created with `0600` permissions.
///   - `"os_store"` (the setup default on macOS and Windows): secrets are stored in the OS
///     credential store (macOS Keychain, Windows Credential Manager, etc.) and
///     the inline fields are absent from the TOML.
#[derive(Debug, Clone, Serialize)]
pub struct Profile {
    /// Authentication method for this profile.
    /// Defaults to `ApiKey` so that existing profiles without this field continue to work.
    #[serde(default)]
    pub auth: AuthKind,
    /// Where credentials for this profile are stored (applies to both API keys
    /// and OAuth tokens).
    #[serde(default)]
    pub credential_storage: CredentialStorage,
    /// Coralogix API key. Present when `auth = "api_key"` and
    /// `credential_storage = "file"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    pub region: Region,
    /// Free-form labels (for example "prod", "eu"). Empty when the profile has
    /// none. Written as a `labels` array. A legacy `label` string is still
    /// read and becomes a one-item list.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    /// OAuth: override the OAuth client ID.
    /// Required for custom regions; hard-coded for known Coralogix regions.
    /// Not written to the TOML for known regions (looked up from `KNOWN_ENVIRONMENTS`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oauth_client_id: Option<String>,
    /// OAuth: override the base URL used for OpenID Connect discovery.
    /// When `None`, `region.api_endpoint()` is used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oauth_base_url: Option<String>,
    /// OAuth: cached token set. Present only when `auth = "oauth"` and
    /// `credential_storage = "file"`. For `os_store`, tokens live in the OS keyring.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oauth_tokens: Option<StoredOAuthTokens>,
    /// Per-profile default output format. When set, takes precedence over the
    /// global `default_output_format` in config.toml.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_output_format: Option<OutputFormat>,
    /// Per-profile default storage tier for DataPrime queries (logs, spans).
    /// When set, used as the default `--tier` value for this profile.
    /// Falls back to `Archive` when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_tier: Option<crate::Tier>,
    /// Explicit override for the Coralogix web console base URL used to build
    /// "View in Coralogix" links. Include the team subdomain - console links
    /// resolve to a team, and the team name is not always derivable
    /// automatically.
    ///
    /// When unset, the CLI resolves this automatically via
    /// `GET /identity/whoami` (see `identity::lookup_whoami`). If that
    /// lookup fails or returns no usable URL, no console link is printed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub console_url: Option<String>,
    /// Machine-managed cache of the team console base URL resolved via
    /// `GET /identity/whoami`, persisted here (best-effort) so that repeated
    /// invocations don't re-hit the identity endpoint just to print a "View in
    /// Coralogix" link. Like `oauth_tokens`, this is written by `cx`, not the
    /// user, and is ignored whenever an explicit `console_url` override is set.
    /// Expired after [`CONSOLE_URL_CACHE_TTL_DAYS`]; see
    /// [`load_cached_console_url`] / [`cache_team_identity`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cached_console_url: Option<String>,
    /// When `cached_console_url` was last resolved. Used to expire the cache.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cached_console_url_at: Option<DateTime<Utc>>,
    /// Team id from the last successful `GET /identity/whoami` for this profile.
    /// Used to reject an OAuth re-login that comes back as a different team.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cached_team_id: Option<i64>,
    /// Display name from that same whoami response. `cx profiles add` asks the
    /// user to pick a team by name, so the re-login hint prefers this over
    /// [`Self::cached_team_id`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cached_team_name: Option<String>,
}

/// On-disk profile shape. `label` is the legacy singular key; `labels` is what
/// current versions write. Unknown keys are ignored, matching historical
/// profile files.
#[derive(Deserialize)]
struct ProfileDe {
    #[serde(default)]
    auth: AuthKind,
    #[serde(default)]
    credential_storage: CredentialStorage,
    #[serde(default)]
    api_key: Option<String>,
    region: Region,
    #[serde(default)]
    label: Option<String>,
    #[serde(default)]
    labels: Option<Vec<String>>,
    #[serde(default)]
    oauth_client_id: Option<String>,
    #[serde(default)]
    oauth_base_url: Option<String>,
    #[serde(default)]
    oauth_tokens: Option<StoredOAuthTokens>,
    #[serde(default)]
    default_output_format: Option<OutputFormat>,
    #[serde(default)]
    default_tier: Option<crate::Tier>,
    #[serde(default)]
    console_url: Option<String>,
    #[serde(default)]
    cached_console_url: Option<String>,
    #[serde(default)]
    cached_console_url_at: Option<DateTime<Utc>>,
    #[serde(default)]
    cached_team_id: Option<i64>,
    #[serde(default)]
    cached_team_name: Option<String>,
}

impl From<ProfileDe> for Profile {
    fn from(file: ProfileDe) -> Self {
        Self {
            auth: file.auth,
            credential_storage: file.credential_storage,
            api_key: file.api_key,
            region: file.region,
            labels: labels_from_file(file.label, file.labels),
            oauth_client_id: file.oauth_client_id,
            oauth_base_url: file.oauth_base_url,
            oauth_tokens: file.oauth_tokens,
            default_output_format: file.default_output_format,
            default_tier: file.default_tier,
            console_url: file.console_url,
            cached_console_url: file.cached_console_url,
            cached_console_url_at: file.cached_console_url_at,
            cached_team_id: file.cached_team_id,
            cached_team_name: file.cached_team_name,
        }
    }
}

impl<'de> Deserialize<'de> for Profile {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(ProfileDe::deserialize(deserializer)?.into())
    }
}

/// Resolved configuration ready for use at runtime.
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
    /// The profile name this config was resolved from.
    pub profile_name: String,
    pub api_key: String,
    /// Authentication mechanism that produced the bearer token.
    pub auth_kind: AuthKind,
    pub endpoint: String,
    /// Default storage tier for DataPrime queries, resolved from the profile
    /// config. Falls back to `Archive` when the profile does not specify one.
    pub default_tier: crate::Tier,
    /// Explicit console base URL override from `Profile::console_url`, with
    /// any trailing slash trimmed. Takes precedence over the automatic
    /// `GET /identity/whoami`-based resolution.
    pub console_url: Option<String>,
    /// True when `api_key` came from a `--api-key`/`CX_API_KEY` override
    /// rather than the profile file's own stored credentials. When set, the
    /// profile's `console_url` and cached console URL must not be read or
    /// written, since they were resolved against a different team's
    /// credentials than the ones actually in use for this run.
    pub credentials_overridden: bool,
}

/// Returns the cx config directory: `~/.cx/`
pub fn config_dir() -> Result<PathBuf> {
    // CX_HOME overrides the home directory for testing and non-standard setups.
    if let Ok(cx_home) = std::env::var("CX_HOME") {
        return Ok(PathBuf::from(cx_home).join(".cx"));
    }
    let home = dirs::home_dir().context("Could not determine home directory")?;
    Ok(home.join(".cx"))
}

pub fn config_file() -> Result<PathBuf> {
    Ok(config_dir()?.join("config.toml"))
}

pub fn profiles_dir() -> Result<PathBuf> {
    Ok(config_dir()?.join("profiles"))
}

pub fn profile_file(name: &str) -> Result<PathBuf> {
    Ok(profiles_dir()?.join(format!("{name}.toml")))
}

/// List all profile names from `~/.cx/profiles/`, sorted alphabetically.
///
/// Returns an empty list (not an error) when the directory does not exist.
/// Silently skips entries whose filenames are not valid UTF-8 or whose
/// extension is not `toml`.
pub fn list_profile_names() -> Result<Vec<String>> {
    list_profile_names_from(&profiles_dir()?)
}

fn list_profile_names_from(dir: &PathBuf) -> Result<Vec<String>> {
    if !dir.exists() {
        return Ok(vec![]);
    }
    let mut names: Vec<String> = std::fs::read_dir(dir)?
        .filter_map(|entry| {
            let entry = entry.ok()?;
            let path = entry.path();
            if path.extension()?.to_str()? != "toml" {
                return None;
            }
            Some(path.file_stem()?.to_str()?.to_string())
        })
        .collect();
    names.sort();
    Ok(names)
}

/// Load the global config (non-fatal if missing - returns default).
pub fn load_config() -> Result<Config> {
    let path = config_file()?;
    if !path.exists() {
        return Ok(Config::default());
    }
    let raw = std::fs::read_to_string(&path)
        .with_context(|| format!("Failed to read {}", path.display()))?;
    toml::from_str(&raw).context("Failed to parse config.toml")
}

/// Write the global config to disk, creating directories as needed.
pub fn save_config(config: &Config) -> Result<()> {
    let dir = config_dir()?;
    std::fs::create_dir_all(&dir)?;
    let path = config_file()?;
    let content = toml::to_string_pretty(config).context("Failed to serialize config")?;
    std::fs::write(&path, content)
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(())
}

/// Load the output format preference from the first of the given profile names.
/// Returns `None` if no profile specifies one, or if the profile cannot be loaded.
pub fn first_profile_output_format(profiles: &[String]) -> Option<OutputFormat> {
    let name = if profiles.is_empty() {
        load_config().ok().map(|c| c.default_profile)
    } else {
        Some(profiles[0].clone())
    };
    name.and_then(|n| load_profile(&n).ok())
        .and_then(|p| p.default_output_format)
}

/// Load a named profile.
pub fn load_profile(name: &str) -> Result<Profile> {
    let path = profile_file(name)?;
    let raw = std::fs::read_to_string(&path).with_context(|| {
        format!("Profile '{name}' not found. Run `cx profiles add` to set it up.")
    })?;
    toml::from_str(&raw).with_context(|| format!("Failed to parse profile '{name}'"))
}

/// Move plaintext profile secrets into the platform credential store when an
/// IT-managed policy requires it.
///
/// This runs before most commands, so a profile that cannot be read or moved
/// is reported and skipped instead of blocking every command, including the
/// `cx profiles` commands that repair it. [`resolve_single`] retries the move
/// and refuses to use the plaintext copy.
pub fn migrate_managed_profiles_to_os_store() -> Result<()> {
    migrate_managed_profiles_with(
        crate::managed_policy::requires_os_store()?,
        list_profile_names,
        |name| {
            load_profile(name)
                .with_context(|| {
                    format!("Could not check profile '{name}' for plaintext credentials")
                })
                .and_then(|mut profile| migrate_profile_to_os_store(name, &mut profile))
                .map(|_| ())
        },
    )
}

fn migrate_managed_profiles_with(
    managed: bool,
    list_profiles: impl FnOnce() -> Result<Vec<String>>,
    migrate_profile: impl Fn(&str) -> Result<()>,
) -> Result<()> {
    if !managed {
        return Ok(());
    }

    for name in list_profiles()? {
        if let Err(err) = migrate_profile(&name) {
            eprintln!("Warning: {err:#}");
        }
    }
    Ok(())
}

/// Move one profile's plaintext secrets into the OS credential store. Returns
/// whether the profile file was rewritten.
fn migrate_profile_to_os_store(name: &str, profile: &mut Profile) -> Result<bool> {
    migrate_profile_with(name, profile, store_profile_secrets, save_profile)
}

/// The OS-store write happens before the profile file is rewritten, so a
/// failed write leaves the plaintext credentials where they were. An
/// `os_store` profile already keeps its secrets in the store, so stray
/// plaintext fields in its file are dropped rather than copied over them.
fn migrate_profile_with(
    name: &str,
    profile: &mut Profile,
    store: impl FnOnce(&str, &Profile) -> Result<()>,
    save: impl FnOnce(&str, &Profile) -> Result<()>,
) -> Result<bool> {
    let has_plaintext = profile.api_key.is_some() || profile.oauth_tokens.is_some();
    if profile.credential_storage == CredentialStorage::OsStore && !has_plaintext {
        return Ok(false);
    }
    if profile.credential_storage == CredentialStorage::File {
        store(name, profile).with_context(|| {
            format!(
                "Could not move the credentials of profile '{name}' into the OS credential \
                 store; its profile file was left unchanged"
            )
        })?;
    }
    profile.credential_storage = CredentialStorage::OsStore;
    profile.api_key = None;
    profile.oauth_tokens = None;
    save(name, profile)?;
    Ok(true)
}

fn store_profile_secrets(name: &str, profile: &Profile) -> Result<()> {
    let stored = match profile.auth {
        AuthKind::ApiKey => match profile.api_key.as_deref() {
            Some(api_key) => keyring_store::store_secret(name, "api_key", api_key),
            None => Ok(()),
        },
        AuthKind::OAuth => match profile.oauth_tokens.as_ref() {
            Some(tokens) => oauth::store_stored_tokens_keyring(name, tokens),
            None => Ok(()),
        },
    };
    // Clear any partial keyring writes from a failed multi-key store. The
    // profile file still says `file`, so `cx profiles delete` would not.
    stored.inspect_err(|_| keyring_store::delete_profile(name))
}

/// Browser re-login is for a person at a terminal. Stdout must be a terminal
/// too: `cx ... -o json | jq` keeps stdin attached but must not open a browser
/// or write login progress into the JSON stream. A coding agent keeps the error
/// instead of blocking on a browser for five minutes.
fn interactive_reauth_allowed() -> bool {
    std::io::stdin().is_terminal()
        && std::io::stdout().is_terminal()
        && !crate::safety::is_agent_mode()
}

fn normalize_team_url(url: &str) -> &str {
    url.trim().trim_end_matches('/')
}

/// A browser sign-in that landed in a different team than the profile last
/// used. Split into parts so the interactive path can print the explanation,
/// ask about a retry naming `select`, and reserve `recovery` for giving up.
struct TeamConflict {
    /// What mismatched, e.g. "Signed in to team 'other' (id 99), but profile
    /// 'default' was last used with team 'c4c' (id 12)."
    explanation: String,
    /// The team the retry (or `cx profiles refresh`) should pick, as a display
    /// label: "team 'c4c' (id 12)", "team id 12", or a console URL.
    select: String,
    /// The give-up instruction: tokens were not saved, re-run `cx profiles
    /// refresh` and pick `select`.
    recovery: String,
}

impl std::fmt::Display for TeamConflict {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}\n{}", self.explanation, self.recovery)
    }
}

/// `Some` when this sign-in is a different team than the profile last used.
/// `None` when it matches, or when the profile has no recorded team yet.
fn reauth_team_conflict(
    profile_name: &str,
    profile: &Profile,
    whoami: &crate::identity::Whoami,
) -> Option<TeamConflict> {
    let signed_in = whoami.team_name.as_deref().unwrap_or("unknown");
    let conflict = |explanation: String, select: String| TeamConflict {
        explanation,
        recovery: format!(
            "Tokens were not saved. Run `cx profiles refresh {profile_name}` and select {select}."
        ),
        select,
    };
    if let Some(previous_id) = profile.cached_team_id {
        let original = team_to_select(profile, &format!("team id {previous_id}"));
        return match whoami.team_id {
            Some(id) if id == previous_id => None,
            Some(id) => Some(conflict(
                format!(
                    "Signed in to team '{signed_in}' (id {id}), but profile '{profile_name}' was last used with {original}."
                ),
                original,
            )),
            None => Some(conflict(
                format!(
                    "Sign-in did not report a team id, so it was not saved for profile '{profile_name}'."
                ),
                original,
            )),
        };
    }
    let previous_url = profile.cached_console_url.as_deref()?;
    let previous_url = normalize_team_url(previous_url);
    let select = team_to_select(profile, previous_url);
    match whoami
        .team_url
        .as_deref()
        .map(normalize_team_url)
        .filter(|url| !url.is_empty())
    {
        Some(url) if url == previous_url => None,
        Some(url) => Some(conflict(
            format!(
                "Signed in to team '{signed_in}' ({url}), but profile '{profile_name}' was last used with {previous_url}."
            ),
            select,
        )),
        None => Some(conflict(
            format!(
                "Sign-in did not report a team, so it was not saved for profile '{profile_name}'."
            ),
            select,
        )),
    }
}

/// Label for the team a re-login (or `cx profiles refresh`) should pick. The browser picker
/// lists names; the id (or console URL) is only the fallback when this
/// profile was cached before the name was stored.
fn cached_display_name(profile: &Profile) -> Option<&str> {
    profile
        .cached_team_name
        .as_deref()
        .map(str::trim)
        .filter(|name| !name.is_empty())
}

fn team_to_select(profile: &Profile, fallback: &str) -> String {
    match cached_display_name(profile) {
        Some(name) => match profile.cached_team_id {
            Some(id) => format!("team '{name}' (id {id})"),
            None => format!("team '{name}'"),
        },
        None => fallback.to_string(),
    }
}

/// `true` when the profile changed and is worth persisting. That includes a
/// pure TTL refresh of an unchanged console URL, not only new values.
pub(crate) fn remember_signed_in_team(
    profile: &mut Profile,
    whoami: &crate::identity::Whoami,
) -> bool {
    let mut changed = false;
    if let Some(id) = whoami.team_id {
        if profile.cached_team_id != Some(id) {
            profile.cached_team_id = Some(id);
            changed = true;
        }
    }
    if let Some(name) = whoami
        .team_name
        .as_deref()
        .map(str::trim)
        .filter(|name| !name.is_empty())
    {
        if profile.cached_team_name.as_deref() != Some(name) {
            profile.cached_team_name = Some(name.to_string());
            changed = true;
        }
    }
    if let Some(url) = whoami
        .team_url
        .as_deref()
        .map(normalize_team_url)
        .filter(|url| !url.is_empty())
    {
        if profile.cached_console_url.as_deref() != Some(url) {
            profile.cached_console_url = Some(url.to_string());
        }
        // The TTL is what skips the next whoami. An unchanged URL still has
        // to refresh it, or a lapsed cache stays cold forever.
        profile.cached_console_url_at = Some(Utc::now());
        changed = true;
    }
    changed
}

/// The OAuth server and client ID an OAuth profile signs in with.
fn oauth_login_target(profile_name: &str, profile: &Profile) -> Result<(String, String)> {
    let region_name = profile.region.to_string();
    let base_url = profile
        .oauth_base_url
        .clone()
        .unwrap_or_else(|| profile.region.api_endpoint().to_string());
    let client_id = profile
        .oauth_client_id
        .clone()
        .or_else(|| oauth::client_id_for_region(&region_name).map(str::to_string))
        .ok_or_else(|| {
            anyhow::anyhow!(
                "No OAuth client ID configured for profile '{profile_name}' \
                 (region: {region_name}).\n\
                 Run `cx profiles add {profile_name}` to reconfigure."
            )
        })?;
    Ok((base_url, client_id))
}

/// Browser sign-in for an existing OAuth profile. The consent page shows only
/// the team this profile last used, preselected. A sign-in to a different team
/// is refused, and the user is offered another browser round. With
/// `region_overridden`, the sign-in is for another endpoint, so it is neither
/// narrowed to nor checked against this profile's team.
async fn sign_in_to_profile_team(
    profile_name: &str,
    profile: &Profile,
    base_url: &str,
    client_id: &str,
    region_overridden: bool,
) -> Result<(oauth::TokenResponse, crate::identity::Whoami)> {
    let mut login = oauth::LoginOptions {
        force_account_selection: false,
        team_id: if region_overridden {
            None
        } else {
            profile.cached_team_id
        },
        signup: false,
    };
    loop {
        let tokens = oauth::browser_login(base_url, client_id, login.clone()).await?;
        let client =
            crate::api_client::CxClient::new(profile.region.api_endpoint(), &tokens.access_token)?;
        let whoami = crate::identity::verify_identity(&client).await.context(
            "Could not confirm which team this sign-in belongs to, so the new tokens were not saved.",
        )?;
        if region_overridden {
            return Ok((tokens, whoami));
        }
        let Some(conflict) = reauth_team_conflict(profile_name, profile, &whoami) else {
            return Ok((tokens, whoami));
        };
        eprintln!("{}", conflict.explanation);
        let retry =
            inquire::Confirm::new(&format!("Sign in again and select {}?", conflict.select))
                .with_default(true)
                .prompt()
                .unwrap_or(false);
        if !retry {
            anyhow::bail!("{}", conflict.recovery);
        }
        // The browser still holds the wrong team's SSO session; ask the IdP
        // to show the picker again.
        login.force_account_selection = true;
    }
}

/// Store new sign-in tokens on the profile's credential backend and return the
/// access token. The OS keyring is written here; for file storage the tokens
/// go on `profile`, and the caller saves the profile. If the keyring write
/// fails, the profile moves to file storage so the sign-in is not lost. While
/// an IT policy requires the OS store, the tokens always go there (replacing
/// any in the profile file) and a failed write is an error.
fn keep_signed_in_tokens(
    profile_name: &str,
    profile: &mut Profile,
    tokens: &oauth::TokenResponse,
) -> Result<String> {
    let managed = crate::managed_policy::requires_os_store()?;
    keep_signed_in_tokens_with(
        profile_name,
        profile,
        tokens,
        managed,
        oauth::store_tokens_keyring,
    )
}

fn keep_signed_in_tokens_with(
    profile_name: &str,
    profile: &mut Profile,
    tokens: &oauth::TokenResponse,
    managed: bool,
    store: impl FnOnce(&str, &oauth::TokenResponse) -> Result<()>,
) -> Result<String> {
    if managed {
        profile.credential_storage = CredentialStorage::OsStore;
        profile.oauth_tokens = None;
    }
    if profile.credential_storage == CredentialStorage::OsStore {
        match store(profile_name, tokens) {
            Ok(()) => return Ok(tokens.access_token.clone()),
            Err(err) => {
                // Clear any partial keyring writes from a failed multi-key store.
                keyring_store::delete_profile(profile_name);
                if managed {
                    anyhow::bail!(
                        "Failed to store OAuth tokens in the OS credential store ({err}). \
                         File credential storage is disabled by your organization's policy."
                    );
                }
                eprintln!(
                    "Warning: failed to store OAuth tokens in the OS credential store ({err}); \
                     migrated profile '{profile_name}' to file storage."
                );
                profile.credential_storage = CredentialStorage::File;
            }
        }
    }
    profile.oauth_tokens = Some(oauth::tokens_to_stored(tokens));
    Ok(tokens.access_token.clone())
}

/// `cx profiles refresh <name>`: sign an OAuth profile in again without
/// reconfiguring it. Region, storage, output format and labels stay as they
/// are; only the tokens (and the cached team) change. A legacy `label` string
/// is loaded into `labels` and written back under that key, with the same
/// values.
pub async fn refresh_oauth_profile(profile_name: &str) -> Result<()> {
    let mut profile = load_profile(profile_name)?;
    if profile.auth != AuthKind::OAuth {
        anyhow::bail!(
            "Profile '{profile_name}' uses an API key, so there is no sign-in to refresh.\n\
             Run `cx profiles add {profile_name}` to change its credentials."
        );
    }
    let (base_url, client_id) = oauth_login_target(profile_name, &profile)?;
    let (tokens, whoami) =
        sign_in_to_profile_team(profile_name, &profile, &base_url, &client_id, false).await?;
    remember_signed_in_team(&mut profile, &whoami);
    keep_signed_in_tokens(profile_name, &mut profile, &tokens)?;
    save_profile(profile_name, &profile)?;
    let team = whoami.team_name.as_deref().unwrap_or("this team");
    println!("Signed in to team '{team}'. Profile '{profile_name}' is ready.");
    Ok(())
}

/// Resolve a single named profile, respecting optional CLI overrides.
///
/// Resolution order for the bearer token:
///   1. `--api-key` CLI flag (explicit command-line value, always wins)
///   2. Profile credentials (when `--profile` is explicit on the CLI, the
///      profile's own key/token is used; `CX_API_KEY` env var is suppressed
///      by `main.rs` in this case)
///   3. `CX_API_KEY` env var (when no `--profile` was explicitly passed)
///
/// Resolution order for the endpoint region:
///   1. `--region` CLI flag (explicit command-line value, always wins)
///   2. Profile's configured region (when `--profile` is explicit on the CLI;
///      `CX_REGION` env var is suppressed by `main.rs`)
///   3. `CX_REGION` env var (when no `--profile` was explicitly passed)
///
/// Env-only mode: when no profile file exists on disk but both an API key
/// override (`--api-key` / `CX_API_KEY`) and a region override (`--region` /
/// `CX_REGION`) are supplied, a `ResolvedConfig` is synthesised directly. This
/// lets ephemeral environments (CI runners, containers, ad-hoc scripts) run
/// `cx` without first invoking `cx profiles add`.
async fn resolve_single(
    profile_name: &str,
    api_key_override: Option<&str>,
    region_override: Option<&str>,
) -> Result<ResolvedConfig> {
    if !profile_file(profile_name)?.exists() {
        if let (Some(key), Some(region)) = (api_key_override, region_override) {
            let region: Region = region.parse()?;
            return Ok(ResolvedConfig {
                profile_name: profile_name.to_string(),
                endpoint: region.api_endpoint().to_string(),
                api_key: key.to_string(),
                auth_kind: AuthKind::ApiKey,
                default_tier: crate::Tier::Archive,
                console_url: None,
                credentials_overridden: true,
            });
        }
    }

    let mut profile = load_profile(profile_name)?;
    let managed = crate::managed_policy::requires_os_store()?;
    if managed && api_key_override.is_none() {
        migrate_profile_to_os_store(profile_name, &mut profile).with_context(|| {
            format!(
                "File credential storage is disabled by your organization's policy. Replace \
                 the profile with `cx profiles add {profile_name} --force`, or remove it with \
                 `cx profiles delete {profile_name}`"
            )
        })?;
    }
    // `--region` is for this invocation only. The profile object is what
    // later gets saved, so remember the on-disk region and put it back
    // before any write.
    let stored_region = profile.region.clone();
    let region_overridden = region_override.is_some();

    if let Some(region) = region_override {
        profile.region = region.parse()?;
    }

    // CLI-level api_key_override (already filtered by main.rs) wins over profile creds.
    let auth_kind = if api_key_override.is_some() {
        AuthKind::ApiKey
    } else {
        profile.auth
    };
    let bearer = match auth_kind {
        AuthKind::ApiKey => {
            if let Some(key) = api_key_override {
                key.to_string()
            } else {
                match profile.credential_storage {
                    CredentialStorage::OsStore => {
                        keyring_store::get_secret(profile_name, "api_key")?
                    }
                    CredentialStorage::File => profile.api_key.clone(),
                }
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "No API key found for profile '{profile_name}'.\n\
                             Run `cx profiles add {profile_name}` to set it up."
                    )
                })?
            }
        }
        AuthKind::OAuth => {
            debug_assert!(api_key_override.is_none());
            let (base_url, client_id) = oauth_login_target(profile_name, &profile)?;
            let storage = profile.credential_storage;
            let resolved = oauth::resolve_token(
                profile_name,
                &base_url,
                &client_id,
                storage,
                profile.oauth_tokens.as_ref(),
            )
            .await;
            let (bearer, refreshed, os_store_fallback_reason, persist_profile) = match resolved {
                Ok(oauth::TokenResolution {
                    bearer,
                    refreshed_tokens,
                    os_store_fallback_reason,
                }) => {
                    let persist = refreshed_tokens.is_some();
                    (bearer, refreshed_tokens, os_store_fallback_reason, persist)
                }
                Err(error) if oauth::is_reauth_required(&error) && interactive_reauth_allowed() => {
                    // The refresh token is missing or rejected. Sign in in the
                    // browser, keep the tokens only when they are for the same
                    // team, and continue this command. A wrong-team sign-in
                    // offers another browser round instead of stopping at
                    // "run cx profiles refresh".
                    eprintln!(
                        "OAuth session for profile '{profile_name}' expired. Sign in to continue."
                    );
                    let (tokens, whoami) = sign_in_to_profile_team(
                        profile_name,
                        &profile,
                        &base_url,
                        &client_id,
                        region_overridden,
                    )
                    .await?;
                    let team = whoami.team_name.as_deref().unwrap_or("this team");
                    eprintln!("Signed in to team '{team}'. Continuing.");
                    // A browser login under `--region` is for this command's
                    // endpoint. Keep those tokens in memory on both backends.
                    // A silent refresh still persists, so a rotated refresh
                    // token is not discarded.
                    let bearer = if region_overridden {
                        tokens.access_token
                    } else {
                        remember_signed_in_team(&mut profile, &whoami);
                        keep_signed_in_tokens(profile_name, &mut profile, &tokens)?
                    };
                    (bearer, None, None, !region_overridden)
                }
                Err(error) => return Err(error),
            };
            if let Some(new_tokens) = refreshed {
                // File-storage profile, or an OS-store refresh that could not
                // be written to the keyring: persist the tokens to disk.
                keep_refreshed_tokens(
                    &mut profile,
                    new_tokens,
                    os_store_fallback_reason.as_deref(),
                    managed,
                )
                // Clear any partial keyring writes, as a failed sign-in does.
                .inspect_err(|_| keyring_store::delete_profile(profile_name))?;
            }
            if persist_profile {
                // Save tokens (and, after a same-team sign-in, team identity)
                // without writing a one-shot `--region` into the profile.
                let mut to_save = profile.clone();
                to_save.region = stored_region;
                save_profile(profile_name, &to_save)?;
                if os_store_fallback_reason.is_some() {
                    // Save the file-backed profile before removing any old or
                    // partially written keyring entries.
                    keyring_store::delete_profile(profile_name);
                    eprintln!(
                        "Warning: failed to store refreshed OAuth tokens in the OS credential \
                         store; migrated profile '{profile_name}' to file storage."
                    );
                }
            }
            // A profile that has not recorded its team (created before
            // `cx profiles add` stored it) learns it while the token still
            // works, so its first expired-session re-login is narrowed to
            // that team. One whoami, only until it succeeds.
            if profile.cached_team_id.is_none() && !region_overridden {
                if let Some(whoami) =
                    crate::identity::lookup_whoami_bounded(profile.region.api_endpoint(), &bearer)
                        .await
                {
                    cache_team_identity(profile_name, &whoami);
                }
            }
            bearer
        }
    };

    Ok(ResolvedConfig {
        profile_name: profile_name.to_string(),
        endpoint: profile.region.api_endpoint().to_string(),
        api_key: bearer,
        auth_kind,
        default_tier: profile.default_tier.unwrap_or(crate::Tier::Archive),
        console_url: profile
            .console_url
            .as_deref()
            .map(|s| s.trim_end_matches('/').to_string()),
        credentials_overridden: api_key_override.is_some(),
    })
}

/// Put a refreshed token set on `profile` for the caller to save. When the
/// OS-store write failed, the profile moves to file storage, unless an IT
/// policy requires the OS store.
fn keep_refreshed_tokens(
    profile: &mut Profile,
    tokens: StoredOAuthTokens,
    os_store_error: Option<&str>,
    managed: bool,
) -> Result<()> {
    if let Some(err) = os_store_error {
        if managed {
            anyhow::bail!(
                "Failed to store refreshed OAuth tokens in the OS credential store ({err}). \
                 File credential storage is disabled by your organization's policy."
            );
        }
        profile.credential_storage = CredentialStorage::File;
    }
    profile.oauth_tokens = Some(tokens);
    Ok(())
}

/// Resolve the active profile, respecting CLI overrides.
///
/// When `profile_override` is `None`, falls back to the default profile in config.
pub async fn resolve(
    profile_override: Option<&str>,
    api_key_override: Option<&str>,
    region_override: Option<&str>,
) -> Result<ResolvedConfig> {
    let config = load_config()?;
    let name = profile_override.unwrap_or(&config.default_profile);
    resolve_single(name, api_key_override, region_override).await
}

/// Resolve one or more named profiles into a list of `ResolvedConfig` values.
///
/// When `profiles` is empty, falls back to the single default profile from config.
/// Overrides (`api_key_override`, `region_override`) are applied uniformly to every
/// resolved profile - the caller should reject these when `profiles.len() > 1`.
pub async fn resolve_all(
    profiles: &[String],
    api_key_override: Option<&str>,
    region_override: Option<&str>,
) -> Result<Vec<ResolvedConfig>> {
    if profiles.is_empty() {
        let cfg = load_config()?;
        return Ok(vec![
            resolve_single(&cfg.default_profile, api_key_override, region_override).await?,
        ]);
    }
    let mut results = Vec::with_capacity(profiles.len());
    for name in profiles {
        results.push(resolve_single(name, api_key_override, region_override).await?);
    }
    Ok(results)
}

/// Write a profile to disk, creating directories as needed.
/// Sets file permissions to 0600 on Unix to protect any inline secrets.
pub fn save_profile(name: &str, profile: &Profile) -> Result<()> {
    let dir = profiles_dir()?;
    std::fs::create_dir_all(&dir)?;
    let path = dir.join(format!("{name}.toml"));
    let content = toml::to_string_pretty(profile).context("Failed to serialize profile")?;
    std::fs::write(&path, &content)
        .with_context(|| format!("Failed to write {}", path.display()))?;
    #[cfg(unix)]
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
        .with_context(|| format!("Failed to set permissions on {}", path.display()))?;
    Ok(())
}

/// Return the profile's cached team console base URL, but only if it is still
/// fresh (resolved within [`CONSOLE_URL_CACHE_TTL_DAYS`]).
///
/// Best-effort and silent: returns `None` for a missing/unreadable profile
/// (e.g. env-only mode, where there is no profile file to cache against), an
/// absent cache, or a stale entry - all of which simply fall back to a live
/// `GET /identity/whoami` lookup.
pub fn load_cached_console_url(profile_name: &str) -> Option<String> {
    let profile = load_profile(profile_name).ok()?;
    let cached_at = profile.cached_console_url_at?;
    if Utc::now() - cached_at < Duration::days(CONSOLE_URL_CACHE_TTL_DAYS) {
        profile.cached_console_url
    } else {
        None
    }
}

/// Persist the team from `GET /identity/whoami` into the profile file, so
/// future invocations can skip the round-trip when printing console links and
/// a later OAuth re-login can refuse a different team.
///
/// Best-effort and silent, mirroring the OAuth-token write-back in
/// `resolve_single`: any failure (no profile file - e.g. env-only mode - or an
/// unwritable config dir) is ignored, since the cache is a "nice to have"
/// that must never fail an otherwise-successful command.
pub fn cache_team_identity(profile_name: &str, whoami: &crate::identity::Whoami) {
    let Ok(mut profile) = load_profile(profile_name) else {
        return;
    };
    if remember_signed_in_team(&mut profile, whoami) {
        let _ = save_profile(profile_name, &profile);
    }
}

// ── Managed completion helpers ────────────────────────────────────────────────

/// Returns `true` when at least one completion file is tracked in the config.
/// Non-fatal: returns `false` if the config cannot be read.
pub fn has_managed_completions() -> bool {
    load_config()
        .map(|c| !c.managed_completions.is_empty())
        .unwrap_or(false)
}

/// Return the tracked managed completion entries from the global config.
pub fn managed_completions() -> Result<Vec<ManagedCompletion>> {
    Ok(load_config()?.managed_completions)
}

/// Add or update a managed completion entry for the given shell and path.
///
/// If an entry for this shell already exists, its path is updated in place.
/// The updated config is persisted to `~/.cx/config.toml`.
pub fn upsert_managed_completion(shell: &str, path: PathBuf) -> Result<()> {
    let mut config = load_config().unwrap_or_default();
    if let Some(existing) = config
        .managed_completions
        .iter_mut()
        .find(|c| c.shell == shell)
    {
        existing.path = path;
    } else {
        config.managed_completions.push(ManagedCompletion {
            shell: shell.to_string(),
            path,
        });
    }
    save_config(&config)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── OutputFormat: toon canonical + agents backward-compat alias ─────────────

    #[test]
    fn output_format_as_str_is_toon() {
        assert_eq!(OutputFormat::Toon.as_str(), "toon");
        assert_eq!(OutputFormat::Toon.to_string(), "toon");
    }

    #[test]
    fn output_format_serializes_as_toon() {
        // New configs are written with the canonical `toon` spelling.
        let json = serde_json::to_string(&OutputFormat::Toon).unwrap();
        assert_eq!(json, "\"toon\"");
    }

    #[test]
    fn output_format_deserializes_toon_and_agents_alias() {
        // Canonical value.
        let toon: OutputFormat = serde_json::from_str("\"toon\"").unwrap();
        assert_eq!(toon, OutputFormat::Toon);
        // Backward compat: existing profiles/config with `default_output_format = "agents"`
        // must still deserialize rather than fail.
        let agents: OutputFormat = serde_json::from_str("\"agents\"").unwrap();
        assert_eq!(agents, OutputFormat::Toon);
    }

    #[test]
    fn output_format_profile_toml_accepts_agents_alias() {
        // Simulate an on-disk profile that predates the rename.
        let profile: Profile =
            toml::from_str("region = \"eu2\"\ndefault_output_format = \"agents\"\n").unwrap();
        assert_eq!(profile.default_output_format, Some(OutputFormat::Toon));
    }

    #[test]
    fn output_format_clap_parses_toon_and_agents_alias() {
        use clap::ValueEnum;
        assert_eq!(
            OutputFormat::from_str("toon", true).unwrap(),
            OutputFormat::Toon
        );
        // `-o agents` on the CLI still resolves to the Toon variant.
        assert_eq!(
            OutputFormat::from_str("agents", true).unwrap(),
            OutputFormat::Toon
        );
    }

    // ── list_profile_names_from ────────────────────────────────────────────────

    #[test]
    fn list_profile_names_sorted_and_filters_non_toml() {
        let dir =
            std::env::temp_dir().join(format!("cx_test_list_profiles_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();

        std::fs::write(dir.join("prod.toml"), "").unwrap();
        std::fs::write(dir.join("staging.toml"), "").unwrap();
        std::fs::write(dir.join("alpha.toml"), "").unwrap();
        std::fs::write(dir.join("ignored.txt"), "").unwrap();
        std::fs::write(dir.join("also-ignored.json"), "").unwrap();

        let names = list_profile_names_from(&dir).unwrap();
        assert_eq!(names, vec!["alpha", "prod", "staging"]);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn list_profile_names_missing_dir_returns_empty() {
        let dir = std::env::temp_dir().join("cx_test_nonexistent_profiles_dir_xyz_never_created");
        // Ensure it really does not exist.
        let _ = std::fs::remove_dir_all(&dir);
        let names = list_profile_names_from(&dir).unwrap();
        assert!(names.is_empty());
    }

    #[test]
    fn list_profile_names_empty_dir_returns_empty() {
        let dir =
            std::env::temp_dir().join(format!("cx_test_empty_profiles_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();

        let names = list_profile_names_from(&dir).unwrap();
        assert!(names.is_empty());

        std::fs::remove_dir_all(&dir).unwrap();
    }

    // ── ManagedCompletion / upsert_managed_completion ─────────────────────────

    #[test]
    fn managed_completion_roundtrips_through_toml() {
        let mc = ManagedCompletion {
            shell: "zsh".to_string(),
            path: PathBuf::from("/home/user/.zfunc/_cx"),
        };
        let config = Config {
            managed_completions: vec![mc.clone()],
            ..Config::default()
        };
        let toml = toml::to_string_pretty(&config).unwrap();
        let restored: Config = toml::from_str(&toml).unwrap();
        assert_eq!(restored.managed_completions.len(), 1);
        assert_eq!(restored.managed_completions[0], mc);
    }

    #[test]
    fn default_config_has_no_managed_completions() {
        let config = Config::default();
        assert!(config.managed_completions.is_empty());
    }

    #[test]
    fn config_without_managed_completions_field_deserialises_ok() {
        let toml = r#"
default_profile = "my-profile"
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(config.managed_completions.is_empty());
        assert_eq!(config.default_profile, "my-profile");
    }

    #[test]
    fn managed_completions_not_written_when_empty() {
        let config = Config::default();
        let toml = toml::to_string_pretty(&config).unwrap();
        assert!(
            !toml.contains("managed_completions"),
            "empty managed_completions should be skipped in TOML output"
        );
    }

    // ── Unit tests (no disk I/O) ───────────────────────────────────────────────

    /// Build a `ResolvedConfig` directly without touching the filesystem, by
    /// testing the field-level properties that `resolve_single` must guarantee.
    #[test]
    fn resolved_config_carries_profile_name() {
        let cfg = ResolvedConfig {
            profile_name: "prod".to_string(),
            api_key: "k".to_string(),
            auth_kind: AuthKind::ApiKey,
            endpoint: "https://api.eu2.coralogix.com".to_string(),
            default_tier: crate::Tier::Archive,
            console_url: None,
            credentials_overridden: false,
        };
        assert_eq!(cfg.profile_name, "prod");
    }

    #[test]
    fn region_api_endpoint_eu1() {
        assert_eq!(Region::Eu1.api_endpoint(), "https://api.eu1.coralogix.com");
    }

    #[test]
    fn region_api_endpoint_us1() {
        assert_eq!(Region::Us1.api_endpoint(), "https://api.us1.coralogix.com");
    }

    #[test]
    fn region_app_url_template_eu2() {
        assert_eq!(
            Region::Eu2.app_url_template(),
            Some("app.eu2.coralogix.com")
        );
    }

    #[test]
    fn region_app_url_template_us2_uses_cx498() {
        assert_eq!(
            Region::Us2.app_url_template(),
            Some("app.cx498.coralogix.com")
        );
    }

    #[test]
    fn region_app_url_template_custom_is_none() {
        assert_eq!(
            Region::Custom("https://api.myenv.example.com".into()).app_url_template(),
            None
        );
    }

    #[test]
    fn every_named_region_has_an_app_url_template() {
        let cases: &[(Region, &str)] = &[
            (Region::Us1, "app.coralogix.us"),
            (Region::Us2, "app.cx498.coralogix.com"),
            (Region::Us3, "app.us3.coralogix.com"),
            (Region::Eu1, "coralogix.com"),
            (Region::Eu2, "app.eu2.coralogix.com"),
            (Region::Ap1, "app.coralogix.in"),
            (Region::Ap2, "app.coralogixsg.com"),
            (Region::Ap3, "app.ap3.coralogix.com"),
            (Region::Stg1, "app.stg1.coralogix.net"),
        ];
        for (region, expected) in cases {
            assert_eq!(region.app_url_template(), Some(*expected), "{region}");
        }
    }

    #[test]
    fn region_parses_from_str() {
        let r: Region = "eu2".parse().unwrap();
        assert_eq!(r.api_endpoint(), "https://api.eu2.coralogix.com");
    }

    #[test]
    fn region_custom_roundtrip() {
        let url = "https://custom.endpoint.io";
        let r: Region = url.parse().unwrap();
        assert_eq!(r.api_endpoint(), url);
    }

    /// Legacy TOML without `auth` field must deserialise as `AuthKind::ApiKey`.
    #[test]
    fn profile_without_auth_field_defaults_to_api_key() {
        let toml = r#"
region = "eu1"
api_key = "mykey"
"#;
        let p: Profile = toml::from_str(toml).unwrap();
        assert_eq!(p.auth, AuthKind::ApiKey);
        assert_eq!(p.api_key.as_deref(), Some("mykey"));
        assert!(p.labels.is_empty());
        assert!(p.oauth_client_id.is_none());
        assert!(p.oauth_base_url.is_none());
    }

    fn assert_no_legacy_label_key(toml_text: &str) {
        assert!(
            toml_text.lines().all(|line| {
                let trimmed = line.trim_start();
                !trimmed.starts_with("label ") && !trimmed.starts_with("label=")
            }),
            "legacy label key should not be written, got: {toml_text}"
        );
    }

    fn profile_with_labels(labels: Vec<String>) -> Profile {
        Profile {
            auth: AuthKind::ApiKey,
            credential_storage: CredentialStorage::File,
            api_key: None,
            region: Region::Eu1,
            labels,
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        }
    }

    #[test]
    fn normalize_labels_trims_drops_empties_and_duplicates() {
        assert_eq!(
            normalize_labels([" prod ", "", "prod", "eu", " eu ", "  "]),
            vec!["prod".to_string(), "eu".to_string()]
        );
        // Case-sensitive: "Prod" and "prod" are different labels.
        assert_eq!(
            normalize_labels(["Prod", "prod"]),
            vec!["Prod".to_string(), "prod".to_string()]
        );
    }

    #[test]
    fn parse_label_args_splits_commas_and_repeated_flags() {
        assert_eq!(
            parse_label_args([" prod, eu ", "eu", " staging ", ",", "prod"]),
            vec!["prod".to_string(), "eu".to_string(), "staging".to_string()]
        );
        assert!(parse_label_args(["", "  ", ","]).is_empty());
    }

    /// Existing configs store one `label` string. That key must still load, as
    /// a one-item list, including surrounding whitespace being trimmed.
    fn labelled(name: &str, labels: &[&str]) -> (String, Vec<String>) {
        (
            name.to_string(),
            labels.iter().map(|l| l.to_string()).collect(),
        )
    }

    fn strings(values: &[&str]) -> Vec<String> {
        values.iter().map(|v| v.to_string()).collect()
    }

    #[test]
    fn has_any_label_is_exact_and_any_match() {
        let labels = strings(&["prod", "eu"]);
        assert!(has_any_label(&labels, &strings(&["eu"])));
        assert!(has_any_label(&labels, &strings(&["missing", "prod"])));
        assert!(!has_any_label(&labels, &strings(&["PROD"])));
        assert!(!has_any_label(&labels, &strings(&["pro"])));
        assert!(!has_any_label(&labels, &[]));
        assert!(!has_any_label(&[], &strings(&["prod"])));
    }

    #[test]
    fn names_with_any_label_keeps_list_order_and_skips_unlabelled() {
        let entries = vec![
            labelled("a", &["prod", "eu"]),
            labelled("b", &[]),
            labelled("c", &["staging"]),
            labelled("d", &["prod"]),
        ];
        assert_eq!(
            names_with_any_label(&entries, &strings(&["prod"])),
            strings(&["a", "d"])
        );
        assert_eq!(
            names_with_any_label(&entries, &strings(&["staging", "eu"])),
            strings(&["a", "c"])
        );
        assert!(names_with_any_label(&entries, &strings(&["qa"])).is_empty());
    }

    #[test]
    fn no_profiles_for_labels_message_lists_every_label() {
        assert_eq!(
            no_profiles_for_labels(&strings(&["prod"])),
            "No profiles with label 'prod'."
        );
        assert_eq!(
            no_profiles_for_labels(&strings(&["a", "b", "c"])),
            "No profiles with label 'a', 'b' or 'c'."
        );
    }

    #[test]
    fn parse_given_label_args_rejects_only_a_given_but_empty_list() {
        assert_eq!(
            parse_given_label_args::<&str>(&[]).unwrap(),
            Vec::<String>::new()
        );
        assert_eq!(parse_given_label_args(&["a,b"]).unwrap(), vec!["a", "b"]);
        for raw in [vec![""], vec![","], vec![" ", ""]] {
            let err = parse_given_label_args(&raw).unwrap_err().to_string();
            assert!(err.contains("non-empty label"), "{raw:?}: {err}");
        }
    }

    #[test]
    fn select_profile_names_without_labels_returns_explicit_names_unchanged() {
        // No disk access happens on this path, so it is safe without CX_HOME.
        assert_eq!(
            select_profile_names(&strings(&["b", "a"]), &[]).unwrap(),
            strings(&["b", "a"])
        );
        assert!(select_profile_names(&[], &[]).unwrap().is_empty());
    }

    #[test]
    fn legacy_label_string_loads_as_one_item_list() {
        let profile: Profile = toml::from_str("region = \"eu1\"\nlabel = \"  prod  \"\n").unwrap();
        assert_eq!(profile.labels, vec!["prod".to_string()]);
    }

    /// The legacy field is a single label, so a comma inside it is not a
    /// separator. Splitting commas is a CLI-flag convenience only.
    #[test]
    fn legacy_label_string_is_not_split_on_commas() {
        let profile: Profile = toml::from_str("region = \"eu1\"\nlabel = \"prod,eu\"\n").unwrap();
        assert_eq!(profile.labels, vec!["prod,eu".to_string()]);
    }

    #[test]
    fn legacy_blank_label_loads_as_no_labels() {
        let profile: Profile = toml::from_str("region = \"eu1\"\nlabel = \"   \"\n").unwrap();
        assert!(profile.labels.is_empty());
    }

    #[test]
    fn labels_array_preserves_order_and_normalizes_on_load() {
        let toml_text = r#"
region = "eu1"
labels = [" eu ", "prod", "eu", "", "staging"]
"#;
        let profile: Profile = toml::from_str(toml_text).unwrap();
        assert_eq!(
            profile.labels,
            vec!["eu".to_string(), "prod".to_string(), "staging".to_string()]
        );
    }

    /// When both keys are present, the canonical `labels` array wins. An empty
    /// `labels` array still falls back to the legacy string so a half-migrated
    /// file does not drop the only label it has.
    #[test]
    fn labels_array_wins_over_legacy_label_unless_empty() {
        let both: Profile =
            toml::from_str("region = \"eu1\"\nlabel = \"old\"\nlabels = [\"prod\", \"eu\"]\n")
                .unwrap();
        assert_eq!(both.labels, vec!["prod".to_string(), "eu".to_string()]);

        let empty_array: Profile =
            toml::from_str("region = \"eu1\"\nlabel = \"old\"\nlabels = []\n").unwrap();
        assert_eq!(empty_array.labels, vec!["old".to_string()]);
    }

    #[test]
    fn labels_round_trip_writes_labels_key_only() {
        let profile = profile_with_labels(vec!["prod".to_string(), "eu".to_string()]);
        let toml_text = toml::to_string_pretty(&profile).unwrap();
        assert!(
            toml_text.contains("labels"),
            "expected labels key, got: {toml_text}"
        );
        assert_no_legacy_label_key(&toml_text);
        let restored: Profile = toml::from_str(&toml_text).unwrap();
        assert_eq!(restored.labels, vec!["prod".to_string(), "eu".to_string()]);
    }

    #[test]
    fn empty_labels_are_omitted_when_writing() {
        let toml_text = toml::to_string_pretty(&profile_with_labels(Vec::new())).unwrap();
        assert!(
            !toml_text.contains("label"),
            "empty labels should be omitted, got: {toml_text}"
        );
    }

    /// The same load-then-save `cx profiles refresh` uses. A legacy file comes
    /// back with the same label values under the `labels` key.
    #[test]
    fn resave_preserves_legacy_label_values() {
        let loaded: Profile = toml::from_str("region = \"eu1\"\nlabel = \"prod\"\n").unwrap();
        assert_eq!(loaded.labels, vec!["prod".to_string()]);
        let written = toml::to_string_pretty(&loaded).unwrap();
        assert_no_legacy_label_key(&written);
        let again: Profile = toml::from_str(&written).unwrap();
        assert_eq!(again.labels, vec!["prod".to_string()]);
    }

    /// OAuth profile round-trips through TOML serialisation.
    #[test]
    fn oauth_profile_round_trips() {
        let profile = Profile {
            auth: AuthKind::OAuth,
            credential_storage: CredentialStorage::OsStore,
            api_key: None,
            region: Region::Eu2,
            labels: vec!["prod".to_string()],
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        let toml = toml::to_string_pretty(&profile).unwrap();
        let restored: Profile = toml::from_str(&toml).unwrap();
        assert_eq!(restored.auth, AuthKind::OAuth);
        assert_eq!(restored.credential_storage, CredentialStorage::OsStore);
        assert!(restored.api_key.is_none());
        assert_eq!(restored.labels, vec!["prod".to_string()]);
        // oauth_client_id / oauth_base_url are skip_serializing_if = None, so absent
        assert!(restored.oauth_client_id.is_none());
        assert!(restored.oauth_tokens.is_none());
    }

    /// OAuth profile with file-stored tokens round-trips through TOML.
    #[test]
    fn oauth_profile_file_storage_round_trips() {
        let profile = Profile {
            auth: AuthKind::OAuth,
            credential_storage: CredentialStorage::File,
            api_key: None,
            region: Region::Eu2,
            labels: vec!["prod".to_string()],
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: Some(StoredOAuthTokens {
                access_token: "access-abc".to_string(),
                refresh_token: Some("refresh-xyz".to_string()),
                id_token: None,
                expiry: Some(1_700_000_000),
            }),
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        let toml = toml::to_string_pretty(&profile).unwrap();
        let restored: Profile = toml::from_str(&toml).unwrap();
        assert_eq!(restored.credential_storage, CredentialStorage::File);
        let tokens = restored.oauth_tokens.expect("oauth_tokens persisted");
        assert_eq!(tokens.access_token, "access-abc");
        assert_eq!(tokens.refresh_token.as_deref(), Some("refresh-xyz"));
        assert!(tokens.id_token.is_none());
        assert_eq!(tokens.expiry, Some(1_700_000_000));
    }

    /// Custom OAuth profile (with explicit client ID) round-trips.
    #[test]
    fn custom_oauth_profile_preserves_client_id() {
        let profile = Profile {
            auth: AuthKind::OAuth,
            credential_storage: CredentialStorage::OsStore,
            api_key: None,
            region: Region::Custom("https://api.myenv.coralogix.com".to_string()),
            labels: Vec::new(),
            oauth_client_id: Some("abc-123".to_string()),
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        let toml = toml::to_string_pretty(&profile).unwrap();
        let restored: Profile = toml::from_str(&toml).unwrap();
        assert_eq!(restored.oauth_client_id.as_deref(), Some("abc-123"));
    }

    // ── resolve_all missing profile (no filesystem) ───────────────────────────

    #[tokio::test]
    async fn resolve_all_missing_profile_returns_error() {
        let result = resolve_all(
            &["cx_definitely_does_not_exist_xyz".to_string()],
            None,
            None,
        )
        .await;
        assert!(result.is_err());
    }

    // ── env-only mode (no filesystem) ────────────────────────────────────────

    #[tokio::test]
    async fn resolve_single_env_only_synthesises_when_profile_file_missing() {
        let cfg = resolve_single(
            "cx_envonly_missing_profile_xyz",
            Some("env-key"),
            Some("eu1"),
        )
        .await
        .unwrap();
        assert_eq!(cfg.profile_name, "cx_envonly_missing_profile_xyz");
        assert_eq!(cfg.api_key, "env-key");
        assert_eq!(cfg.endpoint, "https://api.eu1.coralogix.com");
    }

    #[tokio::test]
    async fn resolve_single_env_only_requires_api_key_override() {
        let result = resolve_single("cx_envonly_no_key_xyz", None, Some("eu1")).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn resolve_single_env_only_requires_region_override() {
        let result = resolve_single("cx_envonly_no_region_xyz", Some("env-key"), None).await;
        assert!(result.is_err());
    }

    // ── Empty profile name edge case ──────────────────────────────────────────

    #[test]
    fn save_profile_empty_name_creates_hidden_file() {
        let dir =
            std::env::temp_dir().join(format!("cx_test_empty_profile_name_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);

        // Point CX_HOME at our temp dir so save_profile writes there.
        // We can't easily redirect save_profile without CX_HOME, so test
        // the underlying list_profile_names_from behavior instead: an empty
        // stem is invisible to profile discovery.
        std::fs::create_dir_all(dir.join("profiles")).unwrap();
        std::fs::write(dir.join("profiles").join(".toml"), "region = \"eu1\"\n").unwrap();

        let names = list_profile_names_from(&dir.join("profiles")).unwrap();
        assert!(
            names.is_empty() || !names.contains(&String::new()),
            "empty-named profile should not appear in list, got: {names:?}"
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    // ── Integration tests (require ~/.cx access, run with --ignored) ──────────

    #[tokio::test]
    #[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
    async fn resolve_all_integration_multiple_profiles() {
        let names = ["cx_inttest_multi_a", "cx_inttest_multi_b"];
        for (i, name) in names.iter().enumerate() {
            let profile = Profile {
                auth: AuthKind::ApiKey,
                credential_storage: CredentialStorage::File,
                api_key: Some(format!("key-{i}")),
                region: Region::Eu1,
                labels: Vec::new(),
                oauth_client_id: None,
                oauth_base_url: None,
                oauth_tokens: None,
                default_output_format: None,
                default_tier: None,
                console_url: None,
                cached_console_url: None,
                cached_console_url_at: None,
                cached_team_id: None,
                cached_team_name: None,
            };
            save_profile(name, &profile).unwrap();
        }

        let configs = resolve_all(
            &names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
            None,
            None,
        )
        .await
        .unwrap();

        assert_eq!(configs.len(), 2);
        assert_eq!(configs[0].profile_name, "cx_inttest_multi_a");
        assert_eq!(configs[0].api_key, "key-0");
        assert_eq!(configs[1].profile_name, "cx_inttest_multi_b");
        assert_eq!(configs[1].api_key, "key-1");

        for name in &names {
            let _ = std::fs::remove_file(profile_file(name).unwrap());
        }
    }

    #[tokio::test]
    #[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
    async fn resolve_all_integration_empty_slice_falls_back_to_default() {
        let profile = Profile {
            auth: AuthKind::ApiKey,
            credential_storage: CredentialStorage::File,
            api_key: Some("default-key".to_string()),
            region: Region::Eu1,
            labels: Vec::new(),
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        save_profile("default", &profile).unwrap();

        let configs = resolve_all(&[], None, None).await.unwrap();
        assert_eq!(configs.len(), 1);
        assert_eq!(configs[0].profile_name, "default");
    }

    #[tokio::test]
    #[ignore = "requires write access to ~/.cx"]
    async fn resolve_prefers_cli_override_over_file() {
        let name = "cx_inttest_resolve_override";
        let profile = Profile {
            auth: AuthKind::ApiKey,
            credential_storage: CredentialStorage::File,
            api_key: Some("file-key".to_string()),
            region: Region::Eu1,
            labels: Vec::new(),
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        save_profile(name, &profile).unwrap();

        let config = resolve_single(name, Some("cli-key"), None).await.unwrap();
        assert_eq!(config.api_key, "cli-key");

        let _ = std::fs::remove_file(profile_file(name).unwrap());
    }

    #[tokio::test]
    #[ignore = "requires write access to ~/.cx"]
    async fn resolve_reads_from_file_storage() {
        let name = "cx_inttest_resolve_file";
        let profile = Profile {
            auth: AuthKind::ApiKey,
            credential_storage: CredentialStorage::File,
            api_key: Some("file-key".to_string()),
            region: Region::Eu1,
            labels: Vec::new(),
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        save_profile(name, &profile).unwrap();

        let config = resolve_single(name, None, None).await.unwrap();
        assert_eq!(config.api_key, "file-key");

        let _ = std::fs::remove_file(profile_file(name).unwrap());
    }

    #[tokio::test]
    #[ignore = "requires write access to ~/.cx"]
    async fn resolve_errors_when_no_key_anywhere() {
        let name = "cx_inttest_resolve_no_key";
        let profile = Profile {
            auth: AuthKind::ApiKey,
            credential_storage: CredentialStorage::File,
            api_key: None,
            region: Region::Eu1,
            labels: Vec::new(),
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: None,
            cached_console_url_at: None,
            cached_team_id: None,
            cached_team_name: None,
        };
        save_profile(name, &profile).unwrap();

        let result = resolve_single(name, None, None).await;
        assert!(result.is_err());

        let _ = std::fs::remove_file(profile_file(name).unwrap());
    }

    // ── Console URL cache ──────────────────────────────────────────────────────

    /// A profile that doesn't exist on disk (e.g. env-only mode) has no cache
    /// to read - this must be a silent `None`, not an error, so the caller
    /// falls back to a live `/identity/whoami` lookup. Read-only, so it needs
    /// no filesystem write access.
    #[test]
    fn load_cached_console_url_none_for_missing_profile() {
        assert_eq!(
            load_cached_console_url("cx_unittest_definitely_missing_profile_xyz"),
            None
        );
    }

    fn profile_with_cache(cached_at: Option<DateTime<Utc>>) -> Profile {
        Profile {
            auth: AuthKind::ApiKey,
            credential_storage: CredentialStorage::File,
            api_key: Some("k".to_string()),
            region: Region::Eu1,
            labels: Vec::new(),
            oauth_client_id: None,
            oauth_base_url: None,
            oauth_tokens: None,
            default_output_format: None,
            default_tier: None,
            console_url: None,
            cached_console_url: Some("https://cached.app.eu2.coralogix.com".to_string()),
            cached_console_url_at: cached_at,
            cached_team_id: None,
            cached_team_name: None,
        }
    }

    #[test]
    #[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
    fn cache_team_identity_round_trips() {
        let name = "cx_inttest_console_cache_roundtrip";
        // Seed a profile so cache_team_identity has a file to write into.
        save_profile(name, &profile_with_cache(None)).unwrap();

        cache_team_identity(
            name,
            &whoami(Some(12), "c4c", Some("https://fresh.app.eu2.coralogix.com")),
        );
        assert_eq!(
            load_cached_console_url(name),
            Some("https://fresh.app.eu2.coralogix.com".to_string())
        );

        let _ = std::fs::remove_file(profile_file(name).unwrap());
    }

    #[test]
    #[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
    fn load_cached_console_url_ignores_stale_entry() {
        let name = "cx_inttest_console_cache_stale";
        let stale = Utc::now() - Duration::days(CONSOLE_URL_CACHE_TTL_DAYS + 1);
        save_profile(name, &profile_with_cache(Some(stale))).unwrap();

        // Present on disk, but older than the TTL -> treated as absent.
        assert_eq!(load_cached_console_url(name), None);

        let _ = std::fs::remove_file(profile_file(name).unwrap());
    }

    #[test]
    #[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
    fn load_cached_console_url_returns_fresh_entry() {
        let name = "cx_inttest_console_cache_fresh";
        let fresh = Utc::now() - Duration::days(CONSOLE_URL_CACHE_TTL_DAYS - 1);
        save_profile(name, &profile_with_cache(Some(fresh))).unwrap();

        assert_eq!(
            load_cached_console_url(name),
            Some("https://cached.app.eu2.coralogix.com".to_string())
        );

        let _ = std::fs::remove_file(profile_file(name).unwrap());
    }

    fn whoami(id: Option<i64>, name: &str, url: Option<&str>) -> crate::identity::Whoami {
        crate::identity::Whoami {
            team_id: id,
            team_name: Some(name.to_string()),
            user_name: None,
            team_url: url.map(str::to_string),
        }
    }

    #[test]
    fn reauth_accepts_the_same_team_id() {
        let mut profile = profile_with_cache(None);
        profile.cached_team_id = Some(12);
        let signed_in = whoami(Some(12), "c4c", Some("https://other.example"));
        assert!(reauth_team_conflict("default", &profile, &signed_in).is_none());
    }

    #[test]
    fn reauth_rejects_a_different_team_id() {
        let mut profile = profile_with_cache(None);
        profile.cached_team_id = Some(12);
        let signed_in = whoami(Some(99), "other", Some("https://other.example"));
        let msg = reauth_team_conflict("default", &profile, &signed_in)
            .unwrap()
            .to_string();
        assert!(msg.contains("id 99"), "{msg}");
        assert!(msg.contains("team id 12"), "{msg}");
        assert!(
            msg.contains("Run `cx profiles refresh default` and select team id 12."),
            "{msg}"
        );
    }

    #[test]
    fn reauth_conflict_separates_explanation_retry_label_and_recovery() {
        let mut profile = profile_with_cache(None);
        profile.cached_team_id = Some(12);
        profile.cached_team_name = Some("c4c".to_string());
        let signed_in = whoami(Some(99), "other", Some("https://other.example"));
        let conflict = reauth_team_conflict("default", &profile, &signed_in).unwrap();
        assert!(
            conflict
                .explanation
                .contains("last used with team 'c4c' (id 12)"),
            "{}",
            conflict.explanation
        );
        assert!(
            !conflict.explanation.contains("Tokens were not saved"),
            "the explanation is printed before the retry prompt and must not \
             claim the flow already gave up: {}",
            conflict.explanation
        );
        assert_eq!(conflict.select, "team 'c4c' (id 12)");
        assert!(
            conflict.recovery.starts_with("Tokens were not saved."),
            "{}",
            conflict.recovery
        );
    }

    #[test]
    fn reauth_recovery_hint_uses_the_cached_team_name() {
        let mut profile = profile_with_cache(None);
        profile.cached_team_id = Some(12);
        profile.cached_team_name = Some("c4c".to_string());
        let signed_in = whoami(Some(99), "other", Some("https://other.example"));
        let msg = reauth_team_conflict("default", &profile, &signed_in)
            .unwrap()
            .to_string();
        assert!(
            msg.contains("Run `cx profiles refresh default` and select team 'c4c' (id 12)."),
            "{msg}"
        );
        assert!(msg.contains("last used with team 'c4c' (id 12)"), "{msg}");
    }

    #[test]
    fn remember_signed_in_team_refreshes_console_url_ttl_when_url_is_unchanged() {
        let stale = Utc::now() - Duration::days(CONSOLE_URL_CACHE_TTL_DAYS + 1);
        let mut profile = profile_with_cache(Some(stale));
        let signed_in = whoami(Some(1), "c4c", Some("https://cached.app.eu2.coralogix.com"));
        assert!(remember_signed_in_team(&mut profile, &signed_in));
        let refreshed_at = profile.cached_console_url_at.expect("ttl refreshed");
        assert!(refreshed_at > stale);
    }

    #[test]
    fn reauth_rejects_a_different_team_url_when_no_id_is_cached() {
        let profile = profile_with_cache(None);
        let signed_in = whoami(
            Some(2),
            "other",
            Some("https://other.app.eu2.coralogix.com"),
        );
        let msg = reauth_team_conflict("default", &profile, &signed_in)
            .unwrap()
            .to_string();
        assert!(msg.contains("other.app.eu2.coralogix.com"), "{msg}");
        assert!(msg.contains("cached.app.eu2.coralogix.com"), "{msg}");
    }

    #[test]
    fn reauth_allows_sign_in_when_no_team_was_recorded() {
        let mut profile = profile_with_cache(None);
        profile.cached_console_url = None;
        profile.cached_team_id = None;
        let signed_in = whoami(Some(2), "c4c", Some("https://c4c.app.eu2.coralogix.com"));
        assert!(reauth_team_conflict("default", &profile, &signed_in).is_none());
    }

    // ── IT-managed policy: migration and token storage ────────────────────────

    fn stored_tokens(access_token: &str) -> StoredOAuthTokens {
        StoredOAuthTokens {
            access_token: access_token.to_string(),
            refresh_token: Some("refresh".to_string()),
            id_token: None,
            expiry: Some(1_900_000_000),
        }
    }

    fn token_response(access_token: &str) -> oauth::TokenResponse {
        oauth::TokenResponse {
            access_token: access_token.to_string(),
            token_type: "Bearer".to_string(),
            expires_in: Some(3600),
            refresh_token: Some("refresh".to_string()),
            id_token: None,
            scope: None,
        }
    }

    #[test]
    fn migration_stores_the_api_key_before_saving_the_profile() {
        let events = std::cell::RefCell::new(Vec::new());
        let mut profile = profile_with_labels(Vec::new());
        profile.api_key = Some("key".to_string());

        let migrated = migrate_profile_with(
            "p",
            &mut profile,
            |name, profile| {
                events
                    .borrow_mut()
                    .push(format!("store {name} {:?}", profile.api_key));
                Ok(())
            },
            |name, profile| {
                events.borrow_mut().push(format!(
                    "save {name} {:?} {:?}",
                    profile.credential_storage, profile.api_key
                ));
                Ok(())
            },
        )
        .expect("migration succeeds");

        assert!(migrated);
        assert_eq!(
            events.into_inner(),
            ["store p Some(\"key\")", "save p OsStore None"]
        );
    }

    #[test]
    fn migration_hands_oauth_tokens_to_the_store_unchanged() {
        let mut profile = profile_with_labels(Vec::new());
        profile.auth = AuthKind::OAuth;
        profile.oauth_tokens = Some(stored_tokens("access"));
        let mut stored = None;
        let mut saved = None;

        migrate_profile_with(
            "p",
            &mut profile,
            |_, profile| {
                stored = profile.oauth_tokens.clone();
                Ok(())
            },
            |_, profile| {
                saved = Some(profile.clone());
                Ok(())
            },
        )
        .expect("migration succeeds");

        assert_eq!(stored, Some(stored_tokens("access")));
        let saved = saved.expect("profile saved");
        assert_eq!(saved.credential_storage, CredentialStorage::OsStore);
        assert_eq!(saved.oauth_tokens, None);
    }

    #[test]
    fn failed_migration_leaves_the_profile_file_alone() {
        let mut profile = profile_with_labels(Vec::new());
        profile.api_key = Some("key".to_string());
        let mut saved = false;

        let err = migrate_profile_with(
            "p",
            &mut profile,
            |_, _| Err(anyhow::anyhow!("keychain locked")),
            |_, _| {
                saved = true;
                Ok(())
            },
        )
        .expect_err("store failure is reported");

        assert!(format!("{err:#}").contains("keychain locked"), "{err:#}");
        assert!(!saved);
        assert_eq!(profile.credential_storage, CredentialStorage::File);
        assert_eq!(profile.api_key.as_deref(), Some("key"));
    }

    #[test]
    fn migration_skips_profiles_already_in_the_os_store() {
        let mut profile = profile_with_labels(Vec::new());
        profile.credential_storage = CredentialStorage::OsStore;

        let migrated = migrate_profile_with(
            "p",
            &mut profile,
            |_, _| panic!("nothing to store"),
            |_, _| panic!("nothing to save"),
        )
        .expect("nothing to migrate");
        assert!(!migrated);
    }

    #[test]
    fn migration_drops_stray_plaintext_from_os_store_profiles() {
        let mut profile = profile_with_labels(Vec::new());
        profile.credential_storage = CredentialStorage::OsStore;
        profile.api_key = Some("stale".to_string());
        let mut saved_without_key = false;

        let migrated = migrate_profile_with(
            "p",
            &mut profile,
            |_, _| panic!("the OS store already holds this profile's secret"),
            |_, profile| {
                saved_without_key = profile.api_key.is_none();
                Ok(())
            },
        )
        .expect("plaintext dropped");
        assert!(migrated);
        assert!(saved_without_key);
    }

    #[test]
    fn managed_sign_in_moves_a_file_profile_to_the_os_store() {
        let mut profile = profile_with_labels(Vec::new());
        profile.auth = AuthKind::OAuth;
        profile.oauth_tokens = Some(stored_tokens("old"));

        let access_token =
            keep_signed_in_tokens_with("p", &mut profile, &token_response("new"), true, |_, _| {
                Ok(())
            })
            .expect("stored in the OS store");

        assert_eq!(access_token, "new");
        assert_eq!(profile.credential_storage, CredentialStorage::OsStore);
        assert_eq!(profile.oauth_tokens, None);
    }

    #[test]
    fn managed_sign_in_fails_instead_of_falling_back_to_file() {
        let mut profile = profile_with_labels(Vec::new());
        profile.auth = AuthKind::OAuth;

        let err = keep_signed_in_tokens_with(
            "cx_test_managed_sign_in",
            &mut profile,
            &token_response("new"),
            true,
            |_, _| Err(anyhow::anyhow!("keychain locked")),
        )
        .expect_err("policy forbids the file fallback");

        assert!(err.to_string().contains("keychain locked"), "{err}");
        assert_eq!(profile.oauth_tokens, None);
    }

    #[test]
    fn unmanaged_sign_in_falls_back_to_file_when_the_os_store_fails() {
        let mut profile = profile_with_labels(Vec::new());
        profile.auth = AuthKind::OAuth;
        profile.credential_storage = CredentialStorage::OsStore;

        keep_signed_in_tokens_with(
            "cx_test_unmanaged_sign_in",
            &mut profile,
            &token_response("new"),
            false,
            |_, _| Err(anyhow::anyhow!("keychain locked")),
        )
        .expect("falls back to file");

        assert_eq!(profile.credential_storage, CredentialStorage::File);
        assert_eq!(
            profile.oauth_tokens.map(|tokens| tokens.access_token),
            Some("new".to_string())
        );
    }

    #[test]
    fn managed_refresh_fails_instead_of_writing_tokens_to_file() {
        let mut profile = profile_with_labels(Vec::new());
        profile.credential_storage = CredentialStorage::OsStore;

        let err = keep_refreshed_tokens(
            &mut profile,
            stored_tokens("new"),
            Some("keychain locked"),
            true,
        )
        .expect_err("policy forbids the file fallback");

        assert!(err.to_string().contains("keychain locked"), "{err}");
        assert_eq!(profile.credential_storage, CredentialStorage::OsStore);
        assert_eq!(profile.oauth_tokens, None);
    }

    #[test]
    fn unmanaged_refresh_falls_back_to_file_when_the_os_store_fails() {
        let mut profile = profile_with_labels(Vec::new());
        profile.credential_storage = CredentialStorage::OsStore;

        keep_refreshed_tokens(
            &mut profile,
            stored_tokens("new"),
            Some("keychain locked"),
            false,
        )
        .expect("falls back to file");

        assert_eq!(profile.credential_storage, CredentialStorage::File);
        assert_eq!(profile.oauth_tokens, Some(stored_tokens("new")));
    }

    #[test]
    fn file_profile_refresh_keeps_tokens_on_the_profile() {
        let mut profile = profile_with_labels(Vec::new());

        keep_refreshed_tokens(&mut profile, stored_tokens("new"), None, false)
            .expect("file profile refresh");

        assert_eq!(profile.credential_storage, CredentialStorage::File);
        assert_eq!(profile.oauth_tokens, Some(stored_tokens("new")));
    }

    #[test]
    fn unmanaged_profile_migration_does_not_list_profiles() {
        let result = migrate_managed_profiles_with(
            false,
            || Err(anyhow::anyhow!("profile listing must not run")),
            |_| Ok(()),
        );

        assert!(result.is_ok());
    }

    #[test]
    fn managed_profile_migration_warns_and_continues_after_a_failed_profile() {
        let migrated = std::cell::RefCell::new(Vec::new());
        migrate_managed_profiles_with(
            true,
            || Ok(vec!["broken".into(), "working".into()]),
            |name| {
                migrated.borrow_mut().push(name.to_owned());
                if name == "broken" {
                    anyhow::bail!("invalid profile")
                }
                Ok(())
            },
        )
        .expect("one broken profile must not stop migration");

        assert_eq!(*migrated.borrow(), vec!["broken", "working"]);
    }
}