lang-check 0.6.0

Multilingual prose linter with tree-sitter extraction and pluggable checking engines
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use tracing::warn;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Config {
    #[serde(default)]
    pub engines: EngineConfig,
    #[serde(default)]
    pub rules: HashMap<String, RuleConfig>,
    #[serde(default = "default_exclude")]
    pub exclude: Vec<String>,
    #[serde(default)]
    pub auto_fix: Vec<AutoFixRule>,
    #[serde(default)]
    pub performance: PerformanceConfig,
    #[serde(default)]
    pub dictionaries: DictionaryConfig,
    #[serde(default)]
    pub languages: LanguageConfig,
    #[serde(default)]
    pub workspace: WorkspaceConfig,
    #[serde(default)]
    pub names: NameConfig,
    #[serde(default)]
    pub morphology: MorphologyConfig,
}

/// Opt-in suppression of spelling diagnostics on human names.
///
/// Off by default: the failure mode is silently hiding a real misspelling, which is
/// much harder to notice than a stray squiggle on a surname.
///
/// ```yaml
/// names:
///   enabled: true
///   aggressiveness: balanced   # conservative | balanced | aggressive
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct NameConfig {
    /// Whether to drop spelling diagnostics on tokens detected as human names.
    #[serde(default)]
    pub enabled: bool,
    /// How much corroborating evidence a name needs before its diagnostic is dropped.
    /// Default: `balanced`.
    #[serde(default)]
    pub aggressiveness: crate::names::Aggressiveness,
}

/// Acceptance of words built by affixation on material already known.
///
/// On by default, unlike [`NameConfig`]: a name verdict is a guess about a token, while
/// a decomposition is a claim that can be checked — `subalgebra` is accepted only
/// because `algebra` is a word. The failure mode both share is silently hiding a real
/// misspelling, and here it is bounded by the engine's own suggestions.
///
/// ```yaml
/// morphology:
///   enabled: true       # accept prefixed and derived forms of known words
///   inflections: true   # also accept the regular inflections of dictionary words
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MorphologyConfig {
    /// Accept a flagged token that decomposes into a known root.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Generate the regular inflections of every dictionary word and accept those too.
    #[serde(default = "default_true")]
    pub inflections: bool,
}

impl Default for MorphologyConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            inflections: true,
        }
    }
}

/// Language extension aliasing configuration.
///
/// Maps canonical language IDs to additional file extensions.
/// Built-in extensions (e.g. `.md` → markdown, `.htm` → html) are always
/// included; entries here add to them.
///
/// ```yaml
/// languages:
///   extensions:
///     markdown: [mdx, Rmd]
///     latex: [sty]
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct LanguageConfig {
    /// Additional file extensions per language ID (without leading dots).
    #[serde(default)]
    pub extensions: HashMap<String, Vec<String>>,
    /// LaTeX-specific settings.
    #[serde(default)]
    pub latex: LaTeXConfig,
}

/// LaTeX-specific configuration.
///
/// ```yaml
/// languages:
///   latex:
///     skip_environments:
///       - prooftree
///       - mycustomenv
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct LaTeXConfig {
    /// Extra environment names to skip during prose extraction.
    /// These are checked in addition to the built-in skip list.
    #[serde(default)]
    pub skip_environments: Vec<String>,
    /// Extra command names whose arguments should be skipped during prose
    /// extraction. These are checked in addition to the built-in skip list
    /// (which includes `texttt`, `verb`, `url`, etc.).
    #[serde(default)]
    pub skip_commands: Vec<String>,
}

/// Workspace-level settings.
///
/// ```yaml
/// workspace:
///   index_on_open: true
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct WorkspaceConfig {
    /// Whether to run a full workspace index when the project is opened.
    /// Default: false (only check documents on open/change).
    #[serde(default)]
    pub index_on_open: bool,
    /// Custom path for the workspace database file. When empty (default),
    /// databases are stored in the user data directory.
    #[serde(default)]
    pub db_path: Option<String>,
}

/// Performance tuning options. High Performance Mode (HPM) disables
/// expensive engines and external providers, using only harper-core.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PerformanceConfig {
    /// Enable High Performance Mode (only harper, no LT/externals).
    #[serde(default)]
    pub high_performance_mode: bool,
    /// How long after the last keystroke a check runs, in milliseconds.
    ///
    /// Read by the editor clients, which own the typing loop; the core checks
    /// whatever it is handed, whenever it is handed it.
    #[serde(default = "default_debounce_ms")]
    pub debounce_ms: u64,
    /// Maximum file size in bytes to check (0 = unlimited).
    #[serde(default)]
    pub max_file_size: usize,
    /// How many engine answers to keep, keyed by the prose that produced them.
    ///
    /// A keystroke re-checks the whole document although one prose range
    /// changed, so the cache is what keeps a long file responsive. `0`
    /// disables it and re-checks every range on every keystroke.
    #[serde(default = "default_result_cache_entries")]
    pub result_cache_entries: usize,
    /// Longest prose range handed on, in bytes; longer ones are split at
    /// sentence boundaries. `0` disables splitting.
    ///
    /// A range is one cache key and one box in the inspector, so a document
    /// written without blank lines between paragraphs otherwise becomes a
    /// single range and neither the cache nor the inspector can say anything
    /// useful about it.
    #[serde(default = "default_max_range_bytes")]
    pub max_range_bytes: usize,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            high_performance_mode: false,
            debounce_ms: 500,
            max_file_size: 0,
            result_cache_entries: default_result_cache_entries(),
            max_range_bytes: default_max_range_bytes(),
        }
    }
}

/// Long enough that a burst of typing produces one check, short enough that a
/// pause feels answered. The VS Code extension defaults to the same number.
const fn default_debounce_ms() -> u64 {
    500
}

/// Room for several long documents at once: a 36 kB file is around 110 prose
/// ranges, so this holds roughly thirty of them per engine before evicting.
const fn default_result_cache_entries() -> usize {
    4096
}

/// Several sentences, so the cross-sentence rules still have something to work
/// with, while a keystroke dirties a paragraph's worth of cache rather than a
/// chapter's. Splitting costs nothing on a cold check: the engines pack ranges
/// back together up to `max_request_bytes` before sending them.
const fn default_max_range_bytes() -> usize {
    2048
}

/// Configuration for bundled and additional wordlist dictionaries.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DictionaryConfig {
    /// Whether to load the bundled domain-specific dictionaries (software terms,
    /// TypeScript, companies, jargon, mathematics). Default: true.
    #[serde(default = "default_true")]
    pub bundled: bool,
    /// Names of individual bundled dictionaries to skip, e.g.
    /// `["companies", "mathematics"]`. Every set loads by default; listing one
    /// here turns off just that one. Ignored when `bundled` is false.
    #[serde(default)]
    pub disabled: Vec<String>,
    /// Paths to additional wordlist files (one word per line, `#` comments).
    /// Relative paths are resolved from the workspace root.
    #[serde(default)]
    pub paths: Vec<String>,
}

impl Default for DictionaryConfig {
    fn default() -> Self {
        Self {
            bundled: true,
            disabled: Vec::new(),
            paths: Vec::new(),
        }
    }
}

/// A user-defined find->replace auto-fix rule.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AutoFixRule {
    /// Pattern to find (plain text, case-sensitive).
    pub find: String,
    /// Replacement text.
    pub replace: String,
    /// Optional context filter: only apply when surrounding text matches.
    #[serde(default)]
    pub context: Option<String>,
    /// Optional description for the rule.
    #[serde(default)]
    pub description: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(from = "EngineConfigWire")]
pub struct EngineConfig {
    pub harper: HarperConfig,
    pub languagetool: LanguageToolConfig,
    pub vale: ValeConfig,
    pub proselint: ProselintConfig,
    pub hunspell: HunspellConfig,
    /// External checker providers registered via config.
    pub external: Vec<ExternalProvider>,
    /// WASM checker plugins loaded via Extism.
    pub wasm_plugins: Vec<WasmPlugin>,
    /// BCP-47 natural language tag for spell/grammar checking (e.g. "en-US", "de-DE").
    pub spell_language: String,
}

/// On-disk form of [`EngineConfig`], carrying the flat pre-nesting keys next to
/// the nested ones.
///
/// `engines.languagetool_url` and `engines.vale_config` were folded into
/// `engines.languagetool.url` and `engines.vale.config` when engine settings
/// became nested structs. serde drops unknown keys without a word, so every
/// config still written the flat way — including the one in our own README —
/// silently fell back to the default `http://localhost:8010`, and the only
/// symptom was a connection error naming a server the user never configured
/// (issue #86). Both spellings are read here, and the flat one warns.
#[derive(Deserialize)]
struct EngineConfigWire {
    #[serde(
        default = "default_harper_config",
        deserialize_with = "deser_engine_or_bool"
    )]
    harper: HarperConfig,
    #[serde(default, deserialize_with = "deser_engine_or_bool")]
    languagetool: LanguageToolConfig,
    #[serde(default, deserialize_with = "deser_engine_or_bool")]
    vale: ValeConfig,
    #[serde(default, deserialize_with = "deser_engine_or_bool")]
    proselint: ProselintConfig,
    #[serde(default, deserialize_with = "deser_engine_or_bool")]
    hunspell: HunspellConfig,
    #[serde(default)]
    external: Vec<ExternalProvider>,
    #[serde(default)]
    wasm_plugins: Vec<WasmPlugin>,
    #[serde(default = "default_spell_language")]
    spell_language: String,
    /// Deprecated alias for `engines.languagetool.url`.
    #[serde(default)]
    languagetool_url: Option<String>,
    /// Deprecated alias for `engines.vale.config`.
    #[serde(default)]
    vale_config: Option<String>,
}

impl From<EngineConfigWire> for EngineConfig {
    fn from(wire: EngineConfigWire) -> Self {
        let EngineConfigWire {
            harper,
            mut languagetool,
            mut vale,
            proselint,
            hunspell,
            external,
            wasm_plugins,
            spell_language,
            languagetool_url,
            vale_config,
        } = wire;

        // The nested key wins when both are present: it is the supported
        // spelling, so a config carrying both is mid-migration.
        if let Some(url) = languagetool_url {
            if languagetool.url == default_lt_url() {
                warn_deprecated_engine_key("engines.languagetool_url", "engines.languagetool.url");
                languagetool.url = url;
            } else {
                warn_ignored_engine_key("engines.languagetool_url", "engines.languagetool.url");
            }
        }
        if let Some(path) = vale_config {
            if vale.config.is_none() {
                warn_deprecated_engine_key("engines.vale_config", "engines.vale.config");
                vale.config = Some(path);
            } else {
                warn_ignored_engine_key("engines.vale_config", "engines.vale.config");
            }
        }

        Self {
            harper,
            languagetool,
            vale,
            proselint,
            hunspell,
            external,
            wasm_plugins,
            spell_language,
        }
    }
}

/// Report a flat pre-nesting key that was honoured but should be rewritten.
fn warn_deprecated_engine_key(old: &str, new: &str) {
    warn!(
        "`{old}` is deprecated and will be removed in a future release; \
         rename it to `{new}`. Honouring it for now."
    );
}

/// Report a flat pre-nesting key that the nested key already overrode.
fn warn_ignored_engine_key(old: &str, new: &str) {
    warn!("`{old}` is ignored because `{new}` is also set; delete the deprecated key.");
}

/// Deserialize an engine config from either a bool shorthand or the full struct.
/// `harper: true` → `HarperConfig { enabled: true, ..default }`.
fn deser_engine_or_bool<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de> + EngineToggle + Default,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum BoolOrStruct<T> {
        Bool(bool),
        Struct(T),
    }

    match BoolOrStruct::deserialize(deserializer)? {
        BoolOrStruct::Bool(b) => {
            let mut cfg = T::default();
            cfg.set_enabled(b);
            Ok(cfg)
        }
        BoolOrStruct::Struct(s) => Ok(s),
    }
}

/// Trait for engine configs that can be toggled with a bool shorthand.
pub trait EngineToggle {
    fn enabled(&self) -> bool;
    fn set_enabled(&mut self, v: bool);
}

/// Harper engine configuration.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HarperConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Harper dialect: `American`, `British`, `Canadian`, `Australian`, `Indian`.
    #[serde(default = "default_dialect")]
    pub dialect: String,
    /// Per-rule toggles. Key is the rule name (e.g. `LongSentences`), value
    /// is `true`/`false`. Omitted rules use the curated default.
    #[serde(default)]
    pub linters: HashMap<String, bool>,
}

impl Default for HarperConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            dialect: "American".to_string(),
            linters: HashMap::new(),
        }
    }
}

fn default_harper_config() -> HarperConfig {
    HarperConfig::default()
}

fn default_dialect() -> String {
    "American".to_string()
}

impl EngineToggle for HarperConfig {
    fn enabled(&self) -> bool {
        self.enabled
    }
    fn set_enabled(&mut self, v: bool) {
        self.enabled = v;
    }
}

/// `LanguageTool` engine configuration.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LanguageToolConfig {
    #[serde(default)]
    pub enabled: bool,
    /// `LanguageTool` server URL.
    #[serde(default = "default_lt_url")]
    pub url: String,
    /// Checking level: `default` or `picky` (enables stricter rules).
    #[serde(default = "default_lt_level")]
    pub level: String,
    /// User's native language for false-friends detection (BCP-47 tag).
    #[serde(default)]
    pub mother_tongue: Option<String>,
    /// Rule IDs to disable (e.g. `["WHITESPACE_RULE"]`).
    #[serde(default)]
    pub disabled_rules: Vec<String>,
    /// Rule IDs to enable beyond defaults.
    #[serde(default)]
    pub enabled_rules: Vec<String>,
    /// Category IDs to disable.
    #[serde(default)]
    pub disabled_categories: Vec<String>,
    /// Category IDs to enable.
    #[serde(default)]
    pub enabled_categories: Vec<String>,
    /// How many `/v2/check` requests may be in flight at once.
    ///
    /// Lower this when pointing at a shared or rate-limited server; `1`
    /// restores serial checking.
    #[serde(default = "default_lt_max_concurrent_requests")]
    pub max_concurrent_requests: usize,
    /// How much prose to put in one `/v2/check`, in bytes.
    ///
    /// Prose ranges are packed up to this size before being sent. A range that
    /// exceeds it on its own still gets a request of its own; `0` disables
    /// packing and restores one request per range.
    #[serde(default = "default_lt_max_request_bytes")]
    pub max_request_bytes: usize,
}

impl Default for LanguageToolConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            url: default_lt_url(),
            level: "default".to_string(),
            mother_tongue: None,
            disabled_rules: Vec::new(),
            enabled_rules: Vec::new(),
            disabled_categories: Vec::new(),
            enabled_categories: Vec::new(),
            max_concurrent_requests: default_lt_max_concurrent_requests(),
            max_request_bytes: default_lt_max_request_bytes(),
        }
    }
}

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

/// Enough parallelism to hide per-request latency on a local server without
/// swamping a shared one — measured saturation point is around 8.
const fn default_lt_max_concurrent_requests() -> usize {
    8
}

/// Measured against a local `LanguageTool` 6.x, a `/v2/check` costs about
/// 8 ms flat plus 20.6 us per byte. Per prose range that flat cost dominates —
/// a 36 kB Typst document is 109 ranges of median 156 bytes, so 872 ms of the
/// wall clock is request overhead alone. Packing to 4 kB leaves overhead under
/// a tenth of the request and keeps each one short enough that the concurrency
/// window stays full; 8 kB and above buys little and delays the first result.
const fn default_lt_max_request_bytes() -> usize {
    4096
}

/// Hunspell: spelling for the languages the other engines do not read.
///
/// ```yaml
/// engines:
///   hunspell:
///     enabled: true
///     languages: ["he", "la"]
///     dictionary_paths:
///       la: /opt/dictionaries/latin
/// ```
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct HunspellConfig {
    /// Off by default, like every engine that needs something installed.
    #[serde(default)]
    pub enabled: bool,
    /// Languages to check with Hunspell, as BCP-47 tags.
    ///
    /// Naming them ahead of time is what lets a pack be fetched before it is
    /// needed rather than mid-document, and what keeps this engine to the gaps
    /// -- leave English out and Harper keeps it. Empty means any language with
    /// a pack behind it, which is the discovery mode and not the tidy one.
    #[serde(default)]
    pub languages: Vec<String>,
    /// Per-language override: a directory, an `.aff`/`.dic` stem, or either
    /// file of the pair. Beats every search path, so a pinned dictionary is
    /// definitely the one in use.
    #[serde(default)]
    pub dictionary_paths: HashMap<String, String>,
    /// Extra directories to search, before the platform's own.
    #[serde(default)]
    pub search_paths: Vec<String>,
    /// Fetch a missing pack without being asked.
    ///
    /// Off by default: a dictionary is a third-party download under its own
    /// licence -- Hspell is AGPL-3.0, the Latin pack GPL -- and that is a
    /// decision to put to the user rather than to make for them.
    #[serde(default)]
    pub auto_install: bool,
}

impl EngineToggle for HunspellConfig {
    fn enabled(&self) -> bool {
        self.enabled
    }
    fn set_enabled(&mut self, v: bool) {
        self.enabled = v;
    }
}

impl EngineToggle for LanguageToolConfig {
    fn enabled(&self) -> bool {
        self.enabled
    }
    fn set_enabled(&mut self, v: bool) {
        self.enabled = v;
    }
}

/// Vale engine configuration.
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct ValeConfig {
    #[serde(default)]
    pub enabled: bool,
    /// Path to `.vale.ini`. When empty, Vale uses its own search logic.
    #[serde(default)]
    pub config: Option<String>,
}

impl EngineToggle for ValeConfig {
    fn enabled(&self) -> bool {
        self.enabled
    }
    fn set_enabled(&mut self, v: bool) {
        self.enabled = v;
    }
}

/// Proselint engine configuration.
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct ProselintConfig {
    #[serde(default)]
    pub enabled: bool,
    /// Path to `proselint.json` config. When empty, proselint uses its own search logic.
    #[serde(default)]
    pub config: Option<String>,
}

impl EngineToggle for ProselintConfig {
    fn enabled(&self) -> bool {
        self.enabled
    }
    fn set_enabled(&mut self, v: bool) {
        self.enabled = v;
    }
}

/// An external checker binary that communicates via stdin/stdout JSON.
///
/// The binary receives `{"text": "...", "language_id": "..."}` on stdin
/// and returns `[{"start_byte": N, "end_byte": N, "message": "...", ...}]` on stdout.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExternalProvider {
    /// Display name for this provider.
    pub name: String,
    /// Path to the executable.
    pub command: String,
    /// Optional arguments to pass to the command.
    #[serde(default)]
    pub args: Vec<String>,
    /// File extensions this provider parses, without the dot (empty = all).
    ///
    /// The markup it understands, which is a different question from the
    /// language it speaks.
    #[serde(default)]
    pub extensions: Vec<String>,
    /// BCP-47 tags this provider checks (empty = all).
    ///
    /// Without this a provider claims every language, including ones it has
    /// no idea what to do with -- and claiming a language suppresses the
    /// report that says nothing could check it.
    #[serde(default)]
    pub languages: Vec<String>,
}

/// A WASM plugin loaded via Extism.
///
/// Plugins must export a `check` function that receives a JSON string
/// `{"text": "...", "language_id": "..."}` and returns a JSON array of diagnostics.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct WasmPlugin {
    /// Display name for this plugin.
    pub name: String,
    /// Path to the `.wasm` file (relative to workspace root or absolute).
    pub path: String,
    /// File extensions this plugin parses, without the dot (empty = all).
    #[serde(default)]
    pub extensions: Vec<String>,
    /// BCP-47 tags this plugin checks (empty = all).
    #[serde(default)]
    pub languages: Vec<String>,
}

impl Default for EngineConfig {
    fn default() -> Self {
        Self {
            harper: HarperConfig::default(),
            languagetool: LanguageToolConfig::default(),
            vale: ValeConfig::default(),
            proselint: ProselintConfig::default(),
            hunspell: HunspellConfig::default(),
            external: Vec::new(),
            wasm_plugins: Vec::new(),
            spell_language: default_spell_language(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RuleConfig {
    pub severity: Option<String>, // "error", "warning", "info", "hint", "off"
}

const fn default_true() -> bool {
    true
}
fn default_lt_url() -> String {
    "http://localhost:8010".to_string()
}
fn default_spell_language() -> String {
    "en-US".to_string()
}
fn default_exclude() -> Vec<String> {
    vec![
        "node_modules/**".to_string(),
        ".git/**".to_string(),
        "target/**".to_string(),
        "dist/**".to_string(),
        "build/**".to_string(),
        ".next/**".to_string(),
        ".nuxt/**".to_string(),
        "vendor/**".to_string(),
        "__pycache__/**".to_string(),
        ".venv/**".to_string(),
        "venv/**".to_string(),
        ".tox/**".to_string(),
        ".mypy_cache/**".to_string(),
        "*.min.js".to_string(),
        "*.min.css".to_string(),
        "*.bundle.js".to_string(),
        "package-lock.json".to_string(),
        "yarn.lock".to_string(),
        "pnpm-lock.yaml".to_string(),
    ]
}

impl Config {
    /// Load configuration, warning and falling back to defaults if it cannot be read.
    ///
    /// `load` fails on a malformed `.languagecheck.yaml` — a bad indent, a typo'd enum — and
    /// callers used to answer that with a bare `Config::default()`, so a rejected file was
    /// indistinguishable from an absent one and the user's overrides silently did nothing.
    /// A missing file is not an error and is not reported; an unreadable one is.
    ///
    /// Callers with no `tracing` subscriber installed (the CLI binary) must report to stderr
    /// themselves rather than call this, or the warning goes nowhere.
    #[must_use]
    pub fn load_or_warn(workspace_root: &Path) -> Self {
        Self::load(workspace_root).unwrap_or_else(|e| {
            warn!(
                root = %workspace_root.display(),
                "Ignoring unreadable workspace config, using defaults: {e}"
            );
            Self::default()
        })
    }

    /// Whether `exclude` covers this path.
    ///
    /// `path` may be absolute or already relative to `workspace_root`; it is
    /// reduced to the workspace-relative form the patterns are written
    /// against, because `node_modules/**` is how a user thinks about it and
    /// an absolute path would never match.
    ///
    /// An unparseable pattern excludes nothing. Refusing to check a file
    /// because a glob had a typo is the worse of the two failures.
    #[must_use]
    pub fn excludes(&self, path: &Path, workspace_root: &Path) -> bool {
        if self.exclude.is_empty() {
            return false;
        }
        let relative = path.strip_prefix(workspace_root).unwrap_or(path);
        // Separators normalised, because the patterns are written with `/` --
        // `node_modules/**` is how anyone writes it, on any platform -- while
        // the path arrives with the platform's own. Without this, `exclude`
        // matched nothing at all on Windows and said nothing about why.
        let as_text = relative.to_string_lossy().replace('\\', "/");
        // Written once, because the indexer, the CLI and the editor all have
        // to agree about what is excluded -- a file the editor still checks
        // after the indexer skipped it is the inconsistency this avoids.
        let options = glob::MatchOptions {
            require_literal_separator: false,
            require_literal_leading_dot: false,
            case_sensitive: true,
        };
        self.exclude
            .iter()
            .filter_map(|pattern| glob::Pattern::new(pattern).ok())
            .any(|pattern| pattern.matches_with(&as_text, options))
    }

    /// Make workspace-relative paths in the config absolute.
    ///
    /// A path in `.languagecheck.yaml` means "relative to the workspace",
    /// which is the only reading that makes sense to whoever wrote it. It was
    /// reaching Vale as written, and Vale is spawned by the core, whose
    /// working directory is wherever the editor started it -- so the
    /// documented `config: ".vale.ini"` worked from the CLI, where the two
    /// coincide, and silently did nothing in VS Code, where they do not. The
    /// dictionary paths were already resolved against the root; this brings
    /// the rest into line.
    ///
    /// An absolute path is left alone. So is an external provider's command
    /// when it is a bare name: that form is looked up on PATH, and making it
    /// workspace-relative would break the one spelling that has no reason to
    /// be.
    fn resolve_paths(&mut self, workspace_root: &Path) {
        let absolute = |value: &str| -> String {
            let path = Path::new(value);
            if path.is_absolute() {
                value.to_string()
            } else {
                workspace_root.join(path).to_string_lossy().into_owned()
            }
        };

        if let Some(vale_config) = &self.engines.vale.config {
            self.engines.vale.config = Some(absolute(vale_config));
        }
        if let Some(proselint_config) = &self.engines.proselint.config {
            self.engines.proselint.config = Some(absolute(proselint_config));
        }
        for plugin in &mut self.engines.wasm_plugins {
            plugin.path = absolute(&plugin.path);
        }
        for provider in &mut self.engines.external {
            // Only when it is written as a path. A bare name is looked up on
            // PATH, and turning `my-checker` into `<root>/my-checker` would
            // break the one form that has no reason to be workspace-relative.
            if provider.command.contains(std::path::MAIN_SEPARATOR)
                || provider.command.contains('/')
            {
                provider.command = absolute(&provider.command);
            }
        }
    }

    pub fn load(workspace_root: &Path) -> Result<Self> {
        // Prefer YAML, fall back to JSON for backward compatibility
        let yaml_path = workspace_root.join(".languagecheck.yaml");
        let yml_path = workspace_root.join(".languagecheck.yml");
        let json_path = workspace_root.join(".languagecheck.json");

        if yaml_path.exists() {
            let content = std::fs::read_to_string(yaml_path)?;
            warn_duplicate_rule_keys(&content);
            let mut config: Self = serde_yaml::from_str(&content)?;
            warn_unknown_keys(&serde_yaml::from_str(&content)?);
            config.resolve_paths(workspace_root);
            Ok(config)
        } else if yml_path.exists() {
            let content = std::fs::read_to_string(yml_path)?;
            warn_duplicate_rule_keys(&content);
            let mut config: Self = serde_yaml::from_str(&content)?;
            warn_unknown_keys(&serde_yaml::from_str(&content)?);
            config.resolve_paths(workspace_root);
            Ok(config)
        } else if json_path.exists() {
            let content = std::fs::read_to_string(json_path)?;
            let mut config: Self = serde_json::from_str(&content)?;
            // YAML 1.2 is a superset of JSON, so one key scanner covers both formats.
            warn_unknown_keys(&serde_yaml::from_str(&content)?);
            config.resolve_paths(workspace_root);
            Ok(config)
        } else {
            Ok(Self::default())
        }
    }

    /// Apply user-defined auto-fix rules to the given text, returning the modified text
    /// and the number of replacements made.
    #[must_use]
    pub fn apply_auto_fixes(&self, text: &str) -> (String, usize) {
        let mut result = text.to_string();
        let mut total = 0;

        for rule in &self.auto_fix {
            if let Some(ctx) = &rule.context
                && !result.contains(ctx.as_str())
            {
                continue;
            }
            let count = result.matches(&rule.find).count();
            if count > 0 {
                result = result.replace(&rule.find, &rule.replace);
                total += count;
            }
        }

        (result, total)
    }
}

/// Collect rule keys that appear more than once under the top-level `rules:`
/// mapping of a raw YAML config, in first-seen order.
///
/// `serde_yaml` silently keeps only the last value for a duplicated mapping
/// key, so duplicates vanish after parsing; this scans the raw text so they can
/// be surfaced. Recognizes block-style child keys (`  some.rule:` on its own
/// line) at the mapping's first child indentation.
fn duplicate_rule_keys(content: &str) -> Vec<String> {
    let mut in_rules = false;
    let mut child_indent: Option<usize> = None;
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut duplicates: Vec<String> = Vec::new();

    for line in content.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let indent = line.len() - line.trim_start().len();

        if !in_rules {
            if indent == 0 && line.trim() == "rules:" {
                in_rules = true;
            }
            continue;
        }

        // A new top-level key ends the rules block.
        if indent == 0 {
            break;
        }

        let child = *child_indent.get_or_insert(indent);
        if indent != child {
            continue; // deeper line (e.g. `severity: ...`), not a rule key
        }
        if let Some(key) = line.trim().strip_suffix(':') {
            let key = key.trim().to_string();
            if !key.is_empty() && !seen.insert(key.clone()) && !duplicates.contains(&key) {
                duplicates.push(key);
            }
        }
    }

    duplicates
}

/// Top-level keys [`Config`] understands.
const KNOWN_TOP_LEVEL_KEYS: &[&str] = &[
    "engines",
    "rules",
    "exclude",
    "auto_fix",
    "performance",
    "dictionaries",
    "languages",
    "workspace",
    "names",
    "morphology",
];

/// Keys [`EngineConfig`] understands, including the deprecated flat aliases.
const KNOWN_ENGINE_KEYS: &[&str] = &[
    "harper",
    "languagetool",
    "vale",
    "proselint",
    "hunspell",
    "external",
    "wasm_plugins",
    "spell_language",
    "languagetool_url",
    "vale_config",
];

/// Collect the keys of `value`'s `section` mapping that are not in `known`.
fn unknown_keys(value: &serde_yaml::Value, known: &[&str]) -> Vec<String> {
    let Some(map) = value.as_mapping() else {
        return Vec::new();
    };
    map.keys()
        .filter_map(serde_yaml::Value::as_str)
        .filter(|k| !known.contains(k))
        .map(ToString::to_string)
        .collect()
}

/// Warn about config keys nothing reads.
///
/// serde ignores what it does not recognise, so a typo'd or renamed key is
/// indistinguishable from an absent one: the setting simply never takes effect
/// and the user is left debugging the default. Reporting them turns a silent
/// no-op into a line in the log.
fn warn_unknown_keys(value: &serde_yaml::Value) {
    let unknown = unknown_keys(value, KNOWN_TOP_LEVEL_KEYS);
    if !unknown.is_empty() {
        warn!(keys = ?unknown, "Unknown keys in workspace config; they have no effect.");
    }
    if let Some(engines) = value.get("engines") {
        let unknown = unknown_keys(engines, KNOWN_ENGINE_KEYS);
        if !unknown.is_empty() {
            warn!(keys = ?unknown, "Unknown keys under `engines:`; they have no effect.");
        }
    }
}

/// Log a warning if a raw YAML config contains duplicate rule keys.
fn warn_duplicate_rule_keys(content: &str) {
    let duplicates = duplicate_rule_keys(content);
    if !duplicates.is_empty() {
        warn!(
            duplicates = ?duplicates,
            "Duplicate rule keys in .languagecheck.yaml; only the last entry for each takes \
             effect. Remove the extra copies to keep the ignore list clean."
        );
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            engines: EngineConfig::default(),
            rules: HashMap::new(),
            exclude: default_exclude(),
            auto_fix: Vec::new(),
            performance: PerformanceConfig::default(),
            dictionaries: DictionaryConfig::default(),
            languages: LanguageConfig::default(),
            workspace: WorkspaceConfig::default(),
            names: NameConfig::default(),
            morphology: MorphologyConfig::default(),
        }
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn every_engine_key_the_config_accepts_is_declared_known() {
        // A field that parses but is not listed here is reported to the user
        // as having no effect, which is the opposite of true and reads as the
        // feature being unsupported. Adding an engine means adding it twice,
        // so this is the reminder.
        let yaml = "\
engines:
  harper: false
  languagetool: false
  vale: false
  proselint: false
  hunspell:
    enabled: true
  spell_language: en-US
";
        let value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
        let engines = value.get("engines").expect("engines section");
        assert_eq!(
            unknown_keys(engines, KNOWN_ENGINE_KEYS),
            Vec::<String>::new(),
            "an engine key parses but is not declared known"
        );
    }
    use super::*;

    #[test]
    fn duplicate_rule_keys_detects_repeats() {
        let yaml = "rules:\n  languagetool.ARROWS:\n    severity: \"off\"\n  \
                    languagetool.UPPERCASE_SENTENCE_START:\n    severity: \"off\"\n  \
                    languagetool.ARROWS:\n    severity: \"off\"\n  \
                    languagetool.UPPERCASE_SENTENCE_START:\n    severity: \"off\"\n  \
                    languagetool.THE_SUPERLATIVE:\n    severity: \"off\"\n";
        let dups = duplicate_rule_keys(yaml);
        assert_eq!(
            dups,
            vec![
                "languagetool.ARROWS".to_string(),
                "languagetool.UPPERCASE_SENTENCE_START".to_string()
            ]
        );
    }

    #[test]
    fn duplicate_rule_keys_clean_list_is_empty() {
        let yaml = "rules:\n  a.B:\n    severity: \"off\"\n  c.D:\n    severity: \"off\"\n";
        assert!(duplicate_rule_keys(yaml).is_empty());
    }

    #[test]
    fn duplicate_rule_keys_stops_at_next_section() {
        // A repeat under a *different* top-level section must not count.
        let yaml = "rules:\n  a.B:\n    severity: \"off\"\nengines:\n  harper: false\n";
        assert!(duplicate_rule_keys(yaml).is_empty());
    }

    #[test]
    fn morphology_is_on_by_default() {
        let config = Config::default();
        assert!(config.morphology.enabled);
        assert!(config.morphology.inflections);
    }

    #[test]
    fn morphology_can_be_switched_off_from_yaml() {
        let yaml = "morphology:\n  enabled: false\n";
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(!config.morphology.enabled);
        // An unmentioned field keeps its default rather than falling to `false`.
        assert!(config.morphology.inflections);
    }

    #[test]
    fn default_dictionaries_load_all_bundled_sets() {
        let config = Config::default();
        assert!(config.dictionaries.bundled);
        assert!(config.dictionaries.disabled.is_empty());
        assert!(config.dictionaries.paths.is_empty());
    }

    #[test]
    fn dictionaries_disabled_from_yaml() {
        let config: Config = serde_yaml::from_str(
            r"
dictionaries:
  disabled: [companies, mathematics]
",
        )
        .unwrap();
        assert_eq!(config.dictionaries.disabled, ["companies", "mathematics"]);
        // The master switch is untouched by listing individual sets.
        assert!(config.dictionaries.bundled);
    }

    #[test]
    fn default_config_has_harper_enabled_lt_disabled() {
        let config = Config::default();
        assert!(config.engines.harper.enabled);
        assert!(!config.engines.languagetool.enabled);
    }

    #[test]
    fn default_config_has_standard_excludes() {
        let config = Config::default();
        assert!(config.exclude.contains(&"node_modules/**".to_string()));
        assert!(config.exclude.contains(&".git/**".to_string()));
        assert!(config.exclude.contains(&"target/**".to_string()));
        assert!(config.exclude.contains(&"dist/**".to_string()));
        assert!(config.exclude.contains(&"vendor/**".to_string()));
    }

    #[test]
    fn default_lt_url() {
        let config = Config::default();
        assert_eq!(config.engines.languagetool.url, "http://localhost:8010");
    }

    #[test]
    fn load_from_json_string() {
        let json = r#"{
            "engines": { "harper": true, "languagetool": false },
            "rules": { "spelling.typo": { "severity": "warning" } }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert!(config.engines.harper.enabled);
        assert!(!config.engines.languagetool.enabled);
        assert!(config.rules.contains_key("spelling.typo"));
        assert_eq!(
            config.rules["spelling.typo"].severity.as_deref(),
            Some("warning")
        );
    }

    #[test]
    fn load_partial_json_uses_defaults() {
        let json = r#"{}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert!(config.engines.harper.enabled);
        assert!(!config.engines.languagetool.enabled);
        assert!(config.rules.is_empty());
    }

    #[test]
    fn load_from_json_file() {
        let dir = std::env::temp_dir().join("lang_check_test_config_json");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let config_path = dir.join(".languagecheck.json");
        std::fs::write(
            &config_path,
            r#"{"engines": {"harper": false, "languagetool": true}}"#,
        )
        .unwrap();

        let config = Config::load(&dir).unwrap();
        assert!(!config.engines.harper.enabled);
        assert!(config.engines.languagetool.enabled);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_from_yaml_file() {
        let dir = std::env::temp_dir().join("lang_check_test_config_yaml");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let config_path = dir.join(".languagecheck.yaml");
        std::fs::write(
            &config_path,
            "engines:\n  harper: false\n  languagetool: true\n",
        )
        .unwrap();

        let config = Config::load(&dir).unwrap();
        assert!(!config.engines.harper.enabled);
        assert!(config.engines.languagetool.enabled);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn yaml_takes_precedence_over_json() {
        let dir = std::env::temp_dir().join("lang_check_test_config_precedence");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        // Write both files with different values
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            "engines:\n  harper: false\n",
        )
        .unwrap();
        std::fs::write(
            dir.join(".languagecheck.json"),
            r#"{"engines": {"harper": true}}"#,
        )
        .unwrap();

        let config = Config::load(&dir).unwrap();
        // YAML should win
        assert!(!config.engines.harper.enabled);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_missing_file_returns_default() {
        let dir = std::env::temp_dir().join("lang_check_test_config_missing");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let config = Config::load(&dir).unwrap();
        assert!(config.engines.harper.enabled);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn exclude_matches_a_path_relative_to_the_workspace() {
        let config = Config {
            exclude: vec!["drafts/**".to_string(), "node_modules/**".to_string()],
            ..Config::default()
        };
        let root = Path::new("/home/someone/project");

        assert!(config.excludes(&root.join("drafts/notes.md"), root));
        assert!(config.excludes(&root.join("node_modules/pkg/README.md"), root));
        assert!(!config.excludes(&root.join("docs/notes.md"), root));
    }

    #[test]
    fn exclude_accepts_a_path_that_is_already_relative() {
        // The indexer has relative paths and the editor absolute ones, and
        // both ask the same question.
        let config = Config {
            exclude: vec!["drafts/**".to_string()],
            ..Config::default()
        };
        let root = Path::new("/home/someone/project");
        assert!(config.excludes(Path::new("drafts/notes.md"), root));
    }

    #[test]
    fn exclude_matches_whichever_separator_the_platform_uses() {
        // The patterns are written with `/` on every platform; the path
        // arrives with the platform's own separator. Matching the two
        // literally meant `exclude` never matched anything on Windows.
        let config = Config {
            exclude: vec!["drafts/**".to_string()],
            ..Config::default()
        };
        let root = Path::new("/home/someone/project");
        let with_backslashes = root.join("drafts").join("notes.md");
        assert!(config.excludes(&with_backslashes, root));
    }

    #[test]
    fn an_empty_exclude_list_excludes_nothing() {
        let config = Config::default();
        let root = Path::new("/tmp");
        assert!(!config.excludes(&root.join("anything.md"), root));
    }

    #[test]
    fn a_malformed_pattern_excludes_nothing_rather_than_everything() {
        // Refusing to check a file because a glob had a typo is the worse of
        // the two failures: the user sees silence and no reason for it.
        let config = Config {
            exclude: vec!["[unclosed".to_string(), "drafts/**".to_string()],
            ..Config::default()
        };
        let root = Path::new("/tmp");
        assert!(!config.excludes(&root.join("notes.md"), root));
        assert!(config.excludes(&root.join("drafts/notes.md"), root));
    }

    #[test]
    fn a_relative_vale_config_is_resolved_against_the_workspace() {
        // Vale is spawned by the core, whose working directory is wherever
        // the editor started it. A path left as written reached Vale meaning
        // something else entirely, so `config: ".vale.ini"` -- the documented
        // form -- worked from the CLI and silently did nothing in VS Code.
        let dir = std::env::temp_dir().join(format!("lc_resolve_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            "engines:\n  vale:\n    enabled: true\n    config: \".vale.ini\"\n",
        )
        .unwrap();

        let config = Config::load(&dir).expect("config");
        let resolved = config.engines.vale.config.expect("a config path");
        assert!(
            Path::new(&resolved).is_absolute(),
            "left relative: {resolved}"
        );
        assert!(resolved.ends_with(".vale.ini"), "{resolved}");
        assert!(resolved.starts_with(&*dir.to_string_lossy()), "{resolved}");

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

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

        // Taken from the platform rather than written out. `/etc/vale.ini` is
        // absolute on Unix and merely rooted on Windows, where it has no drive
        // -- so it is resolved against the workspace's drive, correctly, and a
        // test that hard-coded it would be testing the wrong thing there.
        let elsewhere = std::env::temp_dir().join("vale.ini");
        let elsewhere = elsewhere.to_string_lossy().into_owned();
        // Single-quoted, because a backslash inside a double-quoted YAML
        // scalar is an escape and a Windows path is full of them.
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            format!("engines:\n  vale:\n    enabled: true\n    config: '{elsewhere}'\n"),
        )
        .unwrap();

        let config = Config::load(&dir).expect("config");
        assert_eq!(
            config.engines.vale.config.as_deref(),
            Some(elsewhere.as_str())
        );

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

    #[test]
    fn a_wasm_plugin_path_is_resolved_too() {
        // Same reasoning, same failure: a plugin named relative to the
        // workspace was looked for relative to the editor's cwd.
        let dir = std::env::temp_dir().join(format!("lc_resolve_wasm_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            "engines:\n  wasm_plugins:\n    - name: p\n      path: plugins/p.wasm\n",
        )
        .unwrap();

        let config = Config::load(&dir).expect("config");
        let resolved = &config.engines.wasm_plugins[0].path;
        assert!(
            Path::new(resolved).is_absolute(),
            "left relative: {resolved}"
        );
        // Compared with separators normalised: the join uses the platform's.
        assert!(
            resolved.replace('\\', "/").ends_with("plugins/p.wasm"),
            "{resolved}"
        );

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

    #[test]
    fn a_relative_proselint_config_is_resolved_too() {
        // Same shape as Vale's, spawned the same way, with the same failure.
        let dir = std::env::temp_dir().join(format!("lc_resolve_pl_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            "engines:\n  proselint:\n    enabled: true\n    config: \"proselint.json\"\n",
        )
        .unwrap();

        let config = Config::load(&dir).expect("config");
        let resolved = config.engines.proselint.config.expect("a config path");
        assert!(
            Path::new(&resolved).is_absolute(),
            "left relative: {resolved}"
        );
        assert!(resolved.ends_with("proselint.json"), "{resolved}");

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

    #[test]
    fn an_external_command_written_as_a_path_is_resolved() {
        let dir = std::env::temp_dir().join(format!("lc_resolve_ext_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            "engines:\n  external:\n    - name: c\n      command: ./my-checker\n",
        )
        .unwrap();

        let config = Config::load(&dir).expect("config");
        let command = &config.engines.external[0].command;
        assert!(Path::new(command).is_absolute(), "left relative: {command}");
        assert!(command.ends_with("my-checker"), "{command}");

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

    #[test]
    fn an_external_command_that_is_a_bare_name_is_left_for_path_lookup() {
        // The one spelling that must not be touched: `vale` means "whatever
        // PATH finds", and `<root>/vale` means a file that is not there.
        let dir = std::env::temp_dir().join(format!("lc_resolve_bare_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(".languagecheck.yaml"),
            "engines:\n  external:\n    - name: c\n      command: my-checker\n",
        )
        .unwrap();

        let config = Config::load(&dir).expect("config");
        assert_eq!(config.engines.external[0].command, "my-checker");

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

    #[test]
    fn auto_fix_simple_replacement() {
        let config = Config {
            auto_fix: vec![AutoFixRule {
                find: "teh".to_string(),
                replace: "the".to_string(),
                context: None,
                description: None,
            }],
            ..Config::default()
        };
        let (result, count) = config.apply_auto_fixes("Fix teh typo in teh text.");
        assert_eq!(result, "Fix the typo in the text.");
        assert_eq!(count, 2);
    }

    #[test]
    fn auto_fix_with_context_filter() {
        let config = Config {
            auto_fix: vec![AutoFixRule {
                find: "colour".to_string(),
                replace: "color".to_string(),
                context: Some("American".to_string()),
                description: Some("Use American spelling".to_string()),
            }],
            ..Config::default()
        };
        // Context matches — replacement should happen
        let (result, count) = config.apply_auto_fixes("American English: the colour is red.");
        assert_eq!(result, "American English: the color is red.");
        assert_eq!(count, 1);

        // Context does not match — no replacement
        let (result, count) = config.apply_auto_fixes("British English: the colour is red.");
        assert_eq!(result, "British English: the colour is red.");
        assert_eq!(count, 0);
    }

    #[test]
    fn auto_fix_no_match() {
        let config = Config {
            auto_fix: vec![AutoFixRule {
                find: "foo".to_string(),
                replace: "bar".to_string(),
                context: None,
                description: None,
            }],
            ..Config::default()
        };
        let (result, count) = config.apply_auto_fixes("No matches here.");
        assert_eq!(result, "No matches here.");
        assert_eq!(count, 0);
    }

    #[test]
    fn auto_fix_multiple_rules() {
        let config = Config {
            auto_fix: vec![
                AutoFixRule {
                    find: "recieve".to_string(),
                    replace: "receive".to_string(),
                    context: None,
                    description: None,
                },
                AutoFixRule {
                    find: "seperate".to_string(),
                    replace: "separate".to_string(),
                    context: None,
                    description: None,
                },
            ],
            ..Config::default()
        };
        let (result, count) = config.apply_auto_fixes("Please recieve the seperate package.");
        assert_eq!(result, "Please receive the separate package.");
        assert_eq!(count, 2);
    }

    #[test]
    fn auto_fix_loads_from_yaml() {
        let yaml = r#"
auto_fix:
  - find: "teh"
    replace: "the"
    description: "Fix common typo"
  - find: "colour"
    replace: "color"
    context: "American"
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.auto_fix.len(), 2);
        assert_eq!(config.auto_fix[0].find, "teh");
        assert_eq!(config.auto_fix[0].replace, "the");
        assert_eq!(
            config.auto_fix[0].description.as_deref(),
            Some("Fix common typo")
        );
        assert_eq!(config.auto_fix[1].context.as_deref(), Some("American"));
    }

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

    #[test]
    fn external_providers_from_yaml() {
        let yaml = r#"
engines:
  harper: true
  languagetool: false
  external:
    - name: vale
      command: /usr/bin/vale
      args: ["--output", "JSON"]
      extensions: [md, rst]
    - name: custom-checker
      command: ./my-checker
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.engines.external.len(), 2);
        assert_eq!(config.engines.external[0].name, "vale");
        assert_eq!(config.engines.external[0].command, "/usr/bin/vale");
        assert_eq!(config.engines.external[0].args, vec!["--output", "JSON"]);
        assert_eq!(config.engines.external[0].extensions, vec!["md", "rst"]);
        assert_eq!(config.engines.external[1].name, "custom-checker");
        assert!(config.engines.external[1].args.is_empty());
    }

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

    #[test]
    fn wasm_plugins_from_yaml() {
        let yaml = r#"
engines:
  harper: true
  wasm_plugins:
    - name: custom-checker
      path: .languagecheck/plugins/checker.wasm
      extensions: [md, html]
    - name: style-linter
      path: /opt/plugins/style.wasm
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.engines.wasm_plugins.len(), 2);
        assert_eq!(config.engines.wasm_plugins[0].name, "custom-checker");
        assert_eq!(
            config.engines.wasm_plugins[0].path,
            ".languagecheck/plugins/checker.wasm"
        );
        assert_eq!(
            config.engines.wasm_plugins[0].extensions,
            vec!["md", "html"]
        );
        assert_eq!(config.engines.wasm_plugins[1].name, "style-linter");
        assert!(config.engines.wasm_plugins[1].extensions.is_empty());
    }

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

    #[test]
    fn performance_config_defaults() {
        let config = Config::default();
        assert!(!config.performance.high_performance_mode);
        assert_eq!(config.performance.debounce_ms, 500);
        assert_eq!(config.performance.max_file_size, 0);
    }

    #[test]
    fn performance_config_from_yaml() {
        let yaml = r#"
performance:
  high_performance_mode: true
  debounce_ms: 500
  max_file_size: 1048576
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.performance.high_performance_mode);
        assert_eq!(config.performance.debounce_ms, 500);
        assert_eq!(config.performance.max_file_size, 1_048_576);
    }

    #[test]
    fn latex_skip_environments_from_yaml() {
        let yaml = r#"
languages:
  latex:
    skip_environments:
      - prooftree
      - mycustomenv
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(
            config.languages.latex.skip_environments,
            vec!["prooftree", "mycustomenv"]
        );
    }

    #[test]
    fn default_config_has_empty_latex_skip_environments() {
        let config = Config::default();
        assert!(config.languages.latex.skip_environments.is_empty());
    }

    #[test]
    fn latex_skip_commands_from_yaml() {
        let yaml = r#"
languages:
  latex:
    skip_commands:
      - codefont
      - myverb
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(
            config.languages.latex.skip_commands,
            vec!["codefont", "myverb"]
        );
    }

    #[test]
    fn default_spell_language_is_en_us() {
        let config = Config::default();
        assert_eq!(config.engines.spell_language, "en-US");
    }

    #[test]
    fn spell_language_from_yaml() {
        let yaml = r#"
engines:
  spell_language: de-DE
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.engines.spell_language, "de-DE");
    }

    #[test]
    fn default_config_has_empty_latex_skip_commands() {
        let config = Config::default();
        assert!(config.languages.latex.skip_commands.is_empty());
    }

    #[test]
    fn default_vale_is_disabled() {
        let config = Config::default();
        assert!(!config.engines.vale.enabled);
        assert!(config.engines.vale.config.is_none());
    }

    #[test]
    fn vale_bool_shorthand_from_yaml() {
        let yaml = r#"
engines:
  vale: true
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.vale.enabled);
    }

    #[test]
    fn vale_nested_config_from_yaml() {
        let yaml = r#"
engines:
  vale:
    enabled: true
    config: ".vale.ini"
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.vale.enabled);
        assert_eq!(config.engines.vale.config.as_deref(), Some(".vale.ini"));
    }

    #[test]
    fn harper_nested_config_from_yaml() {
        let yaml = r#"
engines:
  harper:
    enabled: true
    dialect: "British"
    linters:
      LongSentences: false
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.harper.enabled);
        assert_eq!(config.engines.harper.dialect, "British");
        assert_eq!(
            config.engines.harper.linters.get("LongSentences"),
            Some(&false)
        );
    }

    #[test]
    fn languagetool_nested_config_from_yaml() {
        let yaml = r#"
engines:
  languagetool:
    enabled: true
    url: "http://localhost:9090"
    level: "picky"
    disabled_rules:
      - WHITESPACE_RULE
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.languagetool.enabled);
        assert_eq!(config.engines.languagetool.url, "http://localhost:9090");
        assert_eq!(config.engines.languagetool.level, "picky");
        assert_eq!(
            config.engines.languagetool.disabled_rules,
            vec!["WHITESPACE_RULE"]
        );
        assert_eq!(config.engines.languagetool.max_concurrent_requests, 8);
    }

    /// Issue #86: the flat key our own docs advertised was dropped on the floor,
    /// so a self-hosted server was checked against `localhost:8010` instead.
    #[test]
    fn legacy_flat_languagetool_url_is_honoured() {
        let yaml = r#"
engines:
  spell_language: fr
  proselint: false
  vale: false
  languagetool: true
  languagetool_url: "http://10.0.10.3:8003"
  harper: false
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.languagetool.enabled);
        assert_eq!(config.engines.languagetool.url, "http://10.0.10.3:8003");
        assert_eq!(config.engines.spell_language, "fr");
        assert!(!config.engines.harper.enabled);
    }

    #[test]
    fn nested_languagetool_url_beats_the_legacy_key() {
        let yaml = r#"
engines:
  languagetool:
    enabled: true
    url: "http://nested:9090"
  languagetool_url: "http://flat:8003"
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.engines.languagetool.url, "http://nested:9090");
    }

    #[test]
    fn legacy_flat_vale_config_is_honoured() {
        let yaml = "engines:\n  vale: true\n  vale_config: \"config/.vale.ini\"\n";
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.vale.enabled);
        assert_eq!(
            config.engines.vale.config.as_deref(),
            Some("config/.vale.ini")
        );
    }

    #[test]
    fn unknown_keys_are_reported() {
        let value: serde_yaml::Value =
            serde_yaml::from_str("engines:\n  languagetol: true\n  harper: true\nrulez: {}\n")
                .unwrap();
        assert_eq!(unknown_keys(&value, KNOWN_TOP_LEVEL_KEYS), vec!["rulez"]);
        assert_eq!(
            unknown_keys(value.get("engines").unwrap(), KNOWN_ENGINE_KEYS),
            vec!["languagetol"]
        );
    }

    #[test]
    fn recognised_keys_are_not_reported() {
        let value: serde_yaml::Value = serde_yaml::from_str(
            "engines:\n  languagetool_url: \"http://x:1\"\n  harper: true\nrules: {}\n",
        )
        .unwrap();
        assert!(unknown_keys(&value, KNOWN_TOP_LEVEL_KEYS).is_empty());
        assert!(unknown_keys(value.get("engines").unwrap(), KNOWN_ENGINE_KEYS).is_empty());
    }

    #[test]
    fn languagetool_concurrency_can_be_pinned_to_serial() {
        // Shared or rate-limited servers need the old one-at-a-time behaviour back.
        let yaml = r"
engines:
  languagetool:
    enabled: true
    max_concurrent_requests: 1
";
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.engines.languagetool.max_concurrent_requests, 1);
    }

    #[test]
    fn default_proselint_is_disabled() {
        let config = Config::default();
        assert!(!config.engines.proselint.enabled);
        assert!(config.engines.proselint.config.is_none());
    }

    #[test]
    fn proselint_bool_shorthand_from_yaml() {
        let yaml = r#"
engines:
  proselint: true
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.proselint.enabled);
    }

    #[test]
    fn proselint_nested_config_from_yaml() {
        let yaml = r#"
engines:
  proselint:
    enabled: true
    config: "proselint.json"
"#;
        let config: Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.engines.proselint.enabled);
        assert_eq!(
            config.engines.proselint.config.as_deref(),
            Some("proselint.json")
        );
    }
}