cc-switch-tui 0.2.2

All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode, OpenClaw & Hermes
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
// unused imports removed
use std::path::PathBuf;

use crate::config::{
    atomic_write, delete_file, home_dir, sanitize_provider_name, write_json_file, write_text_file,
};
use crate::error::AppError;
use serde_json::json;
use serde_json::Value;
use std::fs;
use std::path::Path;
use toml_edit::DocumentMut;

pub const CC_SWITCH_CODEX_MODEL_PROVIDER_ID: &str = "ccswitch";
pub const CODEX_STRUCTURED_CONFIG_KEY: &str = "codex";
pub const CODEX_LEGACY_CONFIG_KEY: &str = "config";

/// Reserved built-in provider IDs from OpenAI Codex's config/model-provider
/// catalog. Keep in sync with Codex `RESERVED_MODEL_PROVIDER_IDS` and legacy
/// removed provider aliases.
const CODEX_RESERVED_MODEL_PROVIDER_IDS: &[&str] = &[
    "amazon-bedrock",
    "openai",
    "ollama",
    "lmstudio",
    "oss",
    "ollama-chat",
];

/// 获取 Codex 配置目录路径
///
/// Priority: `CODEX_HOME` env var > cc-switch settings override > `$HOME/.codex`
pub fn get_codex_config_dir() -> PathBuf {
    if let Some(dir) = std::env::var_os("CODEX_HOME") {
        let dir = PathBuf::from(dir);
        if !dir.as_os_str().is_empty() && !dir.to_string_lossy().trim().is_empty() {
            return expand_codex_config_dir(dir);
        }
    }

    if let Some(custom) = crate::settings::get_codex_override_dir() {
        return custom;
    }

    home_dir().expect("无法获取用户主目录").join(".codex")
}

fn expand_codex_config_dir(path: PathBuf) -> PathBuf {
    let lossy = path.to_string_lossy();
    if lossy == "~" {
        return home_dir().unwrap_or(path);
    }

    if let Some(rest) = lossy
        .strip_prefix("~/")
        .or_else(|| lossy.strip_prefix("~\\"))
    {
        if let Some(home) = home_dir() {
            return home.join(rest);
        }
    }

    path
}

/// 获取 Codex auth.json 路径
pub fn get_codex_auth_path() -> PathBuf {
    get_codex_config_dir().join("auth.json")
}

/// 获取 Codex config.toml 路径
pub fn get_codex_config_path() -> PathBuf {
    get_codex_config_dir().join("config.toml")
}

/// 获取 Codex 供应商配置文件路径
pub fn get_codex_provider_paths(
    provider_id: &str,
    provider_name: Option<&str>,
) -> (PathBuf, PathBuf) {
    let base_name = provider_name
        .map(sanitize_provider_name)
        .unwrap_or_else(|| sanitize_provider_name(provider_id));

    let auth_path = get_codex_config_dir().join(format!("auth-{base_name}.json"));
    let config_path = get_codex_config_dir().join(format!("config-{base_name}.toml"));

    (auth_path, config_path)
}

/// 删除 Codex 供应商配置文件
pub fn delete_codex_provider_config(
    provider_id: &str,
    provider_name: &str,
) -> Result<(), AppError> {
    let (auth_path, config_path) = get_codex_provider_paths(provider_id, Some(provider_name));

    delete_file(&auth_path).ok();
    delete_file(&config_path).ok();

    Ok(())
}

/// 原子写 Codex 的 `auth.json` 与 `config.toml`,在第二步失败时回滚第一步
pub fn write_codex_live_atomic(
    auth: &Value,
    config_text_opt: Option<&str>,
) -> Result<(), AppError> {
    write_codex_live_atomic_optional_auth(Some(auth), config_text_opt)
}

pub fn write_codex_live_atomic_optional_auth(
    auth: Option<&Value>,
    config_text_opt: Option<&str>,
) -> Result<(), AppError> {
    let auth_path = get_codex_auth_path();
    let config_path = get_codex_config_path();

    if let Some(parent) = auth_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;
    }

    // 读取旧内容用于回滚
    let old_auth = if auth_path.exists() {
        Some(fs::read(&auth_path).map_err(|e| AppError::io(&auth_path, e))?)
    } else {
        None
    };
    let _old_config = if config_path.exists() {
        Some(fs::read(&config_path).map_err(|e| AppError::io(&config_path, e))?)
    } else {
        None
    };

    // 准备写入内容
    let cfg_text = match config_text_opt {
        Some(s) => s.to_string(),
        None => String::new(),
    };
    if !cfg_text.trim().is_empty() {
        toml::from_str::<toml::Table>(&cfg_text).map_err(|e| AppError::toml(&config_path, e))?;
    }

    // 第一步:写 auth.json
    if let Some(auth) = auth {
        write_json_file(&auth_path, auth)?;
    } else {
        delete_file(&auth_path)?;
    }

    // 第二步:写 config.toml(失败则回滚 auth.json)
    if let Err(e) = write_text_file(&config_path, &cfg_text) {
        // 回滚 auth.json
        if let Some(bytes) = old_auth {
            let _ = atomic_write(&auth_path, &bytes);
        } else {
            let _ = delete_file(&auth_path);
        }
        return Err(e);
    }

    Ok(())
}

/// 读取 `~/.codex/config.toml`,若不存在返回空字符串
pub fn read_codex_config_text() -> Result<String, AppError> {
    let path = get_codex_config_path();
    if path.exists() {
        std::fs::read_to_string(&path).map_err(|e| AppError::io(&path, e))
    } else {
        Ok(String::new())
    }
}

/// 对非空的 TOML 文本进行语法校验
pub fn validate_config_toml(text: &str) -> Result<(), AppError> {
    if text.trim().is_empty() {
        return Ok(());
    }
    toml::from_str::<toml::Table>(text)
        .map(|_| ())
        .map_err(|e| AppError::toml(Path::new("config.toml"), e))
}

fn toml_value_to_json(value: toml::Value) -> Value {
    match value {
        toml::Value::String(value) => Value::String(value),
        toml::Value::Integer(value) => json!(value),
        toml::Value::Float(value) => json!(value),
        toml::Value::Boolean(value) => Value::Bool(value),
        toml::Value::Datetime(value) => Value::String(value.to_string()),
        toml::Value::Array(values) => {
            Value::Array(values.into_iter().map(toml_value_to_json).collect())
        }
        toml::Value::Table(table) => {
            let mut obj = serde_json::Map::new();
            for (key, value) in table {
                obj.insert(key, toml_value_to_json(value));
            }
            Value::Object(obj)
        }
    }
}

fn json_value_to_toml(value: &Value, path: &str) -> Result<toml::Value, AppError> {
    match value {
        Value::Null => Err(AppError::Config(format!(
            "Codex structured config contains null at `{path}`; TOML has no null value"
        ))),
        Value::Bool(value) => Ok(toml::Value::Boolean(*value)),
        Value::Number(value) => {
            if let Some(value) = value.as_i64() {
                Ok(toml::Value::Integer(value))
            } else if let Some(value) = value.as_u64() {
                let value = i64::try_from(value).map_err(|_| {
                    AppError::Config(format!(
                        "Codex structured config integer at `{path}` is too large for TOML"
                    ))
                })?;
                Ok(toml::Value::Integer(value))
            } else if let Some(value) = value.as_f64() {
                Ok(toml::Value::Float(value))
            } else {
                Err(AppError::Config(format!(
                    "Codex structured config number at `{path}` is not representable as TOML"
                )))
            }
        }
        Value::String(value) => Ok(toml::Value::String(value.clone())),
        Value::Array(values) => {
            let mut out = Vec::with_capacity(values.len());
            for (index, value) in values.iter().enumerate() {
                out.push(json_value_to_toml(value, &format!("{path}[{index}]"))?);
            }
            Ok(toml::Value::Array(out))
        }
        Value::Object(values) => {
            let mut out = toml::map::Map::new();
            for (key, value) in values {
                let child_path = if path.is_empty() {
                    key.to_string()
                } else {
                    format!("{path}.{key}")
                };
                out.insert(key.clone(), json_value_to_toml(value, &child_path)?);
            }
            Ok(toml::Value::Table(out))
        }
    }
}

pub fn codex_structured_config_from_toml(config_toml: &str) -> Result<Value, AppError> {
    let trimmed = config_toml.trim();
    if trimmed.is_empty() {
        return Ok(Value::Object(serde_json::Map::new()));
    }

    trimmed
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Config(format!("TOML parse error: {e}")))?;
    let value = toml::from_str::<toml::Value>(trimmed)
        .map_err(|e| AppError::toml(Path::new("config.toml"), e))?;
    match toml_value_to_json(value) {
        Value::Object(obj) => Ok(Value::Object(obj)),
        _ => Err(AppError::Config(
            "Codex config.toml root must be a TOML table".to_string(),
        )),
    }
}

pub fn codex_structured_config_to_toml(config: &Value) -> Result<String, AppError> {
    match config {
        Value::Null => Ok(String::new()),
        Value::Object(_) => {
            let value = json_value_to_toml(config, CODEX_STRUCTURED_CONFIG_KEY)?;
            toml::to_string(&value)
                .map_err(|source| {
                    AppError::Config(format!(
                        "Codex structured config TOML serialize error: {source}"
                    ))
                })
                .map(|text| text.trim().to_string())
        }
        _ => Err(AppError::Config(
            "Codex structured config must be a JSON object".to_string(),
        )),
    }
}

pub fn codex_config_text_from_settings(settings: &Value) -> Result<String, AppError> {
    let settings = settings
        .as_object()
        .ok_or_else(|| AppError::Config("Codex 配置必须是 JSON 对象".into()))?;

    if let Some(config) = settings.get(CODEX_STRUCTURED_CONFIG_KEY) {
        return codex_structured_config_to_toml(config);
    }

    match settings.get(CODEX_LEGACY_CONFIG_KEY) {
        Some(Value::String(text)) => Ok(text.clone()),
        Some(Value::Null) | None => Ok(String::new()),
        Some(_) => Err(AppError::Config(
            "Codex config 字段必须是字符串,codex 字段必须是对象".to_string(),
        )),
    }
}

pub fn codex_settings_snapshot_from_toml(
    auth: Option<Value>,
    config_toml: &str,
) -> Result<Value, AppError> {
    let mut settings = serde_json::Map::new();
    if let Some(auth) = auth {
        settings.insert("auth".to_string(), auth);
    }
    settings.insert(
        CODEX_STRUCTURED_CONFIG_KEY.to_string(),
        codex_structured_config_from_toml(config_toml)?,
    );
    Ok(Value::Object(settings))
}

pub fn set_codex_config_text_in_settings(
    settings: &mut Value,
    config_toml: &str,
    prefer_structured: bool,
) -> Result<(), AppError> {
    let settings = settings
        .as_object_mut()
        .ok_or_else(|| AppError::Config("Codex 配置必须是 JSON 对象".into()))?;

    if prefer_structured {
        settings.remove(CODEX_LEGACY_CONFIG_KEY);
        settings.insert(
            CODEX_STRUCTURED_CONFIG_KEY.to_string(),
            codex_structured_config_from_toml(config_toml)?,
        );
    } else {
        settings.insert(
            CODEX_LEGACY_CONFIG_KEY.to_string(),
            Value::String(config_toml.to_string()),
        );
    }

    Ok(())
}

pub fn normalize_codex_settings_config_for_storage(settings: &mut Value) -> Result<(), AppError> {
    let config_toml = isolate_selected_codex_provider(&codex_config_text_from_settings(settings)?)?;
    if !config_toml.trim().is_empty()
        && !config_toml.lines().any(|line| {
            let line = line.trim();
            !line.is_empty()
                && !line.starts_with('#')
                && (line.contains('=') || line.starts_with('['))
        })
    {
        return Err(AppError::Config(
            "Codex config.toml does not contain TOML assignments or tables".to_string(),
        ));
    }
    let settings = settings
        .as_object_mut()
        .ok_or_else(|| AppError::Config("Codex 配置必须是 JSON 对象".into()))?;
    settings.remove(CODEX_LEGACY_CONFIG_KEY);
    settings.insert(
        CODEX_STRUCTURED_CONFIG_KEY.to_string(),
        codex_structured_config_from_toml(&config_toml)?,
    );
    Ok(())
}

/// Remove provider-specific Codex TOML keys and keep only shared/global settings.
///
/// This matches upstream "OpenAI Official" snapshot semantics where the official
/// provider does not persist a provider-local `base_url` / `model_provider`
/// section, but may still carry root-level shared settings.
pub fn strip_codex_provider_config_text(config_toml: &str) -> Result<String, AppError> {
    let config_toml = config_toml.trim();
    if config_toml.is_empty() {
        return Ok(String::new());
    }

    let mut doc = config_toml
        .parse::<toml_edit::DocumentMut>()
        .map_err(|e| AppError::Config(format!("TOML parse error: {e}")))?;
    let root = doc.as_table_mut();
    root.remove("model");
    root.remove("model_provider");
    root.remove("base_url");
    root.remove("model_providers");

    let mut cleaned = String::new();
    let mut blank_run = 0usize;
    for line in doc.to_string().lines() {
        if line.trim().is_empty() {
            blank_run += 1;
            if blank_run <= 1 {
                cleaned.push('\n');
            }
            continue;
        }
        blank_run = 0;
        cleaned.push_str(line);
        cleaned.push('\n');
    }

    Ok(cleaned.trim().to_string())
}

pub fn isolate_selected_codex_provider(config_text: &str) -> Result<String, AppError> {
    let config_text = config_text.trim();
    if config_text.is_empty() {
        return Ok(String::new());
    }

    let mut doc = config_text
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Config(format!("TOML parse error: {e}")))?;
    let selected = active_codex_model_provider_id(&doc);

    let Some(selected) = selected else {
        doc.as_table_mut().remove("model_providers");
        return Ok(doc.to_string());
    };
    let Some(providers) = doc
        .get_mut("model_providers")
        .and_then(|item| item.as_table_like_mut())
    else {
        return Ok(doc.to_string());
    };
    if providers.get(&selected).is_none() {
        if !is_custom_codex_model_provider_id(&selected) {
            doc.as_table_mut().remove("model_providers");
            return Ok(doc.to_string());
        }
        return Err(AppError::Config(format!(
            "Codex model_provider `{selected}` is missing from model_providers"
        )));
    }

    let stale_keys = providers
        .iter()
        .map(|(key, _)| key.to_string())
        .filter(|key| key != &selected)
        .collect::<Vec<_>>();
    for key in stale_keys {
        providers.remove(&key);
    }

    Ok(doc.to_string())
}

/// 读取并校验 `~/.codex/config.toml`,返回文本(可能为空)
pub fn read_and_validate_codex_config_text() -> Result<String, AppError> {
    let s = read_codex_config_text()?;
    validate_config_toml(&s)?;
    Ok(s)
}

fn active_codex_model_provider_id(doc: &DocumentMut) -> Option<String> {
    doc.get("model_provider")
        .and_then(|item| item.as_str())
        .map(str::trim)
        .filter(|id| !id.is_empty())
        .map(str::to_string)
}

fn is_custom_codex_model_provider_id(id: &str) -> bool {
    let id = id.trim();
    !id.is_empty()
        && !CODEX_RESERVED_MODEL_PROVIDER_IDS
            .iter()
            .any(|reserved| reserved.eq_ignore_ascii_case(id))
}

fn stable_codex_model_provider_id_from_config(config_text: &str) -> Option<String> {
    let doc = config_text.parse::<DocumentMut>().ok()?;
    let provider_id = active_codex_model_provider_id(&doc)?;

    if is_custom_codex_model_provider_id(&provider_id) {
        Some(provider_id)
    } else {
        None
    }
}

fn codex_model_provider_id_with_table_from_config(
    config_text: &str,
) -> Result<Option<String>, AppError> {
    if config_text.trim().is_empty() {
        return Ok(None);
    }

    let doc = config_text
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
    let Some(provider_id) = active_codex_model_provider_id(&doc) else {
        return Ok(None);
    };

    let has_provider_table = doc
        .get("model_providers")
        .and_then(|item| item.as_table())
        .and_then(|table| table.get(provider_id.as_str()))
        .is_some();

    Ok(has_provider_table.then_some(provider_id))
}

fn primary_codex_model_provider_id_with_table(doc: &DocumentMut) -> Option<String> {
    if let Some(provider_id) = active_codex_model_provider_id(doc) {
        let has_provider_table = doc
            .get("model_providers")
            .and_then(|item| item.as_table_like())
            .and_then(|table| table.get(provider_id.as_str()))
            .is_some();
        if has_provider_table {
            return Some(provider_id);
        }
    }

    let providers = doc
        .get("model_providers")
        .and_then(|item| item.as_table_like())?;
    let mut keys = providers.iter().map(|(key, _)| key.to_string());
    let first = keys.next()?;
    keys.next().is_none().then_some(first)
}

fn normalize_codex_live_config_model_provider_with_anchors<'a>(
    config_text: &str,
    anchor_config_texts: impl IntoIterator<Item = &'a str>,
) -> Result<String, AppError> {
    if config_text.trim().is_empty() {
        return Ok(config_text.to_string());
    }

    let mut doc = config_text
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;

    let Some(source_provider_id) = active_codex_model_provider_id(&doc) else {
        return Ok(config_text.to_string());
    };

    let has_source_provider_table = doc
        .get("model_providers")
        .and_then(|item| item.as_table())
        .and_then(|table| table.get(source_provider_id.as_str()))
        .is_some();
    if !has_source_provider_table {
        return Ok(config_text.to_string());
    }

    let stable_provider_id = anchor_config_texts
        .into_iter()
        .find_map(stable_codex_model_provider_id_from_config)
        .or_else(|| {
            is_custom_codex_model_provider_id(&source_provider_id)
                .then(|| source_provider_id.clone())
        })
        .unwrap_or_else(|| CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string());

    if stable_provider_id == source_provider_id {
        return Ok(config_text.to_string());
    }

    if let Some(model_providers) = doc
        .get_mut("model_providers")
        .and_then(|item| item.as_table_mut())
    {
        let Some(provider_table) = model_providers.remove(source_provider_id.as_str()) else {
            return Ok(config_text.to_string());
        };
        model_providers[stable_provider_id.as_str()] = provider_table;
    }

    rewrite_codex_profile_model_provider_refs(&mut doc, &source_provider_id, &stable_provider_id);
    doc["model_provider"] = toml_edit::value(stable_provider_id.as_str());

    Ok(doc.to_string())
}

fn rewrite_codex_profile_model_provider_refs(
    doc: &mut DocumentMut,
    source_provider_id: &str,
    stable_provider_id: &str,
) {
    let Some(profiles) = doc
        .get_mut("profiles")
        .and_then(|item| item.as_table_like_mut())
    else {
        return;
    };

    let profile_keys: Vec<String> = profiles.iter().map(|(key, _)| key.to_string()).collect();
    for profile_key in profile_keys {
        let Some(profile_table) = profiles
            .get_mut(&profile_key)
            .and_then(|item| item.as_table_like_mut())
        else {
            continue;
        };

        let references_source = profile_table
            .get("model_provider")
            .and_then(|item| item.as_str())
            == Some(source_provider_id);
        if references_source {
            profile_table.insert("model_provider", toml_edit::value(stable_provider_id));
        }
    }
}

/// Rewrite a Codex snapshot to reuse an existing live custom `model_provider`.
///
/// This is intentionally **not** used for normal provider switches: the live
/// `config.toml` should show the selected provider id. It remains useful for
/// proxy takeover backup/restore flows that explicitly want a history-stable
/// Codex `model_provider` alias.
pub fn normalize_codex_settings_config_model_provider(
    settings: &mut Value,
    anchor_config_text: Option<&str>,
) -> Result<(), AppError> {
    let prefer_structured = settings.get(CODEX_STRUCTURED_CONFIG_KEY).is_some()
        && settings.get(CODEX_LEGACY_CONFIG_KEY).is_none();
    let config_text = codex_config_text_from_settings(settings)?;
    if config_text.trim().is_empty() {
        return Ok(());
    }

    let current_config_text = read_codex_config_text().ok();
    let anchors = anchor_config_text
        .into_iter()
        .chain(current_config_text.as_deref());
    let normalized =
        normalize_codex_live_config_model_provider_with_anchors(&config_text, anchors)?;

    set_codex_config_text_in_settings(settings, &normalized, prefer_structured)?;
    Ok(())
}

fn restore_codex_backfill_model_provider_id(
    config_text: &str,
    template_config_text: &str,
) -> Result<String, AppError> {
    let Some(template_provider_id) =
        codex_model_provider_id_with_table_from_config(template_config_text)?
    else {
        return Ok(config_text.to_string());
    };

    if config_text.trim().is_empty() {
        return Ok(config_text.to_string());
    }

    let mut doc = config_text
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
    let Some(live_provider_id) = active_codex_model_provider_id(&doc) else {
        return Ok(config_text.to_string());
    };

    if live_provider_id == template_provider_id {
        return Ok(config_text.to_string());
    }

    if let Some(model_providers) = doc
        .get_mut("model_providers")
        .and_then(|item| item.as_table_mut())
    {
        let Some(provider_table) = model_providers.remove(live_provider_id.as_str()) else {
            return Ok(config_text.to_string());
        };
        model_providers[template_provider_id.as_str()] = provider_table;
    } else {
        return Ok(config_text.to_string());
    }

    rewrite_codex_profile_model_provider_refs(&mut doc, &live_provider_id, &template_provider_id);
    doc["model_provider"] = toml_edit::value(template_provider_id.as_str());

    Ok(doc.to_string())
}

/// Convert a Codex live config that was normalized for history stability back
/// to the provider-specific id used by the stored provider template.
pub fn restore_codex_settings_config_model_provider_for_backfill(
    settings: &mut Value,
    template_settings: &Value,
) -> Result<(), AppError> {
    let prefer_structured = settings.get(CODEX_STRUCTURED_CONFIG_KEY).is_some()
        && settings.get(CODEX_LEGACY_CONFIG_KEY).is_none();
    let config_text = codex_config_text_from_settings(settings)?;
    let template_config_text = codex_config_text_from_settings(template_settings)?;
    if template_config_text.trim().is_empty() {
        return Ok(());
    }

    let restored = restore_codex_backfill_model_provider_id(&config_text, &template_config_text)?;
    set_codex_config_text_in_settings(settings, &restored, prefer_structured)?;

    Ok(())
}

/// Merge a stored provider snapshot into the current live config.
///
/// Strategy: edit the **live** document in place, overlaying only the entries the
/// snapshot explicitly provides. Everything else stays untouched — in particular
/// every comment the user has placed in `~/.codex/config.toml` survives a
/// provider switch, including:
///
/// - whole commented-out subtables (e.g. `# [mcp_servers.x] / # command = ...`,
///   typically used to temporarily disable an MCP server),
/// - commented-out root-level keys (e.g. `# disable_response_storage = true`),
/// - free-floating header notes attached to a key (toml_edit treats these as
///   the next key's prefix decor; overwriting that key in place preserves the
///   decor because the key already existed in live),
/// - trailing notes at end of file (document-level trailing decor).
///
/// Rules:
///
/// - `[mcp_servers]` is **never** overwritten from the snapshot. The user's live
///   `[mcp_servers]` content (active subtables, commented-out subtables, and any
///   loose comments around them) is preserved verbatim.
/// - Codex runtime trust keys (`projects`, `trusted_workspaces`) are also never
///   overwritten from the snapshot. Trust decisions are tied to local
///   workspaces, not to the selected model provider.
/// - The narrow set in [`PROVIDER_SCOPED_KEYS`] is treated as **provider-scoped**:
///   the snapshot is authoritative, live entries the snapshot doesn't cover are
///   removed (so e.g. `[model_providers.OLD]` doesn't leak into the new one).
/// - Every other root-level entry is treated as **user-owned**:
///     - `preserve_user_preferences = true` (provider switch with applyCommonConfig
///       honored): live wins when present; falls back to snapshot otherwise so an
///       initial write still seeds keys from the snapshot (which is what carries
///       merged common-snippet defaults).
///     - `preserve_user_preferences = false` (common-snippet apply/clear, or
///       provider with `applyCommonConfig=false`): snapshot drives. Live keys
///       absent from the snapshot are removed so old snippet residue doesn't
///       bleed through.
///
/// Defaulting *all* non-blacklisted root keys to user-owned is intentional: it
/// keeps the helper forward-compatible. When Codex adds a new root-level
/// preference (e.g. `sandbox_mode`, `verbose_logging`, …), users' live values
/// survive switches without anyone having to update this list. Only the small
/// set of keys that must hard-sync between providers needs to be maintained.
///
/// Currently provider-scoped:
/// - `model_provider` — pointer to the active `[model_providers.X]` entry.
/// - `model` — currently-selected model name, conventionally per-provider.
/// - `profile` — selected profile name, paired with `[profiles]`.
/// - `model_providers` — provider definitions; replaced wholesale per snapshot.
/// - `profiles` — may point at provider-specific `model_provider` keys.
pub fn merge_provider_into_codex_live_config(
    live_text: &str,
    provider_snapshot: &str,
    preserve_user_preferences: bool,
) -> Result<String, AppError> {
    const LIVE_RUNTIME_KEYS: &[&str] = &["mcp_servers", "projects", "trusted_workspaces"];
    /// Root-level keys whose value must strictly follow the active provider's
    /// snapshot. Anything not listed here is treated as user-owned and follows
    /// the `preserve_user_preferences` rules above, so adding a new preference
    /// key in Codex does NOT require code changes here.
    const PROVIDER_SCOPED_KEYS: &[&str] = &[
        "model_provider",
        "model",
        "profile",
        "model_providers",
        "profiles",
    ];

    let mut live = if live_text.trim().is_empty() {
        toml_edit::DocumentMut::new()
    } else {
        live_text
            .parse::<toml_edit::DocumentMut>()
            .map_err(|e| AppError::Message(format!("Invalid Codex live config.toml: {e}")))?
    };

    let snap = if provider_snapshot.trim().is_empty() {
        toml_edit::DocumentMut::new()
    } else {
        provider_snapshot
            .parse::<toml_edit::DocumentMut>()
            .map_err(|e| AppError::Message(format!("Invalid Codex provider snapshot: {e}")))?
    };

    // Step 1: figure out which live entries to drop.
    //
    // - Live runtime keys are never touched.
    // - Provider-scoped keys are dropped when the snapshot does not provide
    //   them, so the previous provider's [model_providers.OLD] doesn't leak.
    // - User-owned keys (everything else) are dropped only when
    //   `preserve_user_preferences = false` AND the snapshot does not provide
    //   them, so common-snippet residue gets cleared but ordinary user
    //   preferences are kept on a normal switch.
    let live_keys: Vec<String> = live.as_table().iter().map(|(k, _)| k.to_string()).collect();
    for key in live_keys {
        if LIVE_RUNTIME_KEYS.contains(&key.as_str()) {
            continue;
        }
        if snap.get(&key).is_some() {
            continue;
        }
        let is_provider_scoped = PROVIDER_SCOPED_KEYS.contains(&key.as_str());
        if is_provider_scoped || !preserve_user_preferences {
            live.as_table_mut().remove(&key);
        }
    }

    // Step 2: overlay every snapshot entry except live runtime keys.
    //
    // - Provider-scoped keys always overwrite live (the snapshot is the source
    //   of truth for these).
    // - User-owned keys overwrite live unless we are preserving live
    //   preferences AND the key already exists in live (in which case live
    //   wins). When the key is missing from live we still take the snapshot's
    //   value so initial writes get seeded.
    let snap_keys: Vec<String> = snap.as_table().iter().map(|(k, _)| k.to_string()).collect();
    for key in snap_keys {
        if LIVE_RUNTIME_KEYS.contains(&key.as_str()) {
            continue;
        }
        let is_provider_scoped = PROVIDER_SCOPED_KEYS.contains(&key.as_str());
        if !is_provider_scoped && preserve_user_preferences && live.get(&key).is_some() {
            continue;
        }
        if let Some(val) = snap.get(&key) {
            live[key.as_str()] = val.clone();
        }
    }

    Ok(live.to_string())
}

/// Rewrite a stored Codex provider snapshot to use a specific provider key.
///
/// This updates both the root `model_provider` and the matching
/// `[model_providers.<key>]` table, while preserving the provider table body and
/// profile references.
pub fn rewrite_codex_config_model_provider_key(
    config_text: &str,
    target_provider_id: &str,
) -> Result<String, AppError> {
    if config_text.trim().is_empty() {
        return Ok(String::new());
    }

    let target_provider_id = clean_codex_provider_display_key(target_provider_id);
    let mut doc = config_text
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
    let Some(source_provider_id) = primary_codex_model_provider_id_with_table(&doc) else {
        return Ok(config_text.to_string());
    };

    if let Some(model_providers) = doc
        .get_mut("model_providers")
        .and_then(|item| item.as_table_mut())
    {
        if source_provider_id != target_provider_id {
            let Some(provider_table) = model_providers.remove(source_provider_id.as_str()) else {
                return Ok(config_text.to_string());
            };
            model_providers[target_provider_id.as_str()] = provider_table;
            rewrite_codex_profile_model_provider_refs(
                &mut doc,
                &source_provider_id,
                &target_provider_id,
            );
        }
    } else {
        return Ok(config_text.to_string());
    }

    doc["model_provider"] = toml_edit::value(target_provider_id.as_str());

    Ok(doc.to_string())
}

pub fn rewrite_codex_config_model_provider_name(
    config_text: &str,
    provider_key: &str,
    provider_name: &str,
) -> Result<String, AppError> {
    let mut doc = config_text
        .parse::<DocumentMut>()
        .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
    let provider = doc
        .get_mut("model_providers")
        .and_then(|item| item.as_table_like_mut())
        .and_then(|providers| providers.get_mut(provider_key))
        .and_then(|item| item.as_table_like_mut())
        .ok_or_else(|| {
            AppError::Config(format!(
                "Codex provider `{provider_key}` is missing from model_providers"
            ))
        })?;
    provider.insert("name", toml_edit::value(provider_name));
    Ok(doc.to_string())
}

pub fn selected_codex_provider_base_url(config_text: &str) -> Result<Option<String>, AppError> {
    let config_text = config_text.trim();
    if config_text.is_empty() {
        return Ok(None);
    }

    let table = toml::from_str::<toml::Table>(config_text)
        .map_err(|source| AppError::toml(Path::new("config.toml"), source))?;
    let selected_url = table
        .get("model_provider")
        .and_then(toml::Value::as_str)
        .and_then(|key| table.get("model_providers")?.as_table()?.get(key))
        .and_then(toml::Value::as_table)
        .and_then(|provider| provider.get("base_url"))
        .and_then(toml::Value::as_str)
        .map(str::trim)
        .filter(|url| !url.is_empty())
        .map(str::to_string);

    Ok(selected_url.or_else(|| {
        table
            .get("base_url")
            .and_then(toml::Value::as_str)
            .map(str::trim)
            .filter(|url| !url.is_empty())
            .map(str::to_string)
    }))
}

/// Generate a clean TOML key from a raw string for use as `model_provider` and `[model_providers.<key>]`.
///
/// Lowercases ASCII alphanumerics, replaces everything else with `_`, trims leading/trailing `_`.
/// Falls back to `"custom"` if the result is empty.
pub fn clean_codex_provider_key(raw: &str) -> String {
    let mut key: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();

    while key.starts_with('_') {
        key.remove(0);
    }
    while key.ends_with('_') {
        key.pop();
    }

    if key.is_empty() {
        "custom".to_string()
    } else {
        key
    }
}

pub fn clean_codex_provider_display_key(raw: &str) -> String {
    let mut key: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else if c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();

    while key.starts_with(['-', '_']) {
        key.remove(0);
    }
    while key.ends_with(['-', '_']) {
        key.pop();
    }

    if key.is_empty() {
        "custom".to_string()
    } else {
        key
    }
}

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

    #[test]
    fn merge_preserves_user_preferences_and_mcp_from_live() {
        // Current live config has user preferences and MCP servers
        let live = indoc::indoc! {r#"
            model_provider = "old-provider"
            model = "old-model"
            disable_response_storage = true
            model_reasoning_effort = "xhigh"
            approval_mode = "auto-edit"
            check_for_update_on_startup = false

            [model_providers.old-provider]
            name = "Old"

            [projects."/tmp/work"]
            trusted = true

            [mcp_servers.cargo-mcp]
            type = "stdio"
        "#};

        // Snapshot has different provider and its own [projects], no [mcp_servers]
        let snapshot = indoc::indoc! {r#"
            model_provider = "new-provider"
            model = "new-model"
            approval_mode = "suggest"

            [model_providers.new-provider]
            name = "New"
            api_key = "sk-test"

            [projects."/tmp/other"]
            trusted = true
        "#};

        let merged = merge_provider_into_codex_live_config(live, snapshot, true).unwrap();
        let doc: toml_edit::DocumentMut = merged.parse().unwrap();

        // Provider fields come from snapshot
        assert_eq!(doc["model_provider"].as_str(), Some("new-provider"));
        assert_eq!(doc["model"].as_str(), Some("new-model"));
        assert!(doc
            .get("model_providers")
            .unwrap()
            .get("new-provider")
            .is_some());
        assert!(doc
            .get("model_providers")
            .unwrap()
            .get("old-provider")
            .is_none());

        // User preferences come from live (not snapshot's approval_mode)
        assert_eq!(doc["disable_response_storage"].as_bool(), Some(true));
        assert_eq!(doc["model_reasoning_effort"].as_str(), Some("xhigh"));
        assert_eq!(doc["approval_mode"].as_str(), Some("auto-edit"));
        assert_eq!(doc["check_for_update_on_startup"].as_bool(), Some(false));

        // [projects] comes from live because trust decisions are workspace-local.
        assert!(doc.get("projects").unwrap().get("/tmp/work").is_some());
        assert!(doc.get("projects").unwrap().get("/tmp/other").is_none());

        // [mcp_servers] comes from live (preserves comments and manual edits)
        assert!(doc.get("mcp_servers").is_some());
        assert!(doc.get("mcp_servers").unwrap().get("cargo-mcp").is_some());
    }

    #[test]
    fn merge_preserves_live_runtime_projects_from_provider_snapshot() {
        let live = indoc::indoc! {r#"
            model_provider = "old-provider"
            trusted_workspaces = ["/tmp/live-workspace"]

            [model_providers.old-provider]
            name = "Old"

            [projects."/tmp/live-project"]
            trust_level = "trusted"
        "#};

        let snapshot = indoc::indoc! {r#"
            model_provider = "new-provider"
            trusted_workspaces = ["/tmp/snapshot-workspace"]

            [model_providers.new-provider]
            name = "New"

            [projects."/tmp/snapshot-project"]
            trust_level = "trusted"
        "#};

        let merged = merge_provider_into_codex_live_config(live, snapshot, true).unwrap();
        let doc: toml_edit::DocumentMut = merged.parse().unwrap();
        let projects = doc.get("projects").expect("projects should be preserved");
        let trusted_workspaces = doc["trusted_workspaces"]
            .as_array()
            .expect("trusted_workspaces should be preserved");

        assert!(projects.get("/tmp/live-project").is_some());
        assert!(projects.get("/tmp/snapshot-project").is_none());
        assert_eq!(trusted_workspaces.len(), 1);
        assert_eq!(
            trusted_workspaces.get(0).and_then(|value| value.as_str()),
            Some("/tmp/live-workspace")
        );
    }

    #[test]
    fn merge_keeps_commented_out_mcp_entries_verbatim() {
        // The user has temporarily disabled an MCP server by commenting out
        // its whole subtable. Switching providers must NOT uncomment these
        // lines or drop them. Also exercises a comment-only line before an
        // active subtable, and a trailing comment after a value.
        let live = "\
model_provider = \"old\"
approval_mode = \"suggest\"

# top-level note for mcp_servers section
[mcp_servers.active]
# comment before command
command = \"runme\" # trailing comment

# this one is temporarily disabled
# [mcp_servers.disabled]
# command = \"nope\"
# args = [\"--off\"]
";

        let snapshot = "\
model_provider = \"new\"

[model_providers.new]
name = \"New\"
";

        let merged = merge_provider_into_codex_live_config(live, snapshot, true).unwrap();

        // Every comment line from the live mcp_servers region must survive verbatim.
        for needle in [
            "# top-level note for mcp_servers section",
            "# comment before command",
            "# trailing comment",
            "# this one is temporarily disabled",
            "# [mcp_servers.disabled]",
            "# command = \"nope\"",
            "# args = [\"--off\"]",
        ] {
            assert!(
                merged.contains(needle),
                "merged output is missing comment line: {needle:?}\n--- merged ---\n{merged}"
            );
        }

        // And the structural parts still parse and resolve as expected.
        let doc: toml_edit::DocumentMut = merged.parse().unwrap();
        assert_eq!(doc["model_provider"].as_str(), Some("new"));
        assert!(doc
            .get("mcp_servers")
            .and_then(|t| t.get("active"))
            .is_some());
        assert!(doc
            .get("mcp_servers")
            .and_then(|t| t.get("disabled"))
            .is_none());
    }

    #[test]
    fn merge_seeds_preferences_from_snapshot_when_live_is_empty() {
        // Initial write path: live config doesn't exist yet, snapshot carries
        // merged common-snippet defaults like disable_response_storage.
        // With preserve_user_preferences=true, the snapshot's preferences must
        // still land in the resulting file — otherwise the common snippet is lost.
        let snapshot = indoc::indoc! {r#"
            model_provider = "first"
            model = "gpt-5.2-codex"
            disable_response_storage = true
            approval_mode = "suggest"

            [model_providers.first]
            base_url = "https://api.example/v1"
        "#};

        let merged = merge_provider_into_codex_live_config("", snapshot, true).unwrap();
        assert!(
            merged.contains("disable_response_storage = true"),
            "snapshot-provided preference should seed an empty live config\n--- merged ---\n{merged}"
        );
        assert!(merged.contains("approval_mode = \"suggest\""));
        assert!(merged.contains("model_provider = \"first\""));
    }

    #[test]
    fn merge_with_preserve_false_drops_live_prefs_missing_from_snapshot() {
        // Common-snippet "clear" path: snapshot has no preference keys, so live
        // preferences left behind by a previous snippet must be removed.
        let live = indoc::indoc! {r#"
            model_provider = "p1"
            disable_response_storage = true
            model_reasoning_effort = "xhigh"

            [model_providers.p1]
            base_url = "https://a"
        "#};

        let snapshot = indoc::indoc! {r#"
            model_provider = "p1"

            [model_providers.p1]
            base_url = "https://a"
        "#};

        let merged = merge_provider_into_codex_live_config(live, snapshot, false).unwrap();
        let doc: toml_edit::DocumentMut = merged.parse().unwrap();
        assert!(doc.get("disable_response_storage").is_none());
        assert!(doc.get("model_reasoning_effort").is_none());
        assert_eq!(doc["model_provider"].as_str(), Some("p1"));
    }

    #[test]
    fn merge_keeps_unknown_root_keys_from_live_on_switch() {
        // Regression guard for forward compatibility: if Codex introduces a
        // new root-level preference key tomorrow (e.g. `sandbox_mode`,
        // `verbose_logging`, or anything else not yet listed in
        // PROVIDER_SCOPED_KEYS), the user's live value must survive a
        // provider switch without us having to update this file.
        let live = indoc::indoc! {r#"
            model_provider = "old"
            sandbox_mode = "danger-full-access"
            verbose_logging = true

            [model_providers.old]
            name = "Old"
        "#};

        // Snapshot is from a stored provider that doesn't know about the new
        // keys at all (older snapshot, or a provider configured before the
        // user added them).
        let snapshot = indoc::indoc! {r#"
            model_provider = "new"

            [model_providers.new]
            name = "New"
        "#};

        let merged = merge_provider_into_codex_live_config(live, snapshot, true).unwrap();
        let doc: toml_edit::DocumentMut = merged.parse().unwrap();

        // Provider-scoped keys followed the snapshot.
        assert_eq!(doc["model_provider"].as_str(), Some("new"));
        assert!(doc
            .get("model_providers")
            .and_then(|t| t.get("new"))
            .is_some());
        assert!(doc
            .get("model_providers")
            .and_then(|t| t.get("old"))
            .is_none());

        // Unknown root keys stayed put.
        assert_eq!(doc["sandbox_mode"].as_str(), Some("danger-full-access"));
        assert_eq!(doc["verbose_logging"].as_bool(), Some(true));
    }

    #[test]
    fn merge_keeps_root_level_comments_around_overwritten_keys() {
        // In toml_edit's model, comment-only lines between two root-level
        // keys are attached to the **next** key's prefix decor. When the
        // snapshot overwrites that next key, the comments must still be
        // there afterwards — otherwise users lose any inline notes they
        // sprinkled into ~/.codex/config.toml.
        let live = "\
# pinned by me — do not change without checking the runbook
model_provider = \"old\"

# disabled while debugging issue-1234
# disable_response_storage = true
approval_mode = \"auto-edit\"

# trailing footnote at EOF
";

        let snapshot = "\
model_provider = \"new\"

[model_providers.new]
name = \"New\"
";

        let merged = merge_provider_into_codex_live_config(live, snapshot, true).unwrap();

        for needle in [
            "# pinned by me — do not change without checking the runbook",
            "# disabled while debugging issue-1234",
            "# disable_response_storage = true",
            "# trailing footnote at EOF",
        ] {
            assert!(
                merged.contains(needle),
                "merged output is missing comment line: {needle:?}\n--- merged ---\n{merged}"
            );
        }

        let doc: toml_edit::DocumentMut = merged.parse().unwrap();
        assert_eq!(doc["model_provider"].as_str(), Some("new"));
        assert_eq!(doc["approval_mode"].as_str(), Some("auto-edit"));
    }

    #[test]
    fn merge_omits_mcp_section_when_live_has_none() {
        let live = indoc::indoc! {r#"
            model_provider = "foo"
            approval_mode = "suggest"
        "#};

        let snapshot = indoc::indoc! {r#"
            model_provider = "bar"
        "#};

        let merged = merge_provider_into_codex_live_config(live, snapshot, true).unwrap();
        let doc: toml_edit::DocumentMut = merged.parse().unwrap();

        assert_eq!(doc["model_provider"].as_str(), Some("bar"));
        assert!(doc.get("mcp_servers").is_none());
        assert_eq!(doc["approval_mode"].as_str(), Some("suggest"));
    }
    use crate::app_config::AppType;
    use crate::test_support::{lock_test_home_and_settings, set_test_home_override};
    use std::ffi::OsString;
    use std::path::Path;

    struct CodexHomeEnvGuard {
        original: Option<OsString>,
    }

    impl CodexHomeEnvGuard {
        fn new(value: Option<&str>) -> Self {
            let original = std::env::var_os("CODEX_HOME");
            match value {
                Some(v) => unsafe { std::env::set_var("CODEX_HOME", v) },
                None => unsafe { std::env::remove_var("CODEX_HOME") },
            }
            Self { original }
        }
    }

    impl Drop for CodexHomeEnvGuard {
        fn drop(&mut self) {
            match self.original.as_ref() {
                Some(value) => unsafe { std::env::set_var("CODEX_HOME", value) },
                None => unsafe { std::env::remove_var("CODEX_HOME") },
            }
        }
    }

    struct SettingsGuard {
        original: crate::settings::AppSettings,
    }

    impl SettingsGuard {
        fn with_codex_config_dir(dir: Option<&str>) -> Self {
            let original = crate::settings::get_settings();
            let mut settings = original.clone();
            settings.codex_config_dir = dir.map(str::to_string);
            crate::settings::update_settings(settings).unwrap();
            Self { original }
        }
    }

    impl Drop for SettingsGuard {
        fn drop(&mut self) {
            let _ = crate::settings::update_settings(self.original.clone());
        }
    }

    #[test]
    fn get_codex_config_dir_respects_codex_home_env_var_and_tilde() {
        let _guard = lock_test_home_and_settings();
        let _settings = SettingsGuard::with_codex_config_dir(None);
        let _env = CodexHomeEnvGuard::new(Some("~/.config/codex"));
        set_test_home_override(Some(Path::new("/tmp/codex-home-tilde")));

        assert_eq!(
            get_codex_config_dir(),
            PathBuf::from("/tmp/codex-home-tilde")
                .join(".config")
                .join("codex")
        );

        set_test_home_override(None);
    }

    #[test]
    fn get_codex_config_dir_env_overrides_settings_override() {
        let _guard = lock_test_home_and_settings();
        let _settings = SettingsGuard::with_codex_config_dir(Some("/tmp/settings-codex"));
        let _env = CodexHomeEnvGuard::new(Some("/tmp/env-codex"));
        set_test_home_override(Some(Path::new("/tmp/codex-home")));

        assert_eq!(get_codex_config_dir(), PathBuf::from("/tmp/env-codex"));

        set_test_home_override(None);
    }

    #[test]
    fn codex_live_sync_detects_initialized_codex_home_from_env() {
        let _guard = lock_test_home_and_settings();
        let _settings = SettingsGuard::with_codex_config_dir(None);
        let env_home = PathBuf::from("/tmp/codex-live-sync-env");
        let _env = CodexHomeEnvGuard::new(Some(env_home.to_str().unwrap()));
        set_test_home_override(Some(Path::new("/tmp/codex-live-sync-home")));

        std::fs::create_dir_all(&env_home).expect("create CODEX_HOME");

        assert!(crate::sync_policy::should_sync_live(&AppType::Codex));

        let _ = std::fs::remove_dir_all(&env_home);
        set_test_home_override(None);
    }

    #[test]
    fn normalize_live_config_preserves_current_custom_model_provider_id() {
        let current = r#"model_provider = "rightcode"

[model_providers.rightcode]
name = "RightCode"
base_url = "https://rightcode.example/v1"
wire_api = "responses"
"#;
        let target = r#"model_provider = "aihubmix"
model = "gpt-5.4"

[model_providers.aihubmix]
name = "AiHubMix"
base_url = "https://aihubmix.example/v1"
wire_api = "responses"
requires_openai_auth = true

[mcp_servers.context7]
command = "npx"
"#;

        let result =
            normalize_codex_live_config_model_provider_with_anchors(target, Some(current)).unwrap();
        let parsed: toml::Value = toml::from_str(&result).unwrap();

        assert_eq!(
            parsed.get("model_provider").and_then(|v| v.as_str()),
            Some("rightcode")
        );

        let model_providers = parsed
            .get("model_providers")
            .and_then(|v| v.as_table())
            .expect("model_providers should exist");
        assert!(
            model_providers.get("aihubmix").is_none(),
            "source provider id should not remain in live config"
        );

        let stable_provider = model_providers
            .get("rightcode")
            .expect("stable provider table should exist");
        assert_eq!(
            stable_provider.get("base_url").and_then(|v| v.as_str()),
            Some("https://aihubmix.example/v1")
        );
        assert!(
            parsed.get("mcp_servers").is_some(),
            "unrelated config should be preserved"
        );
    }

    #[test]
    fn normalize_live_config_uses_target_custom_provider_when_current_is_reserved() {
        let current = r#"model_provider = "openai""#;
        let target = r#"model_provider = "aihubmix"

[model_providers.aihubmix]
name = "AiHubMix"
base_url = "https://aihubmix.example/v1"
wire_api = "responses"
"#;

        let result =
            normalize_codex_live_config_model_provider_with_anchors(target, Some(current)).unwrap();
        let parsed: toml::Value = toml::from_str(&result).unwrap();

        assert_eq!(
            parsed.get("model_provider").and_then(|v| v.as_str()),
            Some("aihubmix")
        );
        assert!(
            parsed
                .get("model_providers")
                .and_then(|v| v.get("aihubmix"))
                .is_some(),
            "target provider id should be kept when there is no reusable live custom id"
        );
    }

    #[test]
    fn normalize_live_config_leaves_official_empty_config_unchanged() {
        let current = r#"model_provider = "rightcode"

[model_providers.rightcode]
base_url = "https://rightcode.example/v1"
"#;

        let result =
            normalize_codex_live_config_model_provider_with_anchors("", Some(current)).unwrap();

        assert_eq!(result, "");
    }

    #[test]
    fn normalize_live_config_rewrites_matching_profile_model_provider_refs() {
        let current = r#"model_provider = "session_anchor"

[model_providers.session_anchor]
name = "Session Anchor"
base_url = "https://anchor.example/v1"
wire_api = "responses"
"#;
        let target = r#"model_provider = "vendor_alpha"
model = "gpt-5.4"
profile = "work"

[model_providers.vendor_alpha]
name = "Vendor Alpha"
base_url = "https://alpha.example/v1"
wire_api = "responses"

[profiles.work]
model_provider = "vendor_alpha"
model = "gpt-5.4"
"#;

        let result =
            normalize_codex_live_config_model_provider_with_anchors(target, Some(current)).unwrap();
        let parsed: toml::Value = toml::from_str(&result).unwrap();

        assert_eq!(
            parsed.get("model_provider").and_then(|v| v.as_str()),
            Some("session_anchor")
        );
        assert_eq!(
            parsed
                .get("profiles")
                .and_then(|v| v.get("work"))
                .and_then(|v| v.get("model_provider"))
                .and_then(|v| v.as_str()),
            Some("session_anchor"),
            "profile override matching the rewritten provider should stay valid"
        );
    }

    #[test]
    fn normalize_live_config_keeps_unrelated_profile_model_provider_refs() {
        let current = r#"model_provider = "session_anchor"

[model_providers.session_anchor]
name = "Session Anchor"
base_url = "https://anchor.example/v1"
wire_api = "responses"
"#;
        let target = r#"model_provider = "vendor_alpha"
model = "gpt-5.4"

[model_providers.vendor_alpha]
name = "Vendor Alpha"
base_url = "https://alpha.example/v1"
wire_api = "responses"

[model_providers.local_profile]
name = "Local Profile"
base_url = "http://localhost:11434/v1"
wire_api = "responses"

[profiles.local]
model_provider = "local_profile"
model = "local-model"
"#;

        let result =
            normalize_codex_live_config_model_provider_with_anchors(target, Some(current)).unwrap();
        let parsed: toml::Value = toml::from_str(&result).unwrap();

        assert_eq!(
            parsed
                .get("profiles")
                .and_then(|v| v.get("local"))
                .and_then(|v| v.get("model_provider"))
                .and_then(|v| v.as_str()),
            Some("local_profile"),
            "unrelated profile provider references should be preserved"
        );
        assert!(
            parsed
                .get("model_providers")
                .and_then(|v| v.get("local_profile"))
                .is_some(),
            "unrelated provider tables should also remain available"
        );
    }

    #[test]
    fn normalize_live_config_keeps_stable_provider_across_repeated_switches() {
        let anchor = r#"model_provider = "session_anchor"

[model_providers.session_anchor]
name = "Session Anchor"
base_url = "https://anchor.example/v1"
wire_api = "responses"
"#;
        let first_target = r#"model_provider = "vendor_alpha"

[model_providers.vendor_alpha]
name = "Vendor Alpha"
base_url = "https://alpha.example/v1"
wire_api = "responses"
"#;
        let second_target = r#"model_provider = "vendor_beta"

[model_providers.vendor_beta]
name = "Vendor Beta"
base_url = "https://beta.example/v1"
wire_api = "responses"
"#;

        let first =
            normalize_codex_live_config_model_provider_with_anchors(first_target, Some(anchor))
                .unwrap();
        let second = normalize_codex_live_config_model_provider_with_anchors(
            second_target,
            Some(first.as_str()),
        )
        .unwrap();
        let parsed: toml::Value = toml::from_str(&second).unwrap();

        assert_eq!(
            parsed.get("model_provider").and_then(|v| v.as_str()),
            Some("session_anchor"),
            "stable provider id should not drift across repeated switches"
        );
        assert_eq!(
            parsed
                .get("model_providers")
                .and_then(|v| v.get("session_anchor"))
                .and_then(|v| v.get("base_url"))
                .and_then(|v| v.as_str()),
            Some("https://beta.example/v1")
        );
    }

    #[test]
    fn restore_backfill_config_rewrites_live_id_to_template_provider_id() {
        let mut settings = serde_json::json!({
            "config": r#"model_provider = "session_anchor"
model = "gpt-5.4"
profile = "work"

[model_providers.session_anchor]
name = "AiHubMix"
base_url = "https://aihubmix.example/v1"
wire_api = "responses"

[profiles.work]
model_provider = "session_anchor"
model = "gpt-5.4"
"#
        });
        let template = serde_json::json!({
            "config": r#"model_provider = "aihubmix"

[model_providers.aihubmix]
name = "AiHubMix"
base_url = "https://aihubmix.example/v1"
"#
        });

        restore_codex_settings_config_model_provider_for_backfill(&mut settings, &template)
            .unwrap();

        let config = codex_config_text_from_settings(&settings).unwrap();
        let parsed: toml::Value = toml::from_str(&config).unwrap();
        assert_eq!(
            parsed.get("model_provider").and_then(|v| v.as_str()),
            Some("aihubmix")
        );
        assert!(parsed
            .get("model_providers")
            .and_then(|v| v.get("aihubmix"))
            .is_some());
        assert_eq!(
            parsed
                .get("profiles")
                .and_then(|v| v.get("work"))
                .and_then(|v| v.get("model_provider"))
                .and_then(|v| v.as_str()),
            Some("aihubmix")
        );
    }

    #[test]
    fn clean_codex_provider_display_key_preserves_hyphens() {
        assert_eq!(
            clean_codex_provider_display_key("zhima-cx-pro"),
            "zhima-cx-pro"
        );
    }
}