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
use futures::executor::block_on;
use serde_json::json;
use std::{fs, path::Path};

use cc_switch_lib::{
    get_app_config_dir, get_claude_settings_path, read_json_file, AppError, AppType, ConfigService,
    Database, MultiAppConfig, Provider, ProviderMeta, ProviderService,
};

#[path = "support.rs"]
mod support;
use support::{ensure_test_home, lock_test_mutex, reset_test_fs, state_from_config};

#[test]
fn sync_claude_provider_writes_live_settings() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let home = ensure_test_home();

    let mut config = MultiAppConfig::default();
    let provider_config = json!({
        "env": {
            "ANTHROPIC_AUTH_TOKEN": "test-key",
            "ANTHROPIC_BASE_URL": "https://api.test"
        },
        "ui": {
            "displayName": "Test Provider"
        }
    });

    let provider = Provider::with_id(
        "prov-1".to_string(),
        "Test Claude".to_string(),
        provider_config.clone(),
        None,
    );

    let manager = config
        .get_manager_mut(&AppType::Claude)
        .expect("claude manager");
    manager.providers.insert("prov-1".to_string(), provider);
    manager.current = "prov-1".to_string();

    ConfigService::sync_current_providers_to_live(&mut config).expect("sync live settings");

    let settings_path = get_claude_settings_path();
    assert!(
        settings_path.exists(),
        "live settings should be written to {}",
        settings_path.display()
    );

    let live_value: serde_json::Value = read_json_file(&settings_path).expect("read live file");
    assert_eq!(live_value, provider_config);

    // 确认 SSOT 中的供应商也同步了最新内容
    let updated = config
        .get_manager(&AppType::Claude)
        .and_then(|m| m.providers.get("prov-1"))
        .expect("provider in config");
    assert_eq!(updated.settings_config, provider_config);

    // 额外确认写入位置位于测试 HOME 下
    assert!(
        settings_path.starts_with(home),
        "settings path {settings_path:?} should reside under test HOME {home:?}"
    );
}

#[test]
fn sync_codex_provider_writes_auth_and_config() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    let mut config = MultiAppConfig::default();

    // 添加入测 MCP 启用项,确保 sync_enabled_to_codex 会写入 TOML
    config.mcp.codex.servers.insert(
        "echo-server".into(),
        json!({
            "id": "echo-server",
            "enabled": true,
            "server": {
                "type": "stdio",
                "command": "echo",
                "args": ["hello"]
            }
        }),
    );

    let provider_config = json!({
        "auth": {
            "OPENAI_API_KEY": "codex-key"
        },
        "codex": {
            "base_url": "https://codex.test"
        }
    });

    let provider = Provider::with_id(
        "codex-1".to_string(),
        "Codex Test".to_string(),
        provider_config.clone(),
        None,
    );

    let manager = config
        .get_manager_mut(&AppType::Codex)
        .expect("codex manager");
    manager.providers.insert("codex-1".to_string(), provider);
    manager.current = "codex-1".to_string();

    ConfigService::sync_current_providers_to_live(&mut config).expect("sync codex live");

    let auth_path = cc_switch_lib::get_codex_auth_path();
    let config_path = cc_switch_lib::get_codex_config_path();

    assert!(
        auth_path.exists(),
        "auth.json should exist at {}",
        auth_path.display()
    );
    assert!(
        config_path.exists(),
        "config.toml should exist at {}",
        config_path.display()
    );

    let auth_value: serde_json::Value = read_json_file(&auth_path).expect("read auth");
    assert_eq!(
        auth_value,
        provider_config.get("auth").cloned().expect("auth object")
    );

    let toml_text = fs::read_to_string(&config_path).expect("read config.toml");
    assert!(
        toml_text.contains("command = \"echo\""),
        "config.toml should contain serialized enabled MCP server"
    );

    // 当前供应商应同步最新 config 文本
    let manager = config.get_manager(&AppType::Codex).expect("codex manager");
    let synced = manager.providers.get("codex-1").expect("codex provider");
    let synced_cfg = cc_switch_lib::codex_config_text_from_settings(&synced.settings_config)
        .expect("synced config should render to config.toml");
    let synced_toml: toml::Value = toml::from_str(&synced_cfg).expect("parse synced config");
    let live_toml: toml::Value = toml::from_str(&toml_text).expect("parse live config");
    assert_eq!(synced_toml, live_toml);
}

#[test]
fn sync_codex_provider_writes_selected_model_provider_id_to_live() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    let legacy_auth = json!({ "OPENAI_API_KEY": "rightcode-key" });
    let legacy_config = r#"model_provider = "rightcode"
model = "gpt-5.4"

[model_providers.rightcode]
name = "RightCode"
base_url = "https://rightcode.example/v1"
wire_api = "responses"
requires_openai_auth = true
"#;
    cc_switch_lib::write_codex_live_atomic(&legacy_auth, Some(legacy_config))
        .expect("seed existing Codex live config");

    let mut config = MultiAppConfig::default();
    let provider_config = json!({
        "auth": {
            "OPENAI_API_KEY": "fresh-key"
        },
        "config": 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
"#
    });

    let provider = Provider::with_id(
        "codex-1".to_string(),
        "Codex Test".to_string(),
        provider_config,
        None,
    );

    let manager = config
        .get_manager_mut(&AppType::Codex)
        .expect("codex manager");
    manager.providers.insert("codex-1".to_string(), provider);
    manager.current = "codex-1".to_string();

    ConfigService::sync_current_providers_to_live(&mut config).expect("sync codex live");

    let toml_text =
        fs::read_to_string(cc_switch_lib::get_codex_config_path()).expect("read config.toml");
    let parsed: toml::Value = toml::from_str(&toml_text).expect("parse config.toml");

    assert_eq!(
        parsed.get("model_provider").and_then(|v| v.as_str()),
        Some("aihubmix"),
        "ConfigService sync should write the selected provider id to live"
    );

    let model_providers = parsed
        .get("model_providers")
        .and_then(|v| v.as_table())
        .expect("model_providers should exist");
    assert!(
        model_providers.get("aihubmix").is_some(),
        "provider-specific target id should be written to live config"
    );
    assert_eq!(
        model_providers
            .get("aihubmix")
            .and_then(|v| v.get("base_url"))
            .and_then(|v| v.as_str()),
        Some("https://aihubmix.example/v1")
    );

    let synced_settings = config
        .get_manager(&AppType::Codex)
        .and_then(|manager| manager.providers.get("codex-1"))
        .map(|provider| &provider.settings_config)
        .expect("synced config settings");
    let synced_cfg = cc_switch_lib::codex_config_text_from_settings(synced_settings)
        .expect("synced config should render to config.toml");
    assert!(
        synced_cfg.contains("[model_providers.aihubmix]"),
        "ConfigService keeps syncing provider config from live"
    );
}

#[test]
fn sync_enabled_to_codex_writes_enabled_servers() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    // Ensure ~/.codex dir exists (simulates Codex being installed)
    let codex_dir = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = codex_dir.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }

    let mut config = MultiAppConfig::default();
    config.mcp.codex.servers.insert(
        "stdio-enabled".into(),
        json!({
            "id": "stdio-enabled",
            "enabled": true,
            "server": {
                "type": "stdio",
                "command": "echo",
                "args": ["ok"],
            }
        }),
    );

    cc_switch_lib::sync_enabled_to_codex(&config).expect("sync codex");

    let path = cc_switch_lib::get_codex_config_path();
    assert!(path.exists(), "config.toml should be created");
    let text = fs::read_to_string(&path).expect("read config.toml");
    assert!(
        text.contains("mcp_servers") && text.contains("stdio-enabled"),
        "enabled servers should be serialized"
    );
}

#[test]
fn sync_enabled_to_codex_preserves_non_mcp_content_and_style() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    // 预置含有顶层注释与非 MCP 键的 config.toml
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    let seed = r#"# top-comment
title = "keep-me"

[profile]
mode = "dev"
"#;
    fs::write(&path, seed).expect("seed config.toml");

    // 启用一个 MCP 项,触发增量写入
    let mut config = MultiAppConfig::default();
    config.mcp.codex.servers.insert(
        "echo".into(),
        json!({
            "id": "echo",
            "enabled": true,
            "server": { "type": "stdio", "command": "echo" }
        }),
    );

    cc_switch_lib::sync_enabled_to_codex(&config).expect("sync codex");

    let text = fs::read_to_string(&path).expect("read config.toml");
    // 顶层注释与非 MCP 键应保留
    assert!(
        text.contains("# top-comment"),
        "top comment should be preserved"
    );
    assert!(
        text.contains("title = \"keep-me\""),
        "top key should be preserved"
    );
    assert!(
        text.contains("[profile]"),
        "non-MCP table should be preserved"
    );
    assert!(
        text.contains("mcp_servers"),
        "mcp_servers table should be present"
    );
    assert!(
        !text.contains("[mcp.servers]"),
        "invalid [mcp.servers] table should not appear"
    );
    assert!(
        text.contains("echo") && text.contains("command = \"echo\""),
        "echo server should be serialized"
    );
}

#[test]
fn sync_enabled_to_codex_migrates_erroneous_mcp_dot_servers_to_mcp_servers() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    // 预置错误的 mcp.servers 风格(应迁移为顶层 mcp_servers)
    let seed = r#"[mcp]
  other = "keep"
  [mcp.servers]
"#;
    fs::write(&path, seed).expect("seed config.toml");

    let mut config = MultiAppConfig::default();
    config.mcp.codex.servers.insert(
        "echo".into(),
        json!({
            "id": "echo",
            "enabled": true,
            "server": { "type": "stdio", "command": "echo" }
        }),
    );

    cc_switch_lib::sync_enabled_to_codex(&config).expect("sync codex");
    let text = fs::read_to_string(&path).expect("read config.toml");
    // 应迁移到顶层 mcp_servers,并移除错误的 mcp.servers 表
    assert!(
        text.contains("mcp_servers"),
        "should migrate to mcp_servers table"
    );
    assert!(
        !text.contains("[mcp.servers]"),
        "invalid [mcp.servers] table should be removed"
    );
}

#[test]
fn sync_enabled_to_codex_removes_servers_when_none_enabled() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers]
disabled = { type = "stdio", command = "noop" }
"#,
    )
    .expect("seed config file");

    let config = MultiAppConfig::default(); // 无启用项
    cc_switch_lib::sync_enabled_to_codex(&config).expect("sync codex");

    let text = fs::read_to_string(&path).expect("read config.toml");
    assert!(
        !text.contains("mcp_servers") && !text.contains("servers"),
        "disabled entries should be removed from config.toml"
    );
}

#[test]
fn sync_enabled_to_codex_returns_error_on_invalid_toml() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(&path, "invalid = [").expect("write invalid config");

    let mut config = MultiAppConfig::default();
    config.mcp.codex.servers.insert(
        "broken".into(),
        json!({
            "id": "broken",
            "enabled": true,
            "server": {
                "type": "stdio",
                "command": "echo"
            }
        }),
    );

    let err = cc_switch_lib::sync_enabled_to_codex(&config).expect_err("sync should fail");
    match err {
        cc_switch_lib::AppError::Toml { path, .. } => {
            assert!(
                path.ends_with("config.toml"),
                "path should reference config.toml"
            );
        }
        cc_switch_lib::AppError::McpValidation(msg) => {
            assert!(
                msg.contains("config.toml"),
                "error message should mention config.toml"
            );
        }
        other => panic!("unexpected error: {other:?}"),
    }
}

#[test]
fn sync_codex_provider_missing_auth_returns_error() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    let mut config = MultiAppConfig::default();
    let provider = Provider::with_id(
        "codex-missing-auth".to_string(),
        "No Auth".to_string(),
        json!({
            "config": "model = \"test\""
        }),
        None,
    );
    let manager = config
        .get_manager_mut(&AppType::Codex)
        .expect("codex manager");
    manager.providers.insert(provider.id.clone(), provider);
    manager.current = "codex-missing-auth".to_string();

    let err = ConfigService::sync_current_providers_to_live(&mut config)
        .expect_err("sync should fail when auth missing");
    match err {
        cc_switch_lib::AppError::Config(msg) => {
            assert!(msg.contains("auth"), "error message should mention auth");
        }
        other => panic!("unexpected error variant: {other:?}"),
    }

    // 确认未产生任何 live 配置文件
    assert!(
        !cc_switch_lib::get_codex_auth_path().exists(),
        "auth.json should not be created on failure"
    );
    assert!(
        !cc_switch_lib::get_codex_config_path().exists(),
        "config.toml should not be created on failure"
    );
}

#[test]
fn write_codex_live_atomic_persists_auth_and_config() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    let auth = json!({ "OPENAI_API_KEY": "dev-key" });
    let config_text = r#"
[mcp_servers.echo]
type = "stdio"
command = "echo"
args = ["ok"]
"#;

    cc_switch_lib::write_codex_live_atomic(&auth, Some(config_text))
        .expect("atomic write should succeed");

    let auth_path = cc_switch_lib::get_codex_auth_path();
    let config_path = cc_switch_lib::get_codex_config_path();
    assert!(auth_path.exists(), "auth.json should be created");
    assert!(config_path.exists(), "config.toml should be created");

    let stored_auth: serde_json::Value =
        cc_switch_lib::read_json_file(&auth_path).expect("read auth");
    assert_eq!(stored_auth, auth, "auth.json should match input");

    let stored_config = std::fs::read_to_string(&config_path).expect("read config");
    assert!(
        stored_config.contains("mcp_servers.echo"),
        "config.toml should contain serialized table"
    );
}

#[test]
fn write_codex_live_atomic_rolls_back_auth_when_config_write_fails() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    let auth_path = cc_switch_lib::get_codex_auth_path();
    if let Some(parent) = auth_path.parent() {
        std::fs::create_dir_all(parent).expect("create codex dir");
    }
    std::fs::write(&auth_path, r#"{"OPENAI_API_KEY":"legacy"}"#).expect("seed auth");

    let config_path = cc_switch_lib::get_codex_config_path();
    std::fs::create_dir_all(&config_path).expect("create blocking directory");

    let auth = json!({ "OPENAI_API_KEY": "new-key" });
    let config_text = r#"[mcp_servers.sample]
type = "stdio"
command = "noop"
"#;

    let err = cc_switch_lib::write_codex_live_atomic(&auth, Some(config_text))
        .expect_err("config write should fail when target is directory");
    match err {
        cc_switch_lib::AppError::Io { path, .. } => {
            assert!(
                path.ends_with("config.toml"),
                "io error path should point to config.toml"
            );
        }
        cc_switch_lib::AppError::IoContext { context, .. } => {
            assert!(
                context.contains("config.toml"),
                "error context should mention config path"
            );
        }
        other => panic!("unexpected error variant: {other:?}"),
    }

    let stored = std::fs::read_to_string(&auth_path).expect("read existing auth");
    assert!(
        stored.contains("legacy"),
        "auth.json should roll back to legacy content"
    );
    assert!(
        std::fs::metadata(&config_path)
            .expect("config path metadata")
            .is_dir(),
        "config path should remain a directory after failure"
    );
}

#[test]
fn import_from_codex_adds_servers_from_mcp_servers_table() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers.echo_server]
type = "stdio"
command = "echo"
args = ["hello"]

[mcp_servers.http_server]
type = "http"
url = "https://example.com"
"#,
    )
    .expect("write codex config");

    let mut config = MultiAppConfig::default();
    let changed = cc_switch_lib::import_from_codex(&mut config).expect("import codex");
    assert!(changed >= 2, "should import both servers");

    // v3.7.0: 检查统一结构
    let servers = config
        .mcp
        .servers
        .as_ref()
        .expect("unified servers should exist");

    let echo = servers.get("echo_server").expect("echo server");
    assert!(
        echo.apps.codex,
        "Codex app should be enabled for echo_server"
    );
    let server_spec = echo.server.as_object().expect("server spec");
    assert_eq!(
        server_spec
            .get("command")
            .and_then(|v| v.as_str())
            .unwrap_or(""),
        "echo"
    );

    let http = servers.get("http_server").expect("http server");
    assert!(
        http.apps.codex,
        "Codex app should be enabled for http_server"
    );
    let http_spec = http.server.as_object().expect("http spec");
    assert_eq!(
        http_spec.get("url").and_then(|v| v.as_str()).unwrap_or(""),
        "https://example.com"
    );
}

#[test]
fn read_codex_live_mcp_servers_map_parses_supported_shapes() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers.echo_server]
type = "stdio"
command = "echo"
args = ["hello", "world"]
cwd = "/tmp/project"

[mcp_servers.echo_server.env]
API_KEY = "secret"
EMPTY = ""

[mcp_servers.http_server]
url = "https://example.com/mcp"

[mcp_servers.http_server.http_headers]
Authorization = "Bearer token"

[mcp.servers.legacy_sse]
type = "sse"
url = "https://legacy.example.com/sse"

[mcp.servers.legacy_sse.headers]
X_Legacy = "yes"
"#,
    )
    .expect("write codex config");

    let servers =
        cc_switch_lib::read_codex_live_mcp_servers_map().expect("read codex live MCP servers");

    let echo = servers.get("echo_server").expect("echo server");
    assert_eq!(echo["type"], "stdio");
    assert_eq!(echo["command"], "echo");
    assert_eq!(echo["args"], json!(["hello", "world"]));
    assert_eq!(echo["cwd"], "/tmp/project");
    assert_eq!(echo["env"]["API_KEY"], "secret");
    assert_eq!(echo["env"]["EMPTY"], "");

    let http = servers.get("http_server").expect("http server");
    assert_eq!(
        http["type"], "http",
        "URL-only Codex MCP entries should normalize to http"
    );
    assert_eq!(http["url"], "https://example.com/mcp");
    assert_eq!(http["headers"]["Authorization"], "Bearer token");

    let legacy = servers.get("legacy_sse").expect("legacy server");
    assert_eq!(legacy["type"], "sse");
    assert_eq!(legacy["url"], "https://legacy.example.com/sse");
    assert_eq!(legacy["headers"]["X_Legacy"], "yes");
}

#[test]
fn import_from_codex_infers_http_when_url_is_present_without_type() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers.cloudflare_api]
url = "https://mcp.cloudflare.com/mcp"

[mcp_servers.github]
url = "https://api.githubcopilot.com/mcp/"
bearer_token_env_var = "GITHUB_MCP_TOKEN"
"#,
    )
    .expect("write codex config");

    let mut config = MultiAppConfig::default();
    let changed = cc_switch_lib::import_from_codex(&mut config).expect("import codex");
    assert_eq!(changed, 2, "should import both URL-based servers");

    let servers = config
        .mcp
        .servers
        .as_ref()
        .expect("unified servers should exist");

    let cloudflare = servers
        .get("cloudflare_api")
        .expect("cloudflare server should be imported");
    assert!(
        cloudflare.apps.codex,
        "Codex app should be enabled for cloudflare_api"
    );
    assert_eq!(cloudflare.server["type"], "http");
    assert_eq!(cloudflare.server["url"], "https://mcp.cloudflare.com/mcp");

    let github = servers
        .get("github")
        .expect("github server should be imported");
    assert!(github.apps.codex, "Codex app should be enabled for github");
    assert_eq!(github.server["type"], "http");
    assert_eq!(github.server["url"], "https://api.githubcopilot.com/mcp/");
    assert_eq!(
        github.server["bearer_token_env_var"], "GITHUB_MCP_TOKEN",
        "custom Codex HTTP fields should be preserved during import"
    );
}

#[test]
fn import_from_codex_does_not_infer_http_for_malformed_explicit_type() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers.invalid_type]
type = 1
url = "https://example.invalid/mcp"

[mcp_servers.valid_remote]
url = "https://example.com/mcp"
"#,
    )
    .expect("write codex config");

    let mut config = MultiAppConfig::default();
    let changed = cc_switch_lib::import_from_codex(&mut config).expect("import codex");
    assert_eq!(changed, 1, "only the URL-only entry should be imported");

    let servers = config
        .mcp
        .servers
        .as_ref()
        .expect("unified servers should exist");

    assert!(
        !servers.contains_key("invalid_type"),
        "malformed explicit type should not be silently inferred as http"
    );

    let valid_remote = servers
        .get("valid_remote")
        .expect("URL-only entry should still be imported");
    assert_eq!(valid_remote.server["type"], "http");
    assert_eq!(valid_remote.server["url"], "https://example.com/mcp");
}

#[test]
fn import_from_codex_skips_unknown_type_without_stopping_later_entries() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers.aaa_unknown]
type = "bogus"
url = "https://example.invalid/ignored"

[mcp_servers.zzz_echo]
type = "stdio"
command = "echo"
args = ["ok"]
"#,
    )
    .expect("write codex config");

    let mut config = MultiAppConfig::default();
    let changed = cc_switch_lib::import_from_codex(&mut config).expect("import codex");
    assert_eq!(changed, 1, "invalid entries should not stop later imports");

    let servers = config
        .mcp
        .servers
        .as_ref()
        .expect("unified servers should exist");

    assert!(
        !servers.contains_key("aaa_unknown"),
        "unknown type entry should be skipped"
    );

    let echo_after = servers
        .get("zzz_echo")
        .expect("later valid entry should still be imported");
    assert_eq!(echo_after.server["type"], "stdio");
    assert_eq!(echo_after.server["command"], "echo");
}

#[test]
fn mcp_env_import_from_codex_preserves_env_table() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp_servers.echo_server]
type = "stdio"
command = "echo"

[mcp_servers.echo_server.env]
API_KEY = "secret"
PROJECT_ROOT = ""
"#,
    )
    .expect("write codex config");

    let mut config = MultiAppConfig::default();
    cc_switch_lib::import_from_codex(&mut config).expect("import codex");

    let entry = config
        .mcp
        .servers
        .as_ref()
        .expect("unified servers should exist")
        .get("echo_server")
        .expect("echo server");
    assert_eq!(entry.server["env"]["API_KEY"], "secret");
    assert_eq!(entry.server["env"]["PROJECT_ROOT"], "");
}

#[test]
fn import_from_codex_merges_into_existing_entries() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let path = cc_switch_lib::get_codex_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create codex dir");
    }
    fs::write(
        &path,
        r#"[mcp.servers.existing]
type = "stdio"
command = "echo"
"#,
    )
    .expect("write codex config");

    let mut config = MultiAppConfig::default();
    // v3.7.0: 在统一结构中创建已存在的服务器
    config.mcp.servers = Some(std::collections::HashMap::new());
    config.mcp.servers.as_mut().unwrap().insert(
        "existing".to_string(),
        cc_switch_lib::McpServer {
            id: "existing".to_string(),
            name: "existing".to_string(),
            server: json!({
                "type": "stdio",
                "command": "prev"
            }),
            apps: cc_switch_lib::McpApps {
                claude: false,
                codex: false, // 初始未启用
                gemini: false,
                opencode: false,
                openclaw: false,
                hermes: false,
            },
            description: None,
            homepage: None,
            docs: None,
            tags: Vec::new(),
        },
    );

    let changed = cc_switch_lib::import_from_codex(&mut config).expect("import codex");
    assert!(changed >= 1, "should mark change for enabled flag");

    // v3.7.0: 检查统一结构
    let entry = config
        .mcp
        .servers
        .as_ref()
        .unwrap()
        .get("existing")
        .expect("existing entry");

    // 验证 Codex 应用已启用
    assert!(entry.apps.codex, "Codex app should be enabled after import");

    // 验证现有配置被保留(server 不应被覆盖)
    let spec = entry.server.as_object().expect("server spec");
    assert_eq!(
        spec.get("command").and_then(|v| v.as_str()),
        Some("prev"),
        "existing server config should be preserved, not overwritten by import"
    );
}

#[test]
fn sync_claude_enabled_mcp_projects_to_user_config() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    // Seed an empty .claude.json so should_sync_live detects Claude as initialized
    let claude_path = cc_switch_lib::get_claude_mcp_path();
    fs::write(&claude_path, "{}").expect("seed .claude.json");

    let mut config = MultiAppConfig::default();

    config.mcp.claude.servers.insert(
        "stdio-enabled".into(),
        json!({
            "id": "stdio-enabled",
            "enabled": true,
            "server": {
                "type": "stdio",
                "command": "echo",
                "args": ["hi"],
            }
        }),
    );
    config.mcp.claude.servers.insert(
        "http-disabled".into(),
        json!({
            "id": "http-disabled",
            "enabled": false,
            "server": {
                "type": "http",
                "url": "https://example.com",
            }
        }),
    );

    cc_switch_lib::sync_enabled_to_claude(&config).expect("sync Claude MCP");

    let claude_path = cc_switch_lib::get_claude_mcp_path();
    assert!(claude_path.exists(), "claude config should exist");
    let text = fs::read_to_string(&claude_path).expect("read .claude.json");
    let value: serde_json::Value = serde_json::from_str(&text).expect("parse claude json");
    let servers = value
        .get("mcpServers")
        .and_then(|v| v.as_object())
        .expect("mcpServers map");
    assert_eq!(servers.len(), 1, "only enabled entries should be written");
    let enabled = servers.get("stdio-enabled").expect("enabled entry");
    assert_eq!(
        enabled
            .get("command")
            .and_then(|v| v.as_str())
            .unwrap_or_default(),
        "echo"
    );
    assert!(servers.get("http-disabled").is_none());
}

#[test]
fn import_from_claude_merges_into_config() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let home = ensure_test_home();
    let claude_path = home.join(".claude.json");

    fs::write(
        &claude_path,
        serde_json::to_string_pretty(&json!({
            "mcpServers": {
                "stdio-enabled": {
                    "type": "stdio",
                    "command": "echo",
                    "args": ["hello"]
                }
            }
        }))
        .unwrap(),
    )
    .expect("write claude json");

    let mut config = MultiAppConfig::default();
    // v3.7.0: 在统一结构中创建已存在的服务器
    config.mcp.servers = Some(std::collections::HashMap::new());
    config.mcp.servers.as_mut().unwrap().insert(
        "stdio-enabled".to_string(),
        cc_switch_lib::McpServer {
            id: "stdio-enabled".to_string(),
            name: "stdio-enabled".to_string(),
            server: json!({
                "type": "stdio",
                "command": "prev"
            }),
            apps: cc_switch_lib::McpApps {
                claude: false, // 初始未启用
                codex: false,
                gemini: false,
                opencode: false,
                openclaw: false,
                hermes: false,
            },
            description: None,
            homepage: None,
            docs: None,
            tags: Vec::new(),
        },
    );

    let changed = cc_switch_lib::import_from_claude(&mut config).expect("import from claude");
    assert!(changed >= 1, "should mark at least one change");

    // v3.7.0: 检查统一结构
    let entry = config
        .mcp
        .servers
        .as_ref()
        .unwrap()
        .get("stdio-enabled")
        .expect("entry exists");

    // 验证 Claude 应用已启用
    assert!(
        entry.apps.claude,
        "Claude app should be enabled after import"
    );

    // 验证现有配置被保留(server 不应被覆盖)
    let server = entry.server.as_object().expect("server obj");
    assert_eq!(
        server.get("command").and_then(|v| v.as_str()).unwrap_or(""),
        "prev",
        "existing server config should be preserved"
    );
}

#[test]
fn create_backup_skips_missing_file() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();
    let db_path = get_app_config_dir().join("cc-switch.db");

    // 未创建数据库文件时应返回空字符串,不报错
    let result = ConfigService::create_backup(&db_path, None).expect("create backup");
    assert!(
        result.is_empty(),
        "expected empty backup id when database missing"
    );
}

#[test]
fn create_backup_generates_snapshot_file() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();
    let app_config_dir = get_app_config_dir();
    let db_path = app_config_dir.join("cc-switch.db");

    // Seed DB with at least one provider so the SQL dump contains data.
    let mut config = MultiAppConfig::default();
    {
        let manager = config
            .get_manager_mut(&AppType::Claude)
            .expect("claude manager");
        manager.current = "p1".to_string();
        manager.providers.insert(
            "p1".to_string(),
            Provider::with_id(
                "p1".to_string(),
                "Test Claude".to_string(),
                json!({
                    "env": { "ANTHROPIC_AUTH_TOKEN": "test-key" }
                }),
                None,
            ),
        );
    }
    let state = state_from_config(config);
    state.save().expect("persist db");

    let backup_id = ConfigService::create_backup(&db_path, None).expect("backup success");
    assert!(
        !backup_id.is_empty(),
        "backup id should contain timestamp information"
    );

    let backup_path = app_config_dir
        .join("backups")
        .join(format!("{backup_id}.sql"));
    assert!(
        backup_path.exists(),
        "expected backup file at {}",
        backup_path.display()
    );

    let backup_content = fs::read_to_string(&backup_path).expect("read backup");
    assert!(
        backup_content.starts_with("-- CC Switch SQLite 导出"),
        "backup content should be a CC Switch SQL export"
    );
    assert!(
        backup_content.contains("p1"),
        "backup content should include seeded provider data"
    );
}

#[test]
fn create_backup_retains_only_latest_entries() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();
    let app_config_dir = get_app_config_dir();
    let db_path = app_config_dir.join("cc-switch.db");

    // Ensure DB exists so backups are created.
    let state = state_from_config(MultiAppConfig::default());
    state.save().expect("persist db");

    let backups_dir = app_config_dir.join("backups");
    fs::create_dir_all(&backups_dir).expect("create backups dir");
    for idx in 0..12 {
        let manual = backups_dir.join(format!("manual_{idx:02}.sql"));
        fs::write(&manual, format!("-- manual backup {idx}\n")).expect("seed manual backup");
    }

    std::thread::sleep(std::time::Duration::from_secs(1));

    let latest_backup_id =
        ConfigService::create_backup(&db_path, None).expect("create backup with cleanup");
    assert!(
        !latest_backup_id.is_empty(),
        "backup id should not be empty when config exists"
    );

    let entries: Vec<_> = fs::read_dir(&backups_dir)
        .expect("read backups dir")
        .filter_map(|entry| entry.ok())
        .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "sql"))
        .collect();
    assert!(
        entries.len() <= 10,
        "expected backups to be trimmed to at most 10 files, got {}",
        entries.len()
    );

    let latest_path = backups_dir.join(format!("{latest_backup_id}.sql"));
    assert!(
        latest_path.exists(),
        "latest backup {} should be preserved",
        latest_path.display()
    );

    // 进一步确认保留的条目包含一些历史文件,说明清理逻辑仅裁剪多余部分
    let manual_kept = entries
        .iter()
        .filter_map(|entry| entry.file_name().into_string().ok())
        .any(|name| name.starts_with("manual_"));
    assert!(
        manual_kept,
        "cleanup should keep part of the older backups to maintain history"
    );
}

#[test]
fn import_config_from_path_overwrites_state_and_creates_backup() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();
    let app_config_dir = get_app_config_dir();

    // Seed current DB with a provider so pre-import backup is meaningful.
    let mut config = MultiAppConfig::default();
    {
        let manager = config
            .get_manager_mut(&AppType::Claude)
            .expect("claude manager");
        manager.current = "p-old".to_string();
        manager.providers.insert(
            "p-old".to_string(),
            Provider::with_id(
                "p-old".to_string(),
                "Old Claude".to_string(),
                json!({
                    "env": { "ANTHROPIC_AUTH_TOKEN": "old-key" }
                }),
                None,
            ),
        );
    }
    let app_state = state_from_config(config);
    app_state.save().expect("persist initial db");

    // Build an import SQL file using an in-memory database.
    let import_path = app_config_dir.join("import.sql");
    let import_db = Database::memory().expect("create import db");
    let provider = Provider::with_id(
        "p-new".to_string(),
        "Test Claude".to_string(),
        json!({
            "env": { "ANTHROPIC_AUTH_TOKEN": "new-key" }
        }),
        None,
    );
    import_db
        .save_provider(AppType::Claude.as_str(), &provider)
        .expect("seed provider");
    import_db
        .set_current_provider(AppType::Claude.as_str(), "p-new")
        .expect("seed current");
    import_db
        .export_sql(&import_path)
        .expect("export import sql");

    let backup_id = ConfigService::import_config_from_path(&import_path, &app_state)
        .expect("import should succeed");
    assert!(
        !backup_id.is_empty(),
        "expected pre-import backup id when database exists"
    );

    let backup_path = app_config_dir
        .join("backups")
        .join(format!("{backup_id}.sql"));
    assert!(
        backup_path.exists(),
        "backup file should exist at {}",
        backup_path.display()
    );

    let current = app_state
        .db
        .get_current_provider(AppType::Claude.as_str())
        .expect("read current provider from db");
    assert_eq!(
        current.as_deref(),
        Some("p-new"),
        "db should be replaced by imported SQL"
    );

    let cfg = app_state
        .config
        .read()
        .expect("read refreshed config snapshot");
    let manager = cfg.get_manager(&AppType::Claude).expect("claude manager");
    assert_eq!(
        manager.current, "p-new",
        "import should refresh the in-memory config snapshot from the imported database"
    );
    assert!(
        manager.providers.contains_key("p-new"),
        "import should hydrate provider snapshots from the imported database"
    );
    assert!(
        !manager.providers.contains_key("p-old"),
        "import should drop providers that no longer exist in the imported database"
    );
}

#[test]
fn import_config_from_path_invalid_json_returns_error() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();

    let config_dir = get_app_config_dir();
    fs::create_dir_all(&config_dir).expect("create config dir");

    let invalid_path = config_dir.join("broken.sql");
    fs::write(&invalid_path, "SELECT 1;").expect("write invalid sql");

    let app_state = state_from_config(MultiAppConfig::default());

    let err = ConfigService::import_config_from_path(&invalid_path, &app_state)
        .expect_err("import should fail");
    match err {
        AppError::Localized { key, .. } => assert_eq!(key, "backup.sql.invalid_format"),
        other => panic!("expected Localized invalid SQL error, got {other:?}"),
    }
}

#[test]
fn import_config_from_path_missing_file_produces_io_error() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();

    let missing_path = Path::new("/nonexistent/import.sql");
    let app_state = state_from_config(MultiAppConfig::default());

    let err = ConfigService::import_config_from_path(missing_path, &app_state)
        .expect_err("import should fail for missing file");
    match err {
        AppError::InvalidInput(_) => {}
        other => panic!("expected invalid input error, got {other:?}"),
    }
}

#[test]
fn sync_gemini_packycode_sets_security_selected_type() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let _home = ensure_test_home();

    let mut config = MultiAppConfig::default();
    {
        let manager = config
            .get_manager_mut(&AppType::Gemini)
            .expect("gemini manager");
        manager.current = "packy-1".to_string();
        manager.providers.insert(
            "packy-1".to_string(),
            Provider::with_id(
                "packy-1".to_string(),
                "PackyCode".to_string(),
                json!({
                    "env": {
                        "GEMINI_API_KEY": "pk-key",
                        "GOOGLE_GEMINI_BASE_URL": "https://api-slb.packyapi.com"
                    }
                }),
                Some("https://www.packyapi.com".to_string()),
            ),
        );
    }

    ConfigService::sync_current_providers_to_live(&mut config)
        .expect("syncing gemini live should succeed");

    let settings_path = get_app_config_dir().join("settings.json");
    assert!(
        settings_path.exists(),
        "settings.json should exist at {}",
        settings_path.display()
    );

    let raw = std::fs::read_to_string(&settings_path).expect("read settings.json");
    let value: serde_json::Value = serde_json::from_str(&raw).expect("parse settings.json");
    assert_eq!(
        value
            .pointer("/security/auth/selectedType")
            .and_then(|v| v.as_str()),
        Some("gemini-api-key"),
        "syncing PackyCode Gemini should enforce security.auth.selectedType"
    );
}

#[test]
fn sync_gemini_google_official_sets_oauth_security() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let home = ensure_test_home();

    let mut config = MultiAppConfig::default();
    {
        let manager = config
            .get_manager_mut(&AppType::Gemini)
            .expect("gemini manager");
        manager.current = "google-official".to_string();
        let mut provider = Provider::with_id(
            "google-official".to_string(),
            "Google".to_string(),
            json!({
                "env": {}
            }),
            Some("https://ai.google.dev".to_string()),
        );
        provider.meta = Some(ProviderMeta {
            partner_promotion_key: Some("google-official".to_string()),
            ..ProviderMeta::default()
        });
        manager
            .providers
            .insert("google-official".to_string(), provider);
    }

    ConfigService::sync_current_providers_to_live(&mut config)
        .expect("syncing google official gemini should succeed");

    let cc_settings = get_app_config_dir().join("settings.json");
    assert!(
        cc_settings.exists(),
        "app settings should exist at {}",
        cc_settings.display()
    );
    let cc_raw = std::fs::read_to_string(&cc_settings).expect("read app settings");
    let cc_value: serde_json::Value = serde_json::from_str(&cc_raw).expect("parse app settings");
    assert_eq!(
        cc_value
            .pointer("/security/auth/selectedType")
            .and_then(|v| v.as_str()),
        Some("oauth-personal"),
        "syncing Google official should set oauth-personal in app settings"
    );

    let gemini_settings = home.join(".gemini").join("settings.json");
    assert!(
        gemini_settings.exists(),
        "Gemini settings should exist at {}",
        gemini_settings.display()
    );
    let gemini_raw = std::fs::read_to_string(&gemini_settings).expect("read gemini settings");
    let gemini_value: serde_json::Value =
        serde_json::from_str(&gemini_raw).expect("parse gemini settings json");
    assert_eq!(
        gemini_value
            .pointer("/security/auth/selectedType")
            .and_then(|v| v.as_str()),
        Some("oauth-personal"),
        "Gemini settings should also record oauth-personal"
    );
}

#[test]
fn import_openclaw_live_config_preserves_unrelated_root_sections_and_source_text() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let home = ensure_test_home();

    let openclaw_dir = home.join(".openclaw");
    fs::create_dir_all(&openclaw_dir).expect("create openclaw dir");
    let openclaw_path = openclaw_dir.join("openclaw.json");
    let source = r#"// preserve-me
{
  models: {
    mode: 'merge',
    providers: {
      openai: {
        name: 'OpenAI Compatible',
        apiKey: 'sk-openai',
        baseUrl: 'https://api.example.com/v1',
        models: [
          {
            id: 'gpt-4.1',
            name: 'OpenAI Compatible',
          },
        ],
      },
    },
  },
  agents: {
    defaults: {
      model: {
        primary: 'openai/gpt-4.1',
      },
    },
  },
  tools: {
    profile: 'coding',
  },
}
"#;
    fs::write(&openclaw_path, source).expect("seed openclaw json5 config");

    let state = state_from_config(MultiAppConfig::default());

    ProviderService::import_openclaw_providers_from_live(&state)
        .expect("import openclaw live config should succeed");

    let after = fs::read_to_string(&openclaw_path).expect("read openclaw file after import");
    assert_eq!(
        after, source,
        "import should not rewrite unrelated OpenClaw document sections or formatting"
    );

    let openai_provider = state
        .db
        .get_provider_by_id("openai", "openclaw")
        .expect("query openai provider from db")
        .expect("openai provider should be imported");
    assert_eq!(
        openai_provider
            .settings_config
            .get("apiKey")
            .and_then(|v| v.as_str()),
        Some("sk-openai"),
    );
}

#[test]
fn import_openclaw_live_config_skips_modeless_default_provider_without_rewriting_source_text() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let home = ensure_test_home();

    let openclaw_dir = home.join(".openclaw");
    fs::create_dir_all(&openclaw_dir).expect("create openclaw dir");
    let openclaw_path = openclaw_dir.join("openclaw.json");
    let source = r#"// preserve-me-too
{
  models: {
    mode: 'merge',
    providers: {
      empty: {
        apiKey: 'sk-empty',
        baseUrl: 'https://empty.example.com/v1',
        models: [],
      },
      openai: {
        apiKey: 'sk-openai',
        baseUrl: 'https://api.example.com/v1',
        models: [
          {
            id: 'gpt-4.1',
            name: 'OpenAI Compatible',
          },
        ],
      },
    },
  },
  agents: {
    defaults: {
      model: {
        primary: 'empty/gpt-4.1',
        fallbacks: ['openai/gpt-4.1'],
      },
    },
  },
  tools: {
    profile: 'coding',
  },
}
"#;
    fs::write(&openclaw_path, source).expect("seed openclaw json5 config");

    let state = state_from_config(MultiAppConfig::default());

    ProviderService::import_openclaw_providers_from_live(&state)
        .expect("import openclaw live config should succeed");

    let after = fs::read_to_string(&openclaw_path).expect("read openclaw file after import");
    assert_eq!(
        after, source,
        "import should not rewrite the OpenClaw source document while skipping modeless providers"
    );

    // empty provider has no models, so it should be skipped by import
    let empty_provider = state
        .db
        .get_provider_by_id("empty", "openclaw")
        .expect("query empty provider from db");
    assert!(
        empty_provider.is_none(),
        "modeless provider should not be imported"
    );

    // openai provider has models, so it should be imported
    let openai_provider = state
        .db
        .get_provider_by_id("openai", "openclaw")
        .expect("query openai provider from db")
        .expect("openai provider should be imported");
    assert_eq!(
        openai_provider
            .settings_config
            .get("apiKey")
            .and_then(|v| v.as_str()),
        Some("sk-openai"),
    );

    let all_ids = state
        .db
        .get_provider_ids("openclaw")
        .expect("get all openclaw provider ids");
    assert_eq!(all_ids.len(), 1, "only openai should be imported");
}

#[test]
fn export_config_to_file_writes_target_path() {
    let _guard = lock_test_mutex();
    reset_test_fs();
    let home = ensure_test_home();

    // Seed DB with data so export includes at least one known id.
    let mut config = MultiAppConfig::default();
    {
        let manager = config
            .get_manager_mut(&AppType::Claude)
            .expect("claude manager");
        manager.current = "p1".to_string();
        manager.providers.insert(
            "p1".to_string(),
            Provider::with_id(
                "p1".to_string(),
                "Test Claude".to_string(),
                json!({
                    "env": { "ANTHROPIC_AUTH_TOKEN": "test-key" }
                }),
                None,
            ),
        );
    }
    let state = state_from_config(config);
    state.save().expect("persist db");

    let export_path = home.join("exported-config.sql");
    if export_path.exists() {
        fs::remove_file(&export_path).expect("cleanup export target");
    }

    let result = block_on(cc_switch_lib::export_config_to_file(
        export_path.to_string_lossy().to_string(),
    ))
    .expect("export should succeed");
    assert_eq!(result.get("success").and_then(|v| v.as_bool()), Some(true));

    let exported = fs::read_to_string(&export_path).expect("read exported file");
    assert!(
        exported.starts_with("-- CC Switch SQLite 导出"),
        "exported file should be a CC Switch SQL export"
    );
    assert!(
        exported.contains("p1"),
        "exported SQL should contain seeded provider data"
    );
}

#[test]
fn export_config_to_file_returns_error_when_path_invalid() {
    let _guard = lock_test_mutex();
    reset_test_fs();

    let err = block_on(cc_switch_lib::export_config_to_file(String::new()))
        .expect_err("export should fail");
    assert!(
        err.contains("Invalid export path"),
        "expected invalid export path message, got {err}"
    );
}