oxi-cli 0.39.0

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

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

/// Current settings format version.
///
/// Version history:
/// - 4: dynamic_models field + last_used_model/provider split
/// - 5: output_languages field (TUI-only language policy)
/// - 6: language_policy_enabled field (master toggle, default OFF)
/// - 7: edit_format field (Hashline/StrReplace, default StrReplace)
const SETTINGS_VERSION: u32 = 7;

/// Known output channels for the TUI language policy.
///
/// `(key, prompt_label)` — `prompt_label` is the human-readable
/// phrase used when building the system prompt directive.
///
/// New channels can be added by the user in `settings.toml`; the
/// `KNOWN_CHANNELS` list is only the validation whitelist and the
/// prompt-rendering label table. The runtime policy generator
/// (`crate::prompt::system_prompt::language_directive`) walks this
/// list to render each non-auto channel.
pub const KNOWN_CHANNELS: &[(&str, &str)] = &[
    ("response", "Your conversational responses to the user"),
    (
        "code_comment",
        "Code comments you write (//, /* */, #, etc.)",
    ),
    (
        "documentation",
        "Documentation (markdown files, README, AGENTS.md, doc comments)",
    ),
    ("commit_message", "Git commit messages (subject + body)"),
];

/// Known language codes for the TUI language policy.
///
/// `(code, display_label)` — `code` is the ISO 639-1 value stored
/// in `settings.toml`; `display_label` is shown in the UI and used
/// in the rendered prompt directive.
///
/// `"auto"` is the special "match user's input language" sentinel
/// (see `crate::prompt::system_prompt::language_directive`).
/// Unknown codes are accepted at load time (with a warning) so that
/// users can add languages without code changes.
pub const KNOWN_LANGS: &[(&str, &str)] = &[
    ("auto", "Auto (match user)"),
    ("en", "English"),
    ("ko", "Korean (한국어)"),
    ("ja", "Japanese (日本語)"),
    ("zh", "Chinese (中文)"),
    ("es", "Spanish"),
    ("fr", "French"),
    ("de", "German"),
];

/// Environment variable prefix for oxi settings.
/// Keep: reserved for future env-based config loading (e.g. OXI_API_KEY).
#[allow(dead_code)]
const ENV_PREFIX: &str = "OXI_";

/// Thinking level for agent responses
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingLevel {
    /// Extended reasoning disabled (default).
    #[default]
    Off,
    /// Minimal reasoning.
    Minimal,
    /// Low reasoning.
    Low,
    /// Medium reasoning.
    Medium,
    /// High reasoning.
    High,
    /// Very high reasoning.
    XHigh,
}

/// Edit format for the edit tool.
///
/// Controls whether the system prompt instructs the model to use hashline
/// line-anchored patches or traditional str_replace. Hashline is the new
/// format ported from omp — see `docs/designs/omp-adoption/01-hashline-edit.md`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum EditFormat {
    /// Hashline line-anchored editing (default).
    #[default]
    Hashline,
    /// Traditional str_replace (legacy fallback).
    StrReplace,
}
/// A custom OpenAI-compatible provider configuration.
///
/// Custom providers are loaded from `~/.oxi/settings.toml` via `[[custom_provider]]` sections
/// and registered at runtime so that models like `minimax/minimax-m2.5` can be used directly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomProvider {
    /// Unique provider name (e.g. `"minimax"`).
    pub name: String,
    /// Base URL of the OpenAI-compatible API (e.g. `"https://api.minimax.chat/v1"`).
    pub base_url: String,
    /// Environment variable name that holds the API key (e.g. `"MINIMAX_API_KEY"`).
    pub api_key_env: String,
    /// API dialect: `"openai-completions"` or `"openai-responses"`.
    #[serde(default = "default_custom_provider_api")]
    pub api: String,
}

fn default_custom_provider_api() -> String {
    "openai-completions".to_string()
}

/// Application settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
    // ── Version (for migration) ──────────────────────────────────────
    /// Settings format version. Used for automatic migration.
    #[serde(default)]
    pub version: u32,

    // ── Core LLM settings ───────────────────────────────────────────
    /// Thinking level for agent responses
    #[serde(default = "default_thinking_level")]
    pub thinking_level: ThinkingLevel,

    /// Color theme (e.g., "default", "monokai", "dracula")
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Deprecated: use `last_used_model` instead. Kept for serde backward compat.
    #[serde(default, skip_serializing)]
    pub default_model: Option<String>,

    /// Deprecated: use `last_used_provider` instead. Kept for serde backward compat.
    #[serde(default, skip_serializing)]
    pub default_provider: Option<String>,

    /// Model selected by the user (last used = current default).
    /// Set during onboarding and updated every time the user switches model.
    #[serde(default)]
    pub last_used_model: Option<String>,

    /// Provider for the last used model.
    #[serde(default)]
    pub last_used_provider: Option<String>,

    /// Max tokens for responses
    pub max_tokens: Option<u32>,

    /// Temperature for generation (0.0–2.0)
    pub temperature: Option<f32>,

    /// Default temperature as f64 (higher precision, takes precedence over `temperature`)
    pub default_temperature: Option<f64>,

    /// Maximum tokens for generation (usize variant, takes precedence over `max_tokens`)
    pub max_response_tokens: Option<usize>,

    // ── Session settings ─────────────────────────────────────────────
    /// Session history size (entries to keep in memory)
    #[serde(default = "default_session_history_size")]
    pub session_history_size: usize,

    /// Directory for storing sessions (default: `~/.oxi/sessions`)
    pub session_dir: Option<PathBuf>,

    // ── Behaviour flags ──────────────────────────────────────────────
    /// Whether to stream responses
    #[serde(default = "default_true")]
    pub stream_responses: bool,

    /// Whether extensions are enabled
    #[serde(default = "default_true")]
    pub extensions_enabled: bool,

    /// Whether to auto-compact conversations that exceed context window
    #[serde(default = "default_true")]
    pub auto_compaction: bool,

    /// Built-in tools to disable (by name, e.g. `["web_search", "github_search"]`).
    /// All tools are enabled by default; list tools here to turn them off.
    #[serde(default)]
    pub disabled_tools: Vec<String>,

    // ── Timeouts ─────────────────────────────────────────────────────
    /// Timeout in seconds for tool execution
    #[serde(default = "default_tool_timeout")]
    pub tool_timeout_seconds: u64,

    /// Questionnaire overlay timeout in seconds. 0 = disabled (wait indefinitely).
    /// When timeout fires, auto-selects the recommended option (or first option).
    #[serde(default)]
    pub questionnaire_timeout_secs: u64,

    // ── Resource lists (managed by `oxi config`) ────────────────────
    /// List of extension paths or npm package sources to load
    #[serde(default)]
    pub extensions: Vec<String>,

    /// List of skill paths or npm package sources to load
    #[serde(default)]
    pub skills: Vec<String>,

    /// List of prompt template paths to load
    #[serde(default)]
    pub prompts: Vec<String>,

    /// List of theme paths to load
    #[serde(default)]
    pub themes: Vec<String>,

    // ── Custom OpenAI-compatible providers ──────────────────────────────
    /// Registered custom providers (loaded from `[[custom_provider]]` TOML sections).
    #[serde(default)]
    pub custom_providers: Vec<CustomProvider>,

    // ── Dynamic model cache ─────────────────────────────────────────────
    /// Cached model lists fetched from provider `/models` endpoints.
    /// Key is the provider name, value is a list of model IDs.
    /// Updated when API keys are entered in setup wizard or on demand.
    #[serde(default)]
    pub dynamic_models: HashMap<String, Vec<String>>,

    // ── Multi-provider routing ─────────────────────────────────────────
    /// Enable automatic complexity-based routing
    #[serde(default = "default_false")]
    pub enable_routing: bool,

    /// Router profile name to use (e.g., "auto", "balanced").
    #[serde(default)]
    pub router_profile: Option<String>,

    /// Prefer cost-efficient models when routing
    #[serde(default = "default_true")]
    pub prefer_cost_efficient: bool,

    /// Fallback chain: ordered list of model IDs to try on failure
    #[serde(default)]
    pub fallback_chain: Vec<String>,

    /// Whether to use provider fallback on errors (false = fail fast)
    #[serde(default = "default_true")]
    pub enable_fallback: bool,

    /// Disable automatic fallback (same as enable_fallback = false)
    #[serde(default)]
    pub disable_fallback: bool,

    /// Circuit breaker failure threshold per provider
    #[serde(default = "default_circuit_failure_threshold")]
    pub circuit_breaker_failure_threshold: u32,

    /// Circuit breaker open duration in seconds
    #[serde(default = "default_circuit_open_duration_secs")]
    pub circuit_breaker_open_duration_secs: u64,

    // ── Keybindings ────────────────────────────────────────────────────
    /// User-defined keybinding overrides.
    /// Format: `{ "ActionName": ["Ctrl+x", "Alt+y"] }`
    /// Actions are matched case-insensitively to the Action enum in oxi-tui.
    #[serde(default)]
    pub keybindings: HashMap<String, Vec<String>>,

    // ── TUI output language policy (TUI-only) ─────────────────────────
    /// Per-channel output language for the TUI agent loop.
    ///
    /// Maps a channel key (e.g. `"response"`, `"code_comment"`,
    /// `"documentation"`, `"commit_message"`) to a language code
    /// (e.g. `"en"`, `"ko"`, or `"auto"`).
    ///
    /// **Scope:** This setting is consumed exclusively by
    /// `crate::app::agent_session_runtime::build_system_prompt` (the
    /// TUI session build path). The `lib.rs` App build path used by
    /// `oxi --print` and RPC mode **does not** inject the policy,
    /// so this setting is silently ignored in non-TUI modes.
    ///
    /// **Default:** Empty map. Every channel defaults to `"auto"`
    /// (match the most recent user message language), preserving
    /// the previous behavior. Set a channel to a non-`"auto"`
    /// value to fix its output language.
    ///
    /// **Extension map:** User-defined channels beyond the four in
    /// `KNOWN_CHANNELS` are accepted (e.g. `pr_description = "en"`).
    /// Unknown channels fall back to using the raw key as the label
    /// in the rendered directive, and the model typically still
    /// understands from context.
    ///
    /// **Strong default, NOT a hard guarantee.** This setting drives
    /// a prompt-level "MUST" directive at the end of the system
    /// prompt and a `"Focus areas:"` instruction passed to the
    /// compaction summarizer. Both are prompt-level signals — the
    /// model can still occasionally violate the policy when:
    ///
    ///   - the context grows long and the directive is "lost in the
    ///     middle";
    ///   - tool output is echoed verbatim without translation;
    ///   - subagent summarization under a different framing weakens
    ///     the instruction (see `build_compaction_instruction` for
    ///     the exact framing caveat).
    ///
    /// If a 100% guarantee is required, additional layers (tool
    /// output wrapping, response post-processing) are needed — out
    /// of scope for this MVP.
    ///
    /// **Validation:** Unknown language codes are logged at warn
    /// level and kept (so users can add languages without code
    /// changes). Channel keys are not validated — see "Extension
    /// map" above.
    #[serde(default)]
    pub output_languages: HashMap<String, String>,

    // ── TUI language policy master toggle (v6) ────────────────────────
    /// Master switch for the TUI output language policy.
    ///
    /// **Default: `false` (opt-in).** Even with a non-empty
    /// `output_languages` map, the policy is **not** injected into
    /// the system prompt or compaction instruction unless this is
    /// `true`. Users must toggle it ON in the `/settings` overlay
    /// for the policy to take effect.
    ///
    /// **Why opt-in (not opt-out):** keeps the pre-feature behavior
    /// intact for users who never touch language settings, while
    /// making the feature discoverable through the overlay toggle.
    /// Users who configured `output_languages` in v5 will see their
    /// channel mappings preserved on disk, but disabled until they
    /// flip this switch.
    ///
    /// **Scope:** TUI-only. `oxi --print` and RPC mode ignore the
    /// policy regardless of this flag (see AGENTS.md pitfalls).
    #[serde(default = "default_false")]
    pub language_policy_enabled: bool,

    /// Edit format for the edit tool.
    ///
    /// `str_replace` (default): traditional find-and-replace.
    /// `hashline`: line-anchored patches with content-derived tags.
    #[serde(default)]
    pub edit_format: EditFormat,

    // ── Hindsight memory (④) ─────────────────────────────────────────
    /// Enable session-spanning memory tools (retain/recall/reflect/edit).
    /// Default: false (opt-in).
    #[serde(default = "default_false")]
    pub memory_enabled: bool,

    /// Path to the SQLite memory database. Default: `~/.oxi/memory/<project>.db`
    /// when empty.
    #[serde(default)]
    pub memory_db_path: Option<PathBuf>,

    // ── TTSR (③) ─────────────────────────────────────────────────────
    /// Enable Time-Traveling Stream Rules (stream interrupt on rule violation).
    /// Default: false (opt-in, stable-first).
    #[serde(default = "default_false")]
    pub ttsr_enabled: bool,

    /// TTSR interrupt mode. Default: "prose_only".
    #[serde(default = "default_ttsr_mode")]
    pub ttsr_interrupt_mode: String,
}

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

fn default_thinking_level() -> ThinkingLevel {
    ThinkingLevel::Medium
}

fn default_session_history_size() -> usize {
    100
}

fn default_true() -> bool {
    true
}

fn default_false() -> bool {
    false
}

fn default_ttsr_mode() -> String {
    "prose_only".to_string()
}

fn default_circuit_failure_threshold() -> u32 {
    5
}

fn default_circuit_open_duration_secs() -> u64 {
    30
}

fn default_tool_timeout() -> u64 {
    120
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            version: SETTINGS_VERSION,
            thinking_level: ThinkingLevel::Medium,
            theme: default_theme(),
            last_used_model: None,
            last_used_provider: None,
            default_model: None,
            default_provider: None,
            max_tokens: None,
            temperature: None,
            default_temperature: None,
            max_response_tokens: None,
            session_history_size: default_session_history_size(),
            session_dir: None,
            stream_responses: true,
            extensions_enabled: true,
            auto_compaction: true,
            disabled_tools: Vec::new(),
            tool_timeout_seconds: default_tool_timeout(),
            questionnaire_timeout_secs: 0,
            extensions: Vec::new(),
            skills: Vec::new(),
            prompts: Vec::new(),
            themes: Vec::new(),
            custom_providers: Vec::new(),
            dynamic_models: HashMap::new(),
            // Multi-provider routing defaults
            enable_routing: false,
            router_profile: None,
            prefer_cost_efficient: true,
            fallback_chain: Vec::new(),
            enable_fallback: true,
            disable_fallback: false,
            circuit_breaker_failure_threshold: 5,
            circuit_breaker_open_duration_secs: 30,
            keybindings: HashMap::new(),
            output_languages: HashMap::new(),
            language_policy_enabled: false,
            edit_format: EditFormat::default(),
            memory_enabled: false,
            memory_db_path: None,
            ttsr_enabled: false,
            ttsr_interrupt_mode: default_ttsr_mode(),
        }
    }
}

impl Settings {
    // ── Paths ────────────────────────────────────────────────────────

    /// Get the global settings directory path (`~/.oxi`).
    pub fn settings_dir() -> Result<PathBuf> {
        let base = dirs::home_dir().context("Cannot determine home directory")?;
        Ok(base.join(".oxi"))
    }

    /// Get the global settings TOML file path (`~/.oxi/settings.toml`).
    pub fn settings_toml_path() -> Result<PathBuf> {
        Ok(Self::settings_dir()?.join("settings.toml"))
    }

    /// Get the global settings JSON file path (`~/.oxi/settings.json`).
    pub fn settings_json_path() -> Result<PathBuf> {
        Ok(Self::settings_dir()?.join("settings.json"))
    }

    /// Get the global settings file path (JSON takes priority).
    ///
    /// Returns the path to the settings file that should be used.
    /// If both JSON and TOML exist, JSON is returned (takes priority).
    /// If only one exists, that path is returned.
    /// If neither exists, returns the JSON path by default.
    pub fn settings_path() -> Result<PathBuf> {
        let json_path = Self::settings_json_path()?;
        let toml_path = Self::settings_toml_path()?;

        if json_path.exists() && toml_path.exists() {
            // Both exist: JSON takes priority
            tracing::debug!("Both settings.json and settings.toml exist, using settings.json");
            return Ok(json_path);
        }

        if json_path.exists() {
            return Ok(json_path);
        }

        if toml_path.exists() {
            return Ok(toml_path);
        }

        // Neither exists: default to JSON
        Ok(json_path)
    }

    /// Get the effective settings file path, preferring the specified format.
    ///
    /// If `prefer_json` is true, checks JSON first; otherwise checks TOML first.
    /// Returns the first existing file, or the preferred path if neither exists.
    pub fn settings_path_with_preference(prefer_json: bool) -> Result<PathBuf> {
        let json_path = Self::settings_json_path()?;
        let toml_path = Self::settings_toml_path()?;

        let (primary, secondary) = if prefer_json {
            (&json_path, &toml_path)
        } else {
            (&toml_path, &json_path)
        };

        if primary.exists() {
            return Ok(primary.clone());
        }

        if secondary.exists() {
            return Ok(secondary.clone());
        }

        // Neither exists: return preferred path
        Ok(primary.clone())
    }

    /// Detect the settings file format from its path.
    pub fn detect_format(path: &Path) -> SettingsFormat {
        match path.extension().and_then(|e| e.to_str()) {
            Some("json") => SettingsFormat::Json,
            Some("toml") => SettingsFormat::Toml,
            _ => SettingsFormat::Json, // Default to JSON for unknown extensions
        }
    }

    /// Get the project-local settings file path.
    ///
    /// Searches for `.oxi/settings.json` first, then `.oxi/settings.toml`.
    /// Returns the first one found, or None if neither exists.
    pub fn find_project_settings(start_dir: &std::path::Path) -> Option<PathBuf> {
        let mut dir = start_dir.to_path_buf();
        loop {
            // Check JSON first (priority), then TOML
            let json_candidate = dir.join(".oxi").join("settings.json");
            if json_candidate.exists() {
                return Some(json_candidate);
            }

            let toml_candidate = dir.join(".oxi").join("settings.toml");
            if toml_candidate.exists() {
                return Some(toml_candidate);
            }

            if !dir.pop() {
                return None;
            }
        }
    }

    /// Resolve the effective session directory.
    ///
    /// Priority: `session_dir` field → `~/.oxi/sessions`.
    pub fn effective_session_dir(&self) -> Result<PathBuf> {
        if let Some(ref dir) = self.session_dir {
            return Ok(dir.clone());
        }
        Ok(Self::settings_dir()?.join("sessions"))
    }

    // ── Loading ──────────────────────────────────────────────────────

    /// Load settings, applying all layers:
    ///
    /// 1. Built-in defaults
    /// 2. Global `~/.oxi/settings.toml`
    /// 3. Project `.oxi/settings.toml`
    /// 4. Environment variable overrides
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use oxi_cli::Settings;
    ///
    /// let settings = Settings::load().expect("Failed to load settings");
    /// println!("Using model: {}", settings.effective_model(None));
    /// ```
    pub fn load() -> Result<Self> {
        Self::load_from_cwd()
    }

    /// Load settings with an explicit working directory for project config discovery.
    pub fn load_from(dir: &std::path::Path) -> Result<Self> {
        // 1. Start from defaults
        let mut settings = Settings::default();

        // 2. Layer global config
        if let Ok(global_path) = Self::settings_path()
            && global_path.exists()
        {
            settings = Self::layer_file(&settings, &global_path)?;
        }

        // 3. Layer project config
        if let Some(project_path) = Self::find_project_settings(dir) {
            settings = Self::layer_file(&settings, &project_path)?;
        }

        // 4. Layer environment variables
        settings.apply_env();

        // 5. Run migration if needed
        settings = Self::migrate(settings)?;

        // 6. Validate TUI-specific language policy
        settings.validate_output_languages();

        Ok(settings)
    }

    /// Warn on unknown `output_languages` language codes. Channel
    /// keys are **not** validated: any channel (known or user-defined)
    /// is accepted so users can add new channels in `settings.toml`
    /// without code changes. `KNOWN_CHANNELS` provides a label table
    /// for the prompt directive; unknown channels fall back to using
    /// the raw key as the label.
    fn validate_output_languages(&mut self) {
        if self.output_languages.is_empty() {
            return;
        }
        let known_langs: std::collections::HashSet<&str> =
            KNOWN_LANGS.iter().map(|(k, _)| *k).collect();

        for (channel, lang) in &self.output_languages {
            if !known_langs.contains(lang.as_str()) {
                tracing::warn!(
                    "Unknown output_languages language code '{}' for channel '{}'. \
                     Keeping as-is (the model will likely understand).",
                    lang,
                    channel
                );
            }
        }
    }

    /// Convenience: load from current working directory.
    pub fn load_from_cwd() -> Result<Self> {
        let cwd = env::current_dir().context("Cannot determine current directory")?;
        Self::load_from(&cwd)
    }

    /// Parse a settings file (TOML or JSON) and overlay its values onto `base`.
    ///
    /// The format is auto-detected based on the file extension.
    /// Fields present in the file replace those in `base`; absent fields
    /// are left untouched.
    fn layer_file(base: &Settings, path: &std::path::Path) -> Result<Settings> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read settings from {}", path.display()))?;

        let format = Self::detect_format(path);
        let overlay: serde_json::Value = match format {
            SettingsFormat::Toml => {
                let toml_value: toml::Value = toml::from_str(&content).with_context(|| {
                    format!("Failed to parse TOML settings from {}", path.display())
                })?;
                // Convert TOML to JSON Value for uniform merging
                toml_value_to_json(toml_value)
            }
            SettingsFormat::Json => serde_json::from_str(&content).with_context(|| {
                format!("Failed to parse JSON settings from {}", path.display())
            })?,
        };

        // Re-serialize the base to JSON, merge with the overlay, then
        // deserialize back. This gives correct "only override what's
        // present" semantics.
        let base_json =
            serde_json::to_value(base).context("Failed to serialize base settings for merge")?;

        let merged = merge_json_values(base_json, overlay);
        let result: Settings =
            serde_json::from_value(merged).context("Failed to deserialize merged settings")?;

        Ok(result)
    }

    // ── Environment variables ────────────────────────────────────────

    /// Apply environment variable overrides in-place.
    ///
    /// DEPRECATED: Environment variable overrides are being phased out in favor
    /// of file-based configuration (`~/.oxi/settings.toml`). This method is
    /// kept for CI/CD compatibility but should not be relied upon for local
    /// development. Use `oxi config set` or `oxi setup` instead.
    ///
    /// Supported variables (CI/CD only):
    ///
    /// | Env var                    | Setting                |
    /// |---------------------------|------------------------|
    /// | `OXI_MODEL`               | `default_model`        |
    /// | `OXI_PROVIDER`            | `default_provider`     |
    /// | `OXI_THINKING`            | `thinking_level`       |
    /// | `OXI_THEME`               | `theme`                |
    /// | `OXI_MAX_TOKENS`          | `max_tokens`           |
    /// | `OXI_TEMPERATURE`         | `default_temperature`  |
    /// | `OXI_SESSION_DIR`         | `session_dir`          |
    /// | `OXI_STREAM`              | `stream_responses`     |
    /// | `OXI_EXTENSIONS_ENABLED`  | `extensions_enabled`   |
    /// | `OXI_AUTO_COMPACTION`     | `auto_compaction`      |
    /// | `OXI_TOOL_TIMEOUT`        | `tool_timeout_seconds` |
    /// | `OXI_DISABLED_TOOLS`      | `disabled_tools`       |
    #[allow(dead_code)]
    pub fn apply_env(&mut self) {
        // No-op: environment variable overrides are disabled.
        // All configuration should come from settings.toml / settings.json.
        // This method is kept for backward compatibility but does nothing.
    }

    /// Build a `Settings` instance from **only** environment variables
    /// (all other fields stay at defaults).
    ///
    /// DEPRECATED: Returns defaults since env overrides are disabled.
    /// Use `Settings::load()` to load from settings.toml instead.
    #[allow(dead_code)]
    pub fn from_env() -> Self {
        Self::default()
    }

    // ── Persistence ──────────────────────────────────────────────────

    /// Save settings to the global config file.
    ///
    /// Uses the format of the existing file if present, otherwise saves as JSON.
    /// Preserves backward compatibility with existing TOML files.
    pub fn save(&self) -> Result<()> {
        let dir = Self::settings_dir()?;
        let path = Self::settings_path()?;

        if !dir.exists() {
            fs::create_dir_all(&dir).with_context(|| {
                format!("Failed to create settings directory {}", dir.display())
            })?;
        }

        let format = Self::detect_format(&path);
        let content = Self::serialize_for_format(self, format)?;

        // Atomic write: write to temp file first, then rename
        let tmp_path = path.with_extension("tmp");
        fs::write(&tmp_path, &content)
            .with_context(|| format!("Failed to write settings to {}", tmp_path.display()))?;
        fs::rename(&tmp_path, &path)
            .with_context(|| format!("Failed to rename settings to {}", path.display()))?;

        Ok(())
    }

    /// Save settings to a specific path, using the format determined by the file extension.
    pub fn save_to(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent()
            && !parent.exists()
        {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory {}", parent.display()))?;
        }

        let format = Self::detect_format(path);
        let content = Self::serialize_for_format(self, format)?;

        // Atomic write
        let tmp_path = path.with_extension("tmp");
        fs::write(&tmp_path, &content)
            .with_context(|| format!("Failed to write settings to {}", tmp_path.display()))?;
        fs::rename(&tmp_path, path)
            .with_context(|| format!("Failed to rename settings to {}", path.display()))?;

        Ok(())
    }

    /// Save settings to the project-local config file.
    ///
    /// Uses the format of the existing file if present, otherwise saves as JSON.
    pub fn save_project(&self, project_dir: &std::path::Path) -> Result<()> {
        let dir = project_dir.join(".oxi");

        if !dir.exists() {
            fs::create_dir_all(&dir).with_context(|| {
                format!(
                    "Failed to create project settings directory {}",
                    dir.display()
                )
            })?;
        }

        // Check if a settings file already exists in project
        let json_path = dir.join("settings.json");
        let toml_path = dir.join("settings.toml");

        let path = if json_path.exists() {
            &json_path
        } else if toml_path.exists() {
            &toml_path
        } else {
            // Default to JSON for new files
            &json_path
        };

        let format = Self::detect_format(path);
        let content = Self::serialize_for_format(self, format)?;

        // Atomic write
        let tmp_path = path.with_extension("tmp");
        fs::write(&tmp_path, &content)
            .with_context(|| format!("Failed to write settings to {}", tmp_path.display()))?;
        fs::rename(&tmp_path, path)
            .with_context(|| format!("Failed to rename settings to {}", path.display()))?;

        Ok(())
    }

    /// Serialize settings to a string in the specified format.
    pub fn serialize_for_format(settings: &Settings, format: SettingsFormat) -> Result<String> {
        match format {
            SettingsFormat::Toml => {
                toml::to_string_pretty(settings).context("Failed to serialize settings to TOML")
            }
            SettingsFormat::Json => serde_json::to_string_pretty(settings)
                .context("Failed to serialize settings to JSON"),
        }
    }

    /// Parse settings from a string in the specified format.
    pub fn parse_from_str(content: &str, format: SettingsFormat) -> Result<Settings> {
        match format {
            SettingsFormat::Toml => {
                toml::from_str(content).context("Failed to parse TOML settings")
            }
            SettingsFormat::Json => {
                serde_json::from_str(content).context("Failed to parse JSON settings")
            }
        }
    }

    // ── CLI overrides ────────────────────────────────────────────────

    /// Merge with CLI arguments (CLI takes precedence).
    ///
    /// # Arguments
    ///
    /// * `model` — CLI-specified model override
    /// * `provider` — CLI-specified provider override
    /// * `enable_routing` — CLI-specified enable_routing override
    /// * `prefer_cost_efficient` — CLI-specified prefer_cost_efficient override
    /// * `fallback_chain` — CLI-specified fallback chain override
    /// * `disable_fallback` — CLI-specified disable_fallback override
    pub fn merge_cli(
        &mut self,
        model: Option<String>,
        provider: Option<String>,
        enable_routing: Option<bool>,
        prefer_cost_efficient: Option<bool>,
        fallback_chain: Option<Vec<String>>,
        disable_fallback: Option<bool>,
    ) {
        if let Some(m) = model {
            self.last_used_model = Some(m);
        }
        if let Some(p) = provider {
            self.last_used_provider = Some(p);
        }
        if let Some(r) = enable_routing {
            self.enable_routing = r;
        }
        if let Some(p) = prefer_cost_efficient {
            self.prefer_cost_efficient = p;
        }
        if let Some(fc) = fallback_chain
            && !fc.is_empty()
        {
            self.fallback_chain = fc;
        }
        if let Some(df) = disable_fallback {
            self.disable_fallback = df;
            // If disable_fallback is true, disable fallback
            if df {
                self.enable_fallback = false;
            }
        }
    }

    /// Get the effective model ID (provider/model format).
    /// Returns None if no model is configured.
    pub fn effective_model(&self, cli_model: Option<&str>) -> Option<String> {
        cli_model.map(String::from).or_else(|| {
            // Reconstruct full model ID from separate fields.
            // Handles both cases:
            //   - last_used_model = "anthropic/claude-sonnet-4" (full ID, stored by save_last_used)
            //   - last_used_model = "claude-sonnet-4" + last_used_provider = "anthropic" (split)
            let model = self.last_used_model.as_ref()?;
            if model.contains('/') {
                // Already a full model ID
                Some(model.clone())
            } else if let Some(ref provider) = self.last_used_provider {
                // Reconstruct from separate fields
                Some(format!("{}/{}", provider, model))
            } else {
                Some(model.clone())
            }
        })
    }

    /// Get the effective provider.
    /// Returns None if no provider is configured.
    pub fn effective_provider(&self, cli_provider: Option<&str>) -> Option<String> {
        cli_provider
            .map(String::from)
            .or_else(|| self.last_used_provider.clone())
    }

    /// Get the effective temperature, preferring `default_temperature` (f64)
    /// over `temperature` (f32), falling back to `None`.
    pub fn effective_temperature(&self) -> Option<f64> {
        self.default_temperature
            .or(self.temperature.map(|t| t as f64))
    }

    /// Get the effective max tokens, preferring `max_response_tokens` (usize)
    /// over `max_tokens` (u32), falling back to `None`.
    pub fn effective_max_tokens(&self) -> Option<usize> {
        self.max_response_tokens
            .or(self.max_tokens.map(|t| t as usize))
    }

    /// Get the configured router profile name.
    pub fn router_profile(&self) -> Option<&str> {
        self.router_profile.as_deref()
    }

    // ── Theme persistence ─────────────────────────────────────────────

    /// Save the last used model/provider and persist to disk.
    ///
    /// Splits the model_id on first `/` to store provider and model separately.
    pub fn save_last_used(model_id: &str) {
        if let Ok(mut settings) = Self::load() {
            if let Some((provider, model)) = model_id.split_once('/') {
                settings.last_used_provider = Some(provider.to_string());
                settings.last_used_model = Some(model.to_string());
            } else {
                settings.last_used_model = Some(model_id.to_string());
            }
            let _ = settings.save();
        }
    }

    /// Save the current theme to settings and persist to disk.
    pub fn save_theme(&mut self, name: &str) -> Result<()> {
        self.theme = name.to_string();
        self.save()
    }

    /// Get the theme name from settings, returning a default if not set.
    pub fn get_theme_name(&self) -> String {
        if self.theme.is_empty() || self.theme == "default" {
            "oxi_dark".to_string()
        } else {
            self.theme.clone()
        }
    }

    // ── Migration ────────────────────────────────────────────────────

    /// Migrate settings from an older format version to the current one.
    ///
    /// Currently handles:
    /// - Version 0 → Version 6 (multi-step)
    /// - Version 1 → Version 6 (multi-step)
    /// - Version 2 → Version 6 (multi-step)
    /// - Version 3 → Version 4 (default_model → last_used_model)
    /// - Version 4 → Version 5 (output_languages field added — no
    ///   value migration, serde default fills with empty map)
    /// - Version 5 → Version 6 (language_policy_enabled field added —
    ///   defaults to false via `#[serde(default = "default_false")]`)
    fn migrate(settings: Settings) -> Result<Settings> {
        let mut settings = settings;

        match settings.version {
            SETTINGS_VERSION => {
                // Already current — nothing to do.
            }
            0 => {
                // Version 0 = pre-versioning config.
                // Add any defaults that were introduced in version 1.
                if settings.tool_timeout_seconds == 0 {
                    settings.tool_timeout_seconds = default_tool_timeout();
                }
                settings.version = SETTINGS_VERSION;

                tracing::info!("Migrated settings from version 0 to {}", SETTINGS_VERSION);
            }
            1 | 2 => {
                // Version 1/2 → 6: dynamic_models field added + model/provider split.
                // The v3 → v4 default_model → last_used_model split doesn't apply
                // here (no default_model in v1/v2). `#[serde(default)]` fills
                // output_languages (empty) and language_policy_enabled (false).
                settings.version = SETTINGS_VERSION;
                tracing::info!(
                    "Migrated settings from version {} to {} (dynamic_models + output_languages + language_policy_enabled defaults applied)",
                    settings.version,
                    SETTINGS_VERSION
                );
            }
            3 => {
                // Version 3 → 4 step happens inline: migrate default_model → last_used_model.
                if let Some(model) = settings.default_model.take() {
                    if let Some((provider, model_name)) = model.split_once('/') {
                        settings.last_used_provider = Some(provider.to_string());
                        settings.last_used_model = Some(model_name.to_string());
                    } else {
                        settings.last_used_model = Some(model);
                    }
                }
                // Then collapse to v6: output_languages + language_policy_enabled default.
                settings.version = SETTINGS_VERSION;
                tracing::info!(
                    "Migrated settings from version 3 to {} (default_model → last_used_model; output_languages + language_policy_enabled defaults)",
                    SETTINGS_VERSION
                );
            }
            4 => {
                // Version 4 → 5 (output_languages field added) collapses to v6.
                // No value migration needed — `#[serde(default)]` fills the
                // missing fields with empty map + language_policy_enabled = false.
                settings.version = SETTINGS_VERSION;
                tracing::info!(
                    "Migrated settings from version 4 to {} (added output_languages + language_policy_enabled, both defaulted to off)",
                    SETTINGS_VERSION
                );
            }
            5 => {
                // Version 5 → 6: language_policy_enabled field added.
                // `#[serde(default = "default_false")]` fills with false (opt-in).
                // Existing v5 users with output_languages configured will see
                // their channel mappings preserved but disabled until they
                // toggle the master switch ON in /settings.
                settings.version = SETTINGS_VERSION;
                tracing::info!(
                    "Migrated settings from version 5 to {} (added language_policy_enabled, defaulting to OFF — toggle ON in /settings to activate existing channels)",
                    SETTINGS_VERSION
                );
            }
            6 => {
                // Version 6 → 7: edit_format field added.
                // `#[serde(default)]` fills with EditFormat::StrReplace (default).
                settings.version = SETTINGS_VERSION;
                tracing::info!(
                    "Migrated settings from version 6 to {} (added edit_format, defaulting to str_replace)",
                    SETTINGS_VERSION
                );
            }
            v if v > SETTINGS_VERSION => {
                // Future version — we don't know how to downgrade.
                anyhow::bail!(
                    "Settings version {} is newer than supported version {}. \
                     Please update oxi.",
                    v,
                    SETTINGS_VERSION
                );
            }
            v => {
                // Unknown old version — best-effort migration.
                tracing::warn!(
                    "Unknown settings version {}, attempting migration to {}",
                    v,
                    SETTINGS_VERSION
                );
                settings.version = SETTINGS_VERSION;
            }
        }

        Ok(settings)
    }
}

// ── Settings format detection ──────────────────────────────────────

/// Supported settings file formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SettingsFormat {
    /// JSON format.
    #[default]
    Json,
    /// TOML format.
    Toml,
}

impl SettingsFormat {
    /// Get the file extension for this format.
    pub fn extension(&self) -> &'static str {
        match self {
            SettingsFormat::Json => "json",
            SettingsFormat::Toml => "toml",
        }
    }
}

// ── JSON/TOML conversion helpers ────────────────────────────────────

/// Convert a TOML Value to a serde_json::Value.
fn toml_value_to_json(toml: toml::Value) -> serde_json::Value {
    match toml {
        toml::Value::String(s) => serde_json::Value::String(s),
        toml::Value::Integer(i) => serde_json::Value::Number(i.into()),
        toml::Value::Float(f) => serde_json::Number::from_f64(f)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        toml::Value::Boolean(b) => serde_json::Value::Bool(b),
        toml::Value::Datetime(dt) => serde_json::Value::String(dt.to_string()),
        toml::Value::Array(arr) => {
            serde_json::Value::Array(arr.into_iter().map(toml_value_to_json).collect())
        }
        toml::Value::Table(table) => {
            let obj = table
                .into_iter()
                .map(|(k, v)| (k, toml_value_to_json(v)))
                .collect();
            serde_json::Value::Object(obj)
        }
    }
}

/// Deep merge two JSON values. The second value overrides the first.
fn merge_json_values(base: serde_json::Value, override_: serde_json::Value) -> serde_json::Value {
    match (base, override_) {
        // If either is not an object, the override wins
        (serde_json::Value::Object(base_map), serde_json::Value::Object(override_map)) => {
            let mut result = base_map;
            for (key, override_value) in override_map {
                let base_value = result.remove(&key);
                let merged = match base_value {
                    Some(base_v) => merge_json_values(base_v, override_value),
                    None => override_value,
                };
                result.insert(key, merged);
            }
            serde_json::Value::Object(result)
        }
        // Override wins for non-objects
        (_, override_) => override_,
    }
}

/// Parse a thinking level from a string.
pub fn parse_thinking_level(s: &str) -> Option<ThinkingLevel> {
    match s.to_lowercase().as_str() {
        "off" | "none" => Some(ThinkingLevel::Off),
        "minimal" => Some(ThinkingLevel::Minimal),
        "low" => Some(ThinkingLevel::Low),
        "medium" | "standard" => Some(ThinkingLevel::Medium),
        "high" | "thorough" => Some(ThinkingLevel::High),
        "xhigh" => Some(ThinkingLevel::XHigh),
        _ => None,
    }
}

/// Parse a boolean-like string (`"true"`, `"false"`, `"1"`, `"0"`, `"yes"`, `"no"`).
#[allow(dead_code)]
fn parse_boolish(s: &str) -> Result<bool> {
    match s.to_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Ok(true),
        "false" | "0" | "no" | "off" => Ok(false),
        _ => anyhow::bail!("Cannot parse '{}' as boolean", s),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write as IoWrite;
    use std::sync::Mutex;

    /// Global lock to serialize all tests that manipulate process-wide env vars.
    #[allow(dead_code)] // held implicitly via guard pattern; not all tests acquire it
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    /// RAII guard that removes listed env vars on creation and restores them on drop.
    /// This prevents parallel test races where one test sets an env var that leaks into another.
    struct EnvGuard {
        saved: Vec<(String, Option<String>)>,
    }

    impl EnvGuard {
        fn new(vars: &[&str]) -> Self {
            let saved = vars
                .iter()
                .map(|&name| {
                    let old = env::var(name).ok();
                    // SAFETY: test-only; the ENV_LOCK mutex serializes access.
                    unsafe { env::remove_var(name) };
                    (name.to_string(), old)
                })
                .collect();
            Self { saved }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (name, old) in self.saved.drain(..) {
                match old {
                    // SAFETY: test-only; the ENV_LOCK mutex serializes access.
                    Some(val) => unsafe { env::set_var(&name, val) },
                    None => unsafe { env::remove_var(&name) },
                }
            }
        }
    }

    // ── Struct tests ─────────────────────────────────────────────────

    #[test]
    fn test_default_settings() {
        let settings = Settings::default();
        assert_eq!(settings.version, SETTINGS_VERSION);
        assert_eq!(settings.thinking_level, ThinkingLevel::Medium);
        assert_eq!(settings.theme, "default");
        assert!(settings.last_used_model.is_none());
        assert!(settings.last_used_provider.is_none());
        assert!(settings.extensions_enabled);
        assert!(settings.auto_compaction);
        assert_eq!(settings.tool_timeout_seconds, 120);
        assert!(settings.stream_responses);
    }

    #[test]
    fn test_merge_cli() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("gpt-4o".to_string());

        settings.merge_cli(Some("claude".to_string()), None, None, None, None, None);
        assert_eq!(settings.last_used_model, Some("claude".to_string()));

        settings.merge_cli(None, Some("google".to_string()), None, None, None, None);
        assert_eq!(settings.last_used_provider, Some("google".to_string()));

        // Test routing flags
        settings.merge_cli(
            None,
            None,
            Some(true),
            Some(false),
            Some(vec!["openai/gpt-4o".to_string()]),
            Some(false),
        );
        assert!(settings.enable_routing);
        assert!(!settings.prefer_cost_efficient);
        assert_eq!(settings.fallback_chain, vec!["openai/gpt-4o"]);
        assert!(!settings.disable_fallback);

        // Test disable_fallback sets enable_fallback to false
        let mut settings2 = Settings::default();
        settings2.merge_cli(None, None, None, None, None, Some(true));
        assert!(settings2.disable_fallback);
        assert!(!settings2.enable_fallback);
    }

    // ── Layered loading ──────────────────────────────────────────────

    #[test]
    fn test_layer_file_overrides() {
        let base = Settings::default();

        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        let toml_content = r#"
last_used_model = "openai/gpt-4o"
theme = "dracula"
"#;
        tmp.as_file().write_all(toml_content.as_bytes()).unwrap();

        let merged = Settings::layer_file(&base, tmp.path()).unwrap();
        assert_eq!(merged.last_used_model, Some("openai/gpt-4o".to_string()));
        assert_eq!(merged.theme, "dracula");
        // Unchanged fields retain defaults
        assert_eq!(merged.thinking_level, ThinkingLevel::Medium);
        assert!(merged.extensions_enabled);
    }

    #[test]
    fn test_layer_file_preserves_unset() {
        let mut base = Settings::default();
        base.last_used_provider = Some("deepseek".to_string());

        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        // Only override theme — provider should remain
        let toml_content = "theme = \"monokai\"\n";
        tmp.as_file().write_all(toml_content.as_bytes()).unwrap();

        let merged = Settings::layer_file(&base, tmp.path()).unwrap();
        assert_eq!(merged.theme, "monokai");
        assert_eq!(merged.last_used_provider, Some("deepseek".to_string()));
    }

    #[test]
    fn test_load_from_dir_with_project_config() {
        let _guard = EnvGuard::new(&[
            "OXI_MODEL",
            "OXI_PROVIDER",
            "OXI_THEME",
            "OXI_TOOL_TIMEOUT",
            "OXI_TEMPERATURE",
            "OXI_MAX_TOKENS",
            "OXI_SESSION_DIR",
            "OXI_STREAM",
            "OXI_EXTENSIONS_ENABLED",
        ]);
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();
        let settings_path = oxi_dir.join("settings.toml");
        // Write v3 format: default_model contains "provider/model"
        fs::write(
            &settings_path,
            "version = 3\ndefault_model = \"google/gemini-2.0-flash\"\n",
        )
        .unwrap();

        let settings = Settings::load_from(tmp.path()).unwrap();
        // Migration moves default_model → last_used_model
        assert_eq!(
            settings.last_used_model,
            Some("gemini-2.0-flash".to_string())
        );
        assert_eq!(settings.last_used_provider, Some("google".to_string()));
    }

    #[test]
    fn test_load_from_dir_no_config() {
        // Clean env vars that load_from() reads via apply_env()
        let _guard = EnvGuard::new(&[
            "OXI_MODEL",
            "OXI_PROVIDER",
            "OXI_THEME",
            "OXI_TOOL_TIMEOUT",
            "OXI_TEMPERATURE",
            "OXI_MAX_TOKENS",
            "OXI_SESSION_DIR",
            "OXI_STREAM",
            "OXI_EXTENSIONS_ENABLED",
        ]);
        let tmp = tempfile::tempdir().unwrap();
        let settings = Settings::load_from(tmp.path()).unwrap();
        // Falls back to defaults (may include global ~/.oxi/settings)
        assert_eq!(settings.thinking_level, ThinkingLevel::Medium);
    }

    // ── Environment variables ────────────────────────────────────────

    #[test]
    fn test_from_env() {
        // NOTE: Environment variable overrides are disabled.
        // from_env() returns defaults only.
        let _guard = EnvGuard::new(&[
            // no env vars to clear
            "OXI_MODEL",
            "OXI_THEME",
            "OXI_TOOL_TIMEOUT",
            "OXI_PROVIDER",
            "OXI_DEFAULT_MODEL",
        ]);

        let settings = Settings::from_env();
        // All fields should be at defaults since env overrides are disabled
        assert_eq!(settings.last_used_model, None);
        assert_eq!(settings.theme, "default");
        assert_eq!(settings.tool_timeout_seconds, 120);
    }

    #[test]
    fn test_apply_env_boolish() {
        // NOTE: Environment variable overrides are disabled.
        // apply_env() is a no-op.
        let _guard = EnvGuard::new(&["OXI_STREAM", "OXI_EXTENSIONS_ENABLED"]);
        unsafe { env::set_var("OXI_STREAM", "false") };
        unsafe { env::set_var("OXI_EXTENSIONS_ENABLED", "0") };

        let mut settings = Settings::default();
        settings.apply_env();
        // Since env overrides are disabled, values stay at defaults
        assert!(settings.stream_responses); // default is true
        assert!(settings.extensions_enabled); // default is true
    }

    #[test]
    fn test_apply_env_temperature() {
        // NOTE: Environment variable overrides are disabled.
        let _guard = EnvGuard::new(&["OXI_TEMPERATURE"]);
        unsafe { env::set_var("OXI_TEMPERATURE", "0.7") };

        let mut settings = Settings::default();
        settings.apply_env();
        // Since env overrides are disabled, temperature stays at None
        assert_eq!(settings.default_temperature, None);
    }

    #[test]
    fn test_env_does_not_override_when_unset() {
        let _guard = EnvGuard::new(&["OXI_MODEL", "OXI_PROVIDER", "OXI_THEME", "OXI_TEMPERATURE"]);
        let settings = Settings::from_env();
        assert!(settings.last_used_model.is_none());
        assert!(settings.last_used_provider.is_none());
    }

    #[test]
    fn test_parse_thinking_level() {
        assert_eq!(parse_thinking_level("off"), Some(ThinkingLevel::Off));
        assert_eq!(parse_thinking_level("none"), Some(ThinkingLevel::Off));
        assert_eq!(
            parse_thinking_level("MINIMAL"),
            Some(ThinkingLevel::Minimal)
        );
        assert_eq!(parse_thinking_level("Low"), Some(ThinkingLevel::Low));
        assert_eq!(parse_thinking_level("medium"), Some(ThinkingLevel::Medium));
        assert_eq!(parse_thinking_level("Medium"), Some(ThinkingLevel::Medium));
        assert_eq!(
            parse_thinking_level("Standard"),
            Some(ThinkingLevel::Medium)
        );
        assert_eq!(parse_thinking_level("High"), Some(ThinkingLevel::High));
        assert_eq!(parse_thinking_level("thorough"), Some(ThinkingLevel::High));
        assert_eq!(parse_thinking_level("xhigh"), Some(ThinkingLevel::XHigh));
        assert_eq!(parse_thinking_level("invalid"), None);
    }

    #[test]
    fn test_parse_boolish() {
        assert!(parse_boolish("true").unwrap());
        assert!(parse_boolish("1").unwrap());
        assert!(parse_boolish("yes").unwrap());
        assert!(parse_boolish("ON").unwrap());
        assert!(!parse_boolish("false").unwrap());
        assert!(!parse_boolish("0").unwrap());
        assert!(!parse_boolish("no").unwrap());
        assert!(!parse_boolish("OFF").unwrap());
        assert!(parse_boolish("maybe").is_err());
    }

    // ── Effective accessors ──────────────────────────────────────────

    #[test]
    fn test_effective_model_returns_last_used() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("openai/gpt-4o".to_string());
        assert_eq!(
            settings.effective_model(None),
            Some("openai/gpt-4o".to_string())
        );
    }

    #[test]
    fn test_effective_model_cli_overrides() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("openai/gpt-4o".to_string());
        assert_eq!(
            settings.effective_model(Some("anthropic/claude-3")),
            Some("anthropic/claude-3".to_string())
        );
    }

    #[test]
    fn test_effective_model_none_when_unset() {
        let settings = Settings::default();
        assert_eq!(settings.effective_model(None), None);
    }

    #[test]
    fn test_effective_model_falls_back_to_last_used() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("anthropic/claude-3".to_string());
        assert_eq!(
            settings.effective_model(None),
            Some("anthropic/claude-3".to_string())
        );
    }

    #[test]
    fn test_effective_model_returns_none_when_nothing_set() {
        let settings = Settings::default();
        assert_eq!(settings.effective_model(None), None);
    }

    #[test]
    fn test_effective_temperature_prefers_f64() {
        let mut settings = Settings::default();
        settings.temperature = Some(0.5);
        settings.default_temperature = Some(0.7);
        assert_eq!(settings.effective_temperature(), Some(0.7));
    }

    #[test]
    fn test_effective_temperature_falls_back_to_f32() {
        let mut settings = Settings::default();
        settings.temperature = Some(0.5);
        assert_eq!(settings.effective_temperature(), Some(0.5));
    }

    #[test]
    fn test_effective_max_tokens_prefers_usize() {
        let mut settings = Settings::default();
        settings.max_tokens = Some(1024);
        settings.max_response_tokens = Some(4096);
        assert_eq!(settings.effective_max_tokens(), Some(4096));
    }

    #[test]
    fn test_effective_max_tokens_falls_back_to_u32() {
        let mut settings = Settings::default();
        settings.max_tokens = Some(1024);
        assert_eq!(settings.effective_max_tokens(), Some(1024));
    }

    // ── Session dir ──────────────────────────────────────────────────

    #[test]
    fn test_effective_session_dir_default() {
        let _guard = EnvGuard::new(&["OXI_SESSION_DIR"]);
        let settings = Settings::default();
        let dir = settings.effective_session_dir().unwrap();
        assert!(dir.ends_with("sessions"), "dir was: {:?}", dir);
    }

    #[test]
    fn test_effective_session_dir_from_field() {
        let _guard = EnvGuard::new(&["OXI_SESSION_DIR"]);
        let mut settings = Settings::default();
        settings.session_dir = Some(PathBuf::from("/tmp/oxi-sessions"));
        assert_eq!(
            settings.effective_session_dir().unwrap(),
            PathBuf::from("/tmp/oxi-sessions")
        );
    }

    #[test]
    fn test_effective_session_dir_env_disabled() {
        // NOTE: Environment variable overrides are disabled.
        // OXI_SESSION_DIR is ignored; effective_session_dir() returns the field value (or default).
        let _guard = EnvGuard::new(&["OXI_SESSION_DIR"]);
        unsafe { env::set_var("OXI_SESSION_DIR", "/tmp/env-sessions") };
        let settings = Settings::default();
        // Env is ignored, so it should use the default path, not /tmp/env-sessions
        let dir = settings.effective_session_dir().unwrap();
        assert!(
            dir.ends_with("sessions"),
            "expected default sessions dir, got: {:?}",
            dir
        );
    }

    // ── Migration ────────────────────────────────────────────────────

    #[test]
    fn test_migration_v0_to_v1() {
        let mut settings = Settings::default();
        settings.version = 0;
        settings.tool_timeout_seconds = 0; // v0 might not have this field

        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
        assert_eq!(migrated.tool_timeout_seconds, 120);
    }

    #[test]
    fn test_migration_already_current() {
        let settings = Settings::default();
        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
    }

    #[test]
    fn test_migration_v3_to_v4_splits_model() {
        let mut settings = Settings::default();
        settings.version = 3;
        settings.default_model = Some("openai/gpt-4o".to_string());
        settings.default_provider = None;

        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
        assert_eq!(migrated.last_used_model, Some("gpt-4o".to_string()));
        assert_eq!(migrated.last_used_provider, Some("openai".to_string()));
    }

    #[test]
    fn test_migration_v3_no_slash_keeps_model() {
        let mut settings = Settings::default();
        settings.version = 3;
        settings.default_model = Some("bare-model-name".to_string());

        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
        assert_eq!(
            migrated.last_used_model,
            Some("bare-model-name".to_string())
        );
    }

    #[test]
    fn test_migration_future_version_fails() {
        let mut settings = Settings::default();
        settings.version = 9999;
        assert!(Settings::migrate(settings).is_err());
    }

    // ── output_languages tests (TUI language policy, v5) ────────────

    #[test]
    fn test_default_output_languages_is_empty() {
        let settings = Settings::default();
        assert!(
            settings.output_languages.is_empty(),
            "all channels should default to auto (empty map)"
        );
    }

    #[test]
    fn test_migration_v4_to_v5_preserves_existing_output_languages() {
        let mut settings = Settings::default();
        settings.version = 4;
        settings
            .output_languages
            .insert("response".to_string(), "ko".to_string());
        settings
            .output_languages
            .insert("commit_message".to_string(), "en".to_string());

        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
        assert_eq!(
            migrated.output_languages.get("response"),
            Some(&"ko".to_string())
        );
        assert_eq!(
            migrated.output_languages.get("commit_message"),
            Some(&"en".to_string())
        );
    }

    #[test]
    fn test_migration_v4_to_v5_creates_empty_if_missing() {
        // A v4 file loaded fresh will not have `output_languages` at all —
        // serde fills it with an empty HashMap via `#[serde(default)]`.
        // After migration, version is bumped to 5 with the empty map intact.
        let mut settings = Settings::default();
        settings.version = 4;
        assert!(settings.output_languages.is_empty());

        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
        assert!(migrated.output_languages.is_empty());
    }

    #[test]
    fn test_validate_keeps_user_defined_channel() {
        // Per the extension-map contract, ANY channel key must be
        // accepted (known or user-defined). The validator must NOT
        // drop unknown channels — `language_directive` will use the
        // raw key as a label fallback.
        let mut settings = Settings::default();
        settings
            .output_languages
            .insert("pr_description".to_string(), "en".to_string()); // user-defined
        settings
            .output_languages
            .insert("response".to_string(), "ko".to_string()); // known

        settings.validate_output_languages();

        assert!(settings.output_languages.contains_key("pr_description"));
        assert!(settings.output_languages.contains_key("response"));
        assert_eq!(
            settings.output_languages.get("pr_description"),
            Some(&"en".to_string())
        );
        assert_eq!(
            settings.output_languages.get("response"),
            Some(&"ko".to_string())
        );
    }

    #[test]
    fn test_validate_keeps_unknown_lang_with_warning() {
        let mut settings = Settings::default();
        settings
            .output_languages
            .insert("response".to_string(), "klingon".to_string()); // unknown code
        settings
            .output_languages
            .insert("commit_message".to_string(), "en".to_string()); // known

        settings.validate_output_languages();

        // Unknown code is KEPT (with a warn log) so users can add languages
        // without code changes.
        assert_eq!(
            settings.output_languages.get("response"),
            Some(&"klingon".to_string())
        );
        assert_eq!(
            settings.output_languages.get("commit_message"),
            Some(&"en".to_string())
        );
    }

    #[test]
    fn test_known_channels_table_includes_core_four() {
        let keys: Vec<&str> = KNOWN_CHANNELS.iter().map(|(k, _)| *k).collect();
        assert!(keys.contains(&"response"));
        assert!(keys.contains(&"code_comment"));
        assert!(keys.contains(&"documentation"));
        assert!(keys.contains(&"commit_message"));
    }

    #[test]
    fn test_known_langs_table_includes_auto_and_english() {
        let codes: Vec<&str> = KNOWN_LANGS.iter().map(|(k, _)| *k).collect();
        assert!(codes.contains(&"auto"));
        assert!(codes.contains(&"en"));
    }

    #[test]
    fn test_default_language_policy_enabled_is_false() {
        // v6: master toggle defaults to OFF (opt-in).
        let settings = Settings::default();
        assert!(
            !settings.language_policy_enabled,
            "language_policy_enabled must default to false (opt-in)"
        );
    }

    #[test]
    fn test_migration_v5_to_v6_defaults_master_toggle_to_off() {
        // v5 settings (with output_languages configured) should migrate to v6
        // with language_policy_enabled = false. Channel mappings are preserved
        // but disabled until the user flips the master switch.
        let mut settings = Settings::default();
        settings.version = 5;
        settings
            .output_languages
            .insert("response".to_string(), "ko".to_string());
        settings
            .output_languages
            .insert("commit_message".to_string(), "en".to_string());

        let migrated = Settings::migrate(settings).unwrap();
        assert_eq!(migrated.version, SETTINGS_VERSION);
        assert!(
            !migrated.language_policy_enabled,
            "v5 → v6 migration must default language_policy_enabled to false"
        );
        // Channel mappings are preserved verbatim.
        assert_eq!(
            migrated.output_languages.get("response"),
            Some(&"ko".to_string())
        );
        assert_eq!(
            migrated.output_languages.get("commit_message"),
            Some(&"en".to_string())
        );
    }

    #[test]
    fn test_save_and_load_roundtrip_preserves_language_policy_enabled() {
        let tmp = tempfile::tempdir().unwrap();
        let settings_path = tmp.path().join("settings.toml");

        let mut original = Settings::default();
        original.language_policy_enabled = true;
        original
            .output_languages
            .insert("response".to_string(), "ko".to_string());

        let content = toml::to_string_pretty(&original).unwrap();
        fs::write(&settings_path, &content).unwrap();

        let loaded_content = fs::read_to_string(&settings_path).unwrap();
        let loaded: Settings = toml::from_str(&loaded_content).unwrap();

        assert!(loaded.language_policy_enabled);
        assert_eq!(
            loaded.output_languages.get("response"),
            Some(&"ko".to_string())
        );
    }

    #[test]
    fn test_save_and_load_roundtrip_preserves_output_languages() {
        let tmp = tempfile::tempdir().unwrap();
        let settings_path = tmp.path().join("settings.toml");

        let mut original = Settings::default();
        original
            .output_languages
            .insert("response".to_string(), "ko".to_string());
        original
            .output_languages
            .insert("commit_message".to_string(), "en".to_string());

        let content = toml::to_string_pretty(&original).unwrap();
        fs::write(&settings_path, &content).unwrap();

        let loaded_content = fs::read_to_string(&settings_path).unwrap();
        let loaded: Settings = toml::from_str(&loaded_content).unwrap();

        assert_eq!(
            loaded.output_languages.get("response"),
            Some(&"ko".to_string())
        );
        assert_eq!(
            loaded.output_languages.get("commit_message"),
            Some(&"en".to_string())
        );
    }

    // ── Persistence ──────────────────────────────────────────────────

    #[test]
    fn test_save_and_load_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let settings_path = tmp.path().join("settings.toml");

        let mut original = Settings::default();
        original.last_used_model = Some("gpt-4o".to_string());
        original.last_used_provider = Some("openai".to_string());
        original.theme = "dracula".to_string();
        original.tool_timeout_seconds = 60;

        // Serialize
        let content = toml::to_string_pretty(&original).unwrap();
        fs::write(&settings_path, &content).unwrap();

        // Deserialize
        let loaded_content = fs::read_to_string(&settings_path).unwrap();
        let loaded: Settings = toml::from_str(&loaded_content).unwrap();

        assert_eq!(loaded.last_used_model, original.last_used_model);
        assert_eq!(loaded.theme, original.theme);
        assert_eq!(loaded.tool_timeout_seconds, original.tool_timeout_seconds);
    }

    #[test]
    fn test_toml_roundtrip_preserves_new_fields() {
        let mut settings = Settings::default();
        settings.default_temperature = Some(0.8);
        settings.max_response_tokens = Some(8192);
        settings.auto_compaction = false;
        settings.extensions_enabled = false;
        settings.session_dir = Some(PathBuf::from("/custom/sessions"));

        let toml_str = toml::to_string_pretty(&settings).unwrap();
        let parsed: Settings = toml::from_str(&toml_str).unwrap();

        assert_eq!(parsed.default_temperature, Some(0.8));
        assert_eq!(parsed.max_response_tokens, Some(8192));
        assert!(!parsed.auto_compaction);
        assert!(!parsed.extensions_enabled);
        assert_eq!(parsed.session_dir, Some(PathBuf::from("/custom/sessions")));
    }

    // ── JSON format tests ──────────────────────────────────────────────

    #[test]
    fn test_json_roundtrip() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("gpt-4o".to_string());
        settings.last_used_provider = Some("openai".to_string());
        settings.theme = "dracula".to_string();
        settings.tool_timeout_seconds = 60;
        settings.default_temperature = Some(0.8);
        settings.max_response_tokens = Some(8192);

        let json_str = serde_json::to_string_pretty(&settings).unwrap();
        let parsed: Settings = serde_json::from_str(&json_str).unwrap();

        assert_eq!(parsed.last_used_model, settings.last_used_model);
        assert_eq!(parsed.theme, settings.theme);
        assert_eq!(parsed.tool_timeout_seconds, settings.tool_timeout_seconds);
        assert_eq!(parsed.default_temperature, settings.default_temperature);
        assert_eq!(parsed.max_response_tokens, settings.max_response_tokens);
    }

    #[test]
    fn test_json_serialize_for_format() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("claude-3".to_string());
        settings.last_used_provider = Some("anthropic".to_string());
        settings.thinking_level = ThinkingLevel::Minimal;

        let json_content = Settings::serialize_for_format(&settings, SettingsFormat::Json).unwrap();
        let parsed: Settings = serde_json::from_str(&json_content).unwrap();

        assert_eq!(parsed.last_used_model, Some("claude-3".to_string()));
        assert_eq!(parsed.thinking_level, ThinkingLevel::Minimal);
    }

    #[test]
    fn test_toml_serialize_for_format() {
        let mut settings = Settings::default();
        settings.last_used_model = Some("gemini-pro".to_string());
        settings.last_used_provider = Some("google".to_string());
        settings.thinking_level = ThinkingLevel::High;

        let toml_content = Settings::serialize_for_format(&settings, SettingsFormat::Toml).unwrap();
        let parsed: Settings = toml::from_str(&toml_content).unwrap();

        assert_eq!(parsed.last_used_model, Some("gemini-pro".to_string()));
        assert_eq!(parsed.thinking_level, ThinkingLevel::High);
    }

    #[test]
    fn test_parse_from_str_json() {
        let json_content = r#"{
            "last_used_model": "gpt-4",
            "last_used_provider": "openai",
            "theme": "nord",
            "tool_timeout_seconds": 90
        }"#;

        let settings = Settings::parse_from_str(json_content, SettingsFormat::Json).unwrap();
        assert_eq!(settings.last_used_model, Some("gpt-4".to_string()));
        assert_eq!(settings.last_used_provider, Some("openai".to_string()));
        assert_eq!(settings.theme, "nord");
        assert_eq!(settings.tool_timeout_seconds, 90);
        // Unchanged fields retain defaults
        assert_eq!(settings.thinking_level, ThinkingLevel::Medium);
        assert!(settings.extensions_enabled);
    }

    #[test]
    fn test_parse_from_str_toml() {
        let toml_content = r#"
last_used_model = "claude-opus"
last_used_provider = "anthropic"
theme = "monokai"
tool_timeout_seconds = 45
"#;

        let settings = Settings::parse_from_str(toml_content, SettingsFormat::Toml).unwrap();
        assert_eq!(settings.last_used_model, Some("claude-opus".to_string()));
        assert_eq!(settings.last_used_provider, Some("anthropic".to_string()));
        assert_eq!(settings.theme, "monokai");
        assert_eq!(settings.tool_timeout_seconds, 45);
        assert_eq!(settings.thinking_level, ThinkingLevel::Medium);
    }

    #[test]
    fn test_layer_file_json() {
        let base = Settings::default();

        let tmp = tempfile::NamedTempFile::with_suffix(".json").unwrap();
        let json_content = r#"{
            "last_used_model": "gpt-4o",
            "last_used_provider": "openai",
            "theme": "dracula",
            "auto_compaction": false
        }"#;
        tmp.as_file().write_all(json_content.as_bytes()).unwrap();

        let merged = Settings::layer_file(&base, tmp.path()).unwrap();
        assert_eq!(merged.last_used_model, Some("gpt-4o".to_string()));
        assert_eq!(merged.last_used_provider, Some("openai".to_string()));
        assert_eq!(merged.theme, "dracula");
        assert!(!merged.auto_compaction);
        // Unchanged fields retain defaults
        assert_eq!(merged.thinking_level, ThinkingLevel::Medium);
        assert!(merged.extensions_enabled);
        assert_eq!(merged.tool_timeout_seconds, 120);
    }

    #[test]
    fn test_layer_file_json_preserves_unset() {
        let mut base = Settings::default();
        base.last_used_provider = Some("deepseek".to_string());

        let tmp = tempfile::NamedTempFile::with_suffix(".json").unwrap();
        let json_content = r#"{ "theme": "nord" }"#;
        tmp.as_file().write_all(json_content.as_bytes()).unwrap();

        let merged = Settings::layer_file(&base, tmp.path()).unwrap();
        assert_eq!(merged.theme, "nord");
        assert_eq!(merged.last_used_provider, Some("deepseek".to_string()));
    }

    #[test]
    fn test_save_to_json() {
        let tmp = tempfile::tempdir().unwrap();
        let settings_path = tmp.path().join("settings.json");

        let mut settings = Settings::default();
        settings.last_used_model = Some("gpt-4o".to_string());
        settings.last_used_provider = Some("openai".to_string());
        settings.theme = "dracula".to_string();
        settings.tool_timeout_seconds = 60;

        settings.save_to(&settings_path).unwrap();

        // Verify it's valid JSON
        let content = fs::read_to_string(&settings_path).unwrap();
        let parsed: Settings = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed.last_used_model, Some("gpt-4o".to_string()));
        assert_eq!(parsed.theme, "dracula");
        assert_eq!(parsed.tool_timeout_seconds, 60);
    }

    #[test]
    fn test_save_to_toml() {
        let tmp = tempfile::tempdir().unwrap();
        let settings_path = tmp.path().join("settings.toml");

        let mut settings = Settings::default();
        settings.last_used_model = Some("gemini-pro".to_string());
        settings.last_used_provider = Some("google".to_string());
        settings.theme = "monokai".to_string();
        settings.tool_timeout_seconds = 90;

        settings.save_to(&settings_path).unwrap();

        // Verify it's valid TOML
        let content = fs::read_to_string(&settings_path).unwrap();
        let parsed: Settings = toml::from_str(&content).unwrap();
        assert_eq!(parsed.last_used_model, Some("gemini-pro".to_string()));
        assert_eq!(parsed.theme, "monokai");
        assert_eq!(parsed.tool_timeout_seconds, 90);
    }

    #[test]
    fn test_load_from_dir_with_json_project_config() {
        let _guard = EnvGuard::new(&[
            "OXI_MODEL",
            "OXI_PROVIDER",
            "OXI_THEME",
            "OXI_TOOL_TIMEOUT",
            "OXI_TEMPERATURE",
            "OXI_MAX_TOKENS",
            "OXI_SESSION_DIR",
            "OXI_STREAM",
            "OXI_EXTENSIONS_ENABLED",
        ]);
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();
        let settings_path = oxi_dir.join("settings.json");
        // v3 format: default_model has provider/model
        let json_content = r#"{ "version": 3, "default_model": "google/gemini-2.0-flash" }"#;
        fs::write(&settings_path, json_content).unwrap();

        let settings = Settings::load_from(tmp.path()).unwrap();
        // Migration splits provider from model
        assert_eq!(
            settings.last_used_model,
            Some("gemini-2.0-flash".to_string())
        );
        assert_eq!(settings.last_used_provider, Some("google".to_string()));
    }

    #[test]
    fn test_find_project_settings_json_priority() {
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();

        // Create both files
        let json_path = oxi_dir.join("settings.json");
        let toml_path = oxi_dir.join("settings.toml");
        fs::write(&json_path, r#"{ "theme": "json-theme" }"#).unwrap();
        fs::write(&toml_path, r#"theme = "toml-theme""#).unwrap();

        // JSON takes priority
        let found = Settings::find_project_settings(tmp.path());
        assert!(found.is_some());
        assert_eq!(
            found.unwrap().file_name().unwrap().to_str().unwrap(),
            "settings.json"
        );
    }

    #[test]
    fn test_find_project_settings_json_only() {
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();

        let json_path = oxi_dir.join("settings.json");
        fs::write(&json_path, r#"{ "theme": "test" }"#).unwrap();

        let found = Settings::find_project_settings(tmp.path());
        assert!(found.is_some());
        assert_eq!(
            found.unwrap().file_name().unwrap().to_str().unwrap(),
            "settings.json"
        );
    }

    #[test]
    fn test_find_project_settings_toml_fallback() {
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();

        let toml_path = oxi_dir.join("settings.toml");
        fs::write(&toml_path, r#"theme = "test""#).unwrap();

        let found = Settings::find_project_settings(tmp.path());
        assert!(found.is_some());
        assert_eq!(
            found.unwrap().file_name().unwrap().to_str().unwrap(),
            "settings.toml"
        );
    }

    #[test]
    fn test_detect_format() {
        let json_path = PathBuf::from("/test/settings.json");
        let toml_path = PathBuf::from("/test/settings.toml");
        let unknown_path = PathBuf::from("/test/settings");

        assert_eq!(Settings::detect_format(&json_path), SettingsFormat::Json);
        assert_eq!(Settings::detect_format(&toml_path), SettingsFormat::Toml);
        assert_eq!(Settings::detect_format(&unknown_path), SettingsFormat::Json);
        // Default
    }

    #[test]
    fn test_settings_format_extension() {
        assert_eq!(SettingsFormat::Json.extension(), "json");
        assert_eq!(SettingsFormat::Toml.extension(), "toml");
    }

    #[test]
    fn test_layer_json_over_toml() {
        // Test that when loading, JSON takes priority over TOML
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();

        let json_path = oxi_dir.join("settings.json");
        let toml_path = oxi_dir.join("settings.toml");

        // JSON has model set to "json-model"
        fs::write(&json_path, r#"{ "last_used_model": "json-model" }"#).unwrap();
        // TOML has model set to "toml-model"
        fs::write(&toml_path, r#"last_used_model = "toml-model""#).unwrap();

        // JSON takes priority
        let settings = Settings::load_from(tmp.path()).unwrap();
        assert_eq!(settings.last_used_model, Some("json-model".to_string()));
    }

    #[test]
    fn test_mixed_format_loading() {
        // Test loading a TOML file through the generic layer_file
        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        let toml_content = r#"
last_used_model = "loaded-via-toml"
theme = "loaded-theme"
stream_responses = false
"#;
        tmp.as_file().write_all(toml_content.as_bytes()).unwrap();

        let merged = Settings::layer_file(&Settings::default(), tmp.path()).unwrap();
        assert_eq!(merged.last_used_model, Some("loaded-via-toml".to_string()));
        assert_eq!(merged.theme, "loaded-theme");
        assert!(!merged.stream_responses);
    }

    #[test]
    fn test_merge_json_values() {
        let base = serde_json::json!({
            "version": 1,
            "theme": "default",
            "extensions": ["ext1"],
            "nested": {
                "a": 1,
                "b": 2
            }
        });

        let override_ = serde_json::json!({
            "version": 2,
            "theme": "dark",
            "extensions": ["ext2"],
            "nested": {
                "b": 20,
                "c": 30
            }
        });

        let merged = merge_json_values(base, override_);

        assert_eq!(merged["version"], 2);
        assert_eq!(merged["theme"], "dark");
        // Arrays are replaced, not merged
        assert_eq!(merged["extensions"], serde_json::json!(["ext2"]));
        // Nested objects are deeply merged
        assert_eq!(merged["nested"]["a"], 1);
        assert_eq!(merged["nested"]["b"], 20);
        assert_eq!(merged["nested"]["c"], 30);
    }

    #[test]
    fn test_save_project_preserves_existing_format() {
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();

        // Create existing TOML file
        let toml_path = oxi_dir.join("settings.toml");
        fs::write(&toml_path, "theme = 'old-theme'").unwrap();

        let mut settings = Settings::default();
        settings.theme = "new-theme".to_string();
        settings.save_project(tmp.path()).unwrap();

        // Should still be TOML
        let content = fs::read_to_string(&toml_path).unwrap();
        assert!(content.contains("new-theme"));
        assert!(serde_json::from_str::<serde_json::Value>(&content).is_err());
    }

    #[test]
    fn test_save_project_creates_json_by_default() {
        let tmp = tempfile::tempdir().unwrap();
        let oxi_dir = tmp.path().join(".oxi");
        fs::create_dir_all(&oxi_dir).unwrap();
        // Don't create any settings file

        let mut settings = Settings::default();
        settings.theme = "json-theme".to_string();
        settings.save_project(tmp.path()).unwrap();

        // Should create JSON file
        let json_path = oxi_dir.join("settings.json");
        assert!(json_path.exists());
        let content = fs::read_to_string(&json_path).unwrap();
        assert!(serde_json::from_str::<serde_json::Value>(&content).is_ok());
        assert!(content.contains("json-theme"));
    }

    // ── Custom provider tests ───────────────────────────────────────

    #[test]
    fn test_custom_provider_default_api() {
        use super::CustomProvider;
        let cp = CustomProvider {
            name: "test".to_string(),
            base_url: "https://api.test.com/v1".to_string(),
            api_key_env: "TEST_API_KEY".to_string(),
            api: super::default_custom_provider_api(),
        };
        assert_eq!(cp.api, "openai-completions");
    }

    #[test]
    fn test_custom_provider_toml_deserialize() {
        let toml_content = r#"
[[custom_providers]]
name = "minimax"
base_url = "https://api.minimax.chat/v1"
api_key_env = "MINIMAX_API_KEY"
api = "openai-completions"

[[custom_providers]]
name = "zai"
base_url = "https://api.z.ai/v1"
api_key_env = "ZAI_API_KEY"
api = "openai-responses"
"#;
        let settings: Settings = toml::from_str(toml_content).unwrap();
        assert_eq!(settings.custom_providers.len(), 2);
        assert_eq!(settings.custom_providers[0].name, "minimax");
        assert_eq!(
            settings.custom_providers[0].base_url,
            "https://api.minimax.chat/v1"
        );
        assert_eq!(settings.custom_providers[0].api_key_env, "MINIMAX_API_KEY");
        assert_eq!(settings.custom_providers[0].api, "openai-completions");
        assert_eq!(settings.custom_providers[1].name, "zai");
        assert_eq!(settings.custom_providers[1].api, "openai-responses");
    }

    #[test]
    fn test_custom_provider_json_deserialize() {
        let json_content = r#"{
            "custom_providers": [
                {
                    "name": "minimax",
                    "base_url": "https://api.minimax.chat/v1",
                    "api_key_env": "MINIMAX_API_KEY",
                    "api": "openai-completions"
                }
            ]
        }"#;
        let settings: Settings = serde_json::from_str(json_content).unwrap();
        assert_eq!(settings.custom_providers.len(), 1);
        assert_eq!(settings.custom_providers[0].name, "minimax");
    }

    #[test]
    fn test_custom_provider_toml_roundtrip() {
        let mut settings = Settings::default();
        settings.custom_providers.push(super::CustomProvider {
            name: "test".to_string(),
            base_url: "https://api.test.com/v1".to_string(),
            api_key_env: "TEST_API_KEY".to_string(),
            api: "openai-completions".to_string(),
        });

        let toml_str = toml::to_string_pretty(&settings).unwrap();
        let parsed: Settings = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.custom_providers.len(), 1);
        assert_eq!(parsed.custom_providers[0].name, "test");
        assert_eq!(
            parsed.custom_providers[0].base_url,
            "https://api.test.com/v1"
        );
    }

    #[test]
    fn test_custom_provider_defaults_empty() {
        let settings = Settings::default();
        assert!(settings.custom_providers.is_empty());
    }

    #[test]
    fn test_custom_provider_layer_file() {
        let base = Settings::default();

        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        let toml_content = r#"
[[custom_providers]]
name = "my-provider"
base_url = "https://api.my-provider.com/v1"
api_key_env = "MY_PROVIDER_API_KEY"
"#;
        tmp.as_file().write_all(toml_content.as_bytes()).unwrap();

        let merged = Settings::layer_file(&base, tmp.path()).unwrap();
        assert_eq!(merged.custom_providers.len(), 1);
        assert_eq!(merged.custom_providers[0].name, "my-provider");
        // Default api value
        assert_eq!(merged.custom_providers[0].api, "openai-completions");
    }
}