coralogix-cli 0.1.29

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
use std::io::IsTerminal;
use std::path::PathBuf;

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

use anyhow::{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/`.
    #[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,

    /// 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
}

fn default_temp_dir() -> String {
    "/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,
            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>,
}

/// A named profile storing credentials and endpoint info.
///
/// `credential_storage` selects where secrets live for both auth modes:
///   - `"file"` (default): API keys / OAuth tokens are written inline in the
///     TOML, which is created with `0600` permissions.
///   - `"os_store"`: 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, Deserialize)]
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,
    /// Optional free-form label (e.g. "prod", "staging")
    pub label: Option<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>,
}

/// 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}'"))
}

/// 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.
fn keep_signed_in_tokens(
    profile_name: &str,
    profile: &mut Profile,
    tokens: &oauth::TokenResponse,
) -> Result<String> {
    if profile.credential_storage == CredentialStorage::OsStore {
        match oauth::store_tokens_keyring(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);
                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 label stay as they
/// are; only the tokens (and the cached team) change.
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)?;
    // `--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.
                profile.oauth_tokens = Some(new_tokens);
                if os_store_fallback_reason.is_some() {
                    profile.credential_storage = CredentialStorage::File;
                }
            }
            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(),
    })
}

/// 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.oauth_client_id.is_none());
        assert!(p.oauth_base_url.is_none());
    }

    /// 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,
            label: Some("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());
        // 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,
            label: Some("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()),
            label: None,
            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,
                label: None,
                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,
            label: None,
            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,
            label: None,
            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,
            label: None,
            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,
            label: None,
            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,
            label: None,
            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());
    }
}