adotenv-lint 0.4.0

Opt-in lint rules, schema checks and verified fixes for adotenv documents.
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
//! Opt-in lint rules, schema checks and verified fixes for [`adotenv`] documents.
//!
//! The linter is deliberately separate from the parser. A lint finding is
//! policy, not a parse error, and every suggested fix is applied through
//! `adotenv`'s verified edit or format APIs.
//!
//! The default rule set reports duplicate keys only. Enable ordering, key
//! case, quoting, whitespace, or [`Schema`] / `.env.example` rules explicitly
//! through [`LintOptions`], [`lint_with_schema`], and [`lint_with_options`].
//!
//! ```
//! use adotenv_lint::{lint, LintOptions};
//!
//! let doc = adotenv::parse_strict("B=2\nA=1\n").unwrap();
//! let defaults = lint(&doc, LintOptions::default());
//! assert!(defaults.is_empty());
//!
//! let findings = lint(
//!     &doc,
//!     LintOptions::default().with_key_order(true),
//! );
//! assert_eq!(findings.len(), 1);
//! assert_eq!(findings[0].rule(), adotenv_lint::Rule::KeyOrder);
//! ```

pub mod config;
pub mod schema;

#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctests {}

pub use adotenv::EditOptions;
pub use config::{
    discover_config, load_effective_config, parse_dialect, parse_equals_spacing, parse_key_case,
    parse_output_format, parse_quote_style, ConfigError, ConfigExplicit, IgnoredPaths,
    KeySchemaConfig, LintConfig, LintPolicy, OutputFormat, RuleSeverity, SchemaConfig,
};
pub use schema::{KeySchema, Schema, ValueShape};

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::ops::Range;

use adotenv::{
    parse_strict_with_options, parse_with_options, BlankLines, ColumnEncoding, Diagnostic, Dialect,
    Document, Edit, EditError, EqualsSpacing, FinalNewline, FormatError, FormatOptions,
    FormatResult, InsertPosition, LineIndex, ParseOptions, Quote, QuoteStyle, Severity,
    VerifiedEdits,
};

/// The policy rules understood by the linter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rule {
    /// A key is declared more than once.
    DuplicateKey,
    /// Keys are not in the configured order.
    KeyOrder,
    /// A key does not use the configured ASCII case.
    KeyCase,
    /// A value does not use the configured quote style.
    QuoteStyle,
    /// Spacing around `=` or trailing whitespace differs from the policy.
    Whitespace,
    /// A required key declared by a [`Schema`] is absent from the document.
    MissingKey,
    /// A key declared in the document is absent from a closed [`Schema`].
    UnknownKey,
    /// A key has an empty or disallowed bare value under a [`Schema`].
    EmptyValue,
    /// A key's literal value does not match its [`Schema`] [`ValueShape`] or
    /// literal bounds.
    InvalidValue,
    /// A key declared in the document is marked deprecated in the [`Schema`].
    DeprecatedKey,
}

/// Offline documentation metadata for one lint [`Rule`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct RuleExplanation {
    /// Stable kebab-case rule identifier (matches [`Rule::as_str`]).
    pub id: &'static str,
    /// Short one-line summary suitable for listings and SARIF `shortDescription`.
    pub summary: &'static str,
    /// Default activation and severity summary.
    pub default_behavior: &'static str,
    /// Autofix capability summary.
    pub autofix: &'static str,
    /// Relevant `.adotenv-lint.toml` and CLI configuration keys.
    pub config: &'static str,
    /// Rationale explaining what the rule checks and why.
    pub rationale: &'static str,
}

impl Rule {
    /// Every lint rule supported by this crate in stable documentation order.
    pub const ALL: &'static [Self] = &[
        Self::DuplicateKey,
        Self::KeyOrder,
        Self::KeyCase,
        Self::QuoteStyle,
        Self::Whitespace,
        Self::MissingKey,
        Self::UnknownKey,
        Self::EmptyValue,
        Self::InvalidValue,
        Self::DeprecatedKey,
    ];

    const fn index(self) -> usize {
        match self {
            Self::DuplicateKey => 0,
            Self::KeyOrder => 1,
            Self::KeyCase => 2,
            Self::QuoteStyle => 3,
            Self::Whitespace => 4,
            Self::MissingKey => 5,
            Self::UnknownKey => 6,
            Self::EmptyValue => 7,
            Self::InvalidValue => 8,
            Self::DeprecatedKey => 9,
        }
    }

    /// Returns the stable rule identifier.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DuplicateKey => "duplicate-key",
            Self::KeyOrder => "key-order",
            Self::KeyCase => "key-case",
            Self::QuoteStyle => "quote-style",
            Self::Whitespace => "whitespace",
            Self::MissingKey => "missing-key",
            Self::UnknownKey => "unknown-key",
            Self::EmptyValue => "empty-value",
            Self::InvalidValue => "invalid-value",
            Self::DeprecatedKey => "deprecated-key",
        }
    }

    /// Parses a stable kebab-case rule identifier.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "duplicate-key" => Some(Self::DuplicateKey),
            "key-order" => Some(Self::KeyOrder),
            "key-case" => Some(Self::KeyCase),
            "quote-style" => Some(Self::QuoteStyle),
            "whitespace" => Some(Self::Whitespace),
            "missing-key" => Some(Self::MissingKey),
            "unknown-key" => Some(Self::UnknownKey),
            "empty-value" => Some(Self::EmptyValue),
            "invalid-value" => Some(Self::InvalidValue),
            "deprecated-key" => Some(Self::DeprecatedKey),
            _ => None,
        }
    }

    /// Returns structured offline documentation for this rule.
    #[must_use]
    pub const fn explain(self) -> RuleExplanation {
        match self {
            Self::DuplicateKey => RuleExplanation {
                id: "duplicate-key",
                summary: "Reports keys declared more than once in the same document.",
                default_behavior: "on (warning)",
                autofix: "none",
                config: "[rules] duplicate-key = \"off\" | \"warning\" | \"error\"",
                rationale: "Repeated declarations are usually accidental and make effective values depend on the active dialect's duplicate-key policy.",
            },
            Self::KeyOrder => RuleExplanation {
                id: "key-order",
                summary: "Reports declaration groups whose keys are not in sorted order.",
                default_behavior: "off (warning when enabled)",
                autofix: "verified sort (when group has no reference cycle or limit exceeded)",
                config: "key_order = true, [rules] key-order, CLI --key-order",
                rationale: "Keeping each blank-line-separated group sorted reduces merge conflicts and makes large .env files easier to scan while preserving reference dependencies.",
            },
            Self::KeyCase => RuleExplanation {
                id: "key-case",
                summary: "Reports keys that do not match the configured ASCII letter case.",
                default_behavior: "off (warning when enabled)",
                autofix: "verified rename",
                config: "key_case = \"upper\" | \"lower\", [rules] key-case = \"off\" | \"warning\" | \"error\", CLI --key-case",
                rationale: "Consistent key casing avoids subtle mismatches across shells, deployment platforms, and case-sensitive environments.",
            },
            Self::QuoteStyle => RuleExplanation {
                id: "quote-style",
                summary: "Reports non-empty values that do not use the configured quote style.",
                default_behavior: "preserve (warning when enabled)",
                autofix: "verified format (two-pass when unquoting with trivia options)",
                config: "quote_style = \"double\" | \"single\" | \"unquoted\" | \"preserve\", [rules] quote-style, CLI --quote-style",
                rationale: "Enforcing a uniform quoting style prevents accidental expansion or escape differences when values are edited.",
            },
            Self::Whitespace => RuleExplanation {
                id: "whitespace",
                summary: "Reports non-normalized assignment spacing or trailing whitespace.",
                default_behavior: "preserve (warning when enabled)",
                autofix: "verified format",
                config: "equals_spacing = \"none\" | \"spaces\" | \"preserve\", trim_trailing_whitespace = true, [rules] whitespace, CLI --equals-spacing / --trim-trailing-whitespace",
                rationale: "Normalizing spacing around assignment separators and trimming trailing horizontal whitespace eliminates noisy diffs.",
            },
            Self::MissingKey => RuleExplanation {
                id: "missing-key",
                summary: "Reports required keys declared in a Schema or .env.example that are absent.",
                default_behavior: "schema opt-in (warning when a schema is active)",
                autofix: "verified empty placeholder insert (KEY=); explicit via apply_fix, apply_batch_with_policy, or CLI --fix --fix-missing",
                config: "[schema] example = \".env.example\", [schema.keys.<KEY>] required = true, [rules] missing-key, CLI --example / --fix-missing",
                rationale: "Catching missing required keys before deployment prevents startup failures without ever exposing or copying secret values.",
            },
            Self::UnknownKey => RuleExplanation {
                id: "unknown-key",
                summary: "Reports keys absent from a closed Schema (allow_unknown = false).",
                default_behavior: "schema opt-in (warning when allow_unknown = false)",
                autofix: "none",
                config: "[schema] allow_unknown = false, [rules] unknown-key, CLI --no-unknown-keys",
                rationale: "Rejecting undeclared keys catches typos and stale variables that are no longer read by the application.",
            },
            Self::EmptyValue => RuleExplanation {
                id: "empty-value",
                summary: "Reports disallowed empty (KEY=) or bare (KEY) declarations under a Schema.",
                default_behavior: "schema opt-in (warning when a schema disallows empty or bare values)",
                autofix: "none",
                config: "[schema] allow_empty = false, [schema.keys.<KEY>] allow_empty / allow_bare, [rules] empty-value, CLI --no-empty-values",
                rationale: "Typed keys and strict schemas often require explicit non-empty values rather than blank placeholders or bare declarations.",
            },
            Self::InvalidValue => RuleExplanation {
                id: "invalid-value",
                summary: "Reports decoded literal values failing their Schema ValueShape or literal bounds.",
                default_behavior: "schema opt-in (warning when a schema defines shapes or bounds)",
                autofix: "none",
                config: "[schema.keys.<KEY>] shape / one_of / prefix / suffix / min_len / max_len, [rules] invalid-value",
                rationale: "Validates literal values (such as ports, URLs, IP addresses, hosts, socket addresses, emails, enums, prefixes, suffixes, and length bounds) without expanding references or printing values.",
            },
            Self::DeprecatedKey => RuleExplanation {
                id: "deprecated-key",
                summary: "Reports declared keys marked deprecated in the active Schema.",
                default_behavior: "schema opt-in (warning when a schema key sets deprecated)",
                autofix: "none",
                config: "[schema.keys.<KEY>] deprecated = true | \"reason\" (typically with required = false), [rules] deprecated-key",
                rationale: "Surfaces migrations away from legacy environment variable names directly in CI and editors without exposing values.",
            },
        }
    }
}

/// The desired ASCII case for keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum KeyCase {
    /// Do not check key case.
    #[default]
    Off,
    /// Require lowercase ASCII letters.
    Lower,
    /// Require uppercase ASCII letters.
    Upper,
}

/// Linter policy.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct LintOptions {
    /// Report later declarations of a repeated key.
    pub duplicate_keys: bool,
    /// Require each group's declarations to be in key order.
    ///
    /// A group that `Document::sort` cannot reorder, such as one with a
    /// self-reference or a reference cycle, is still reported, with no fix
    /// attached.
    pub key_order: bool,
    /// Require a key case.
    pub key_case: KeyCase,
    /// Require a quote style for non-empty values.
    pub quote_style: QuoteStyle,
    /// Require a spacing policy around assignment separators.
    pub equals_spacing: EqualsSpacing,
    /// Remove trailing spaces and tabs.
    pub trim_trailing_whitespace: bool,
    /// Report missing required keys when a [`Schema`] is supplied.
    pub missing_keys: bool,
    /// Report undeclared keys when a [`Schema`] sets `allow_unknown = false`.
    pub unknown_keys: bool,
    /// Report disallowed empty or bare values when a [`Schema`] is supplied.
    pub empty_values: bool,
    /// Report values failing their configured [`ValueShape`] or literal bounds
    /// when a [`Schema`] is supplied.
    pub invalid_values: bool,
    /// Report declared keys marked deprecated when a [`Schema`] is supplied.
    pub deprecated_keys: bool,
    severities: [Severity; 10],
}

impl Default for LintOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl LintOptions {
    /// Creates the conservative default policy: duplicate-key checks only when
    /// no [`Schema`] is supplied, with schema rules enabled when a [`Schema`]
    /// is passed to [`lint_with_schema`] or [`lint_with_options`].
    #[must_use]
    pub const fn new() -> Self {
        Self {
            duplicate_keys: true,
            key_order: false,
            key_case: KeyCase::Off,
            quote_style: QuoteStyle::Preserve,
            equals_spacing: EqualsSpacing::Preserve,
            trim_trailing_whitespace: false,
            missing_keys: true,
            unknown_keys: true,
            empty_values: true,
            invalid_values: true,
            deprecated_keys: true,
            severities: [Severity::Warning; 10],
        }
    }
    /// Enables or disables duplicate-key findings.
    #[must_use]
    pub const fn with_duplicate_keys(mut self, value: bool) -> Self {
        self.duplicate_keys = value;
        self
    }
    /// Enables or disables key-order findings.
    #[must_use]
    pub const fn with_key_order(mut self, value: bool) -> Self {
        self.key_order = value;
        self
    }
    /// Sets the key-case policy.
    #[must_use]
    pub const fn with_key_case(mut self, value: KeyCase) -> Self {
        self.key_case = value;
        self
    }
    /// Sets the quote-style policy.
    #[must_use]
    pub const fn with_quote_style(mut self, value: QuoteStyle) -> Self {
        self.quote_style = value;
        self
    }
    /// Sets the assignment-spacing policy.
    #[must_use]
    pub const fn with_equals_spacing(mut self, value: EqualsSpacing) -> Self {
        self.equals_spacing = value;
        self
    }
    /// Enables or disables trailing-whitespace findings.
    #[must_use]
    pub const fn with_trim_trailing_whitespace(mut self, value: bool) -> Self {
        self.trim_trailing_whitespace = value;
        self
    }
    /// Enables or disables missing-key schema findings.
    #[must_use]
    pub const fn with_missing_keys(mut self, value: bool) -> Self {
        self.missing_keys = value;
        self
    }
    /// Enables or disables unknown-key schema findings.
    #[must_use]
    pub const fn with_unknown_keys(mut self, value: bool) -> Self {
        self.unknown_keys = value;
        self
    }
    /// Enables or disables empty- and bare-value schema findings.
    #[must_use]
    pub const fn with_empty_values(mut self, value: bool) -> Self {
        self.empty_values = value;
        self
    }
    /// Enables or disables invalid-value schema findings.
    #[must_use]
    pub const fn with_invalid_values(mut self, value: bool) -> Self {
        self.invalid_values = value;
        self
    }
    /// Enables or disables deprecated-key schema findings.
    #[must_use]
    pub const fn with_deprecated_keys(mut self, value: bool) -> Self {
        self.deprecated_keys = value;
        self
    }
    /// Sets the severity reported for one rule.
    #[must_use]
    pub const fn with_severity(mut self, rule: Rule, severity: Severity) -> Self {
        self.severities[rule.index()] = severity;
        self
    }
    /// Returns the configured severity for one rule.
    #[must_use]
    pub const fn severity_for_rule(self, rule: Rule) -> Severity {
        self.severities[rule.index()]
    }
    fn format_options(self) -> FormatOptions {
        FormatOptions::default()
            .with_quote_style(self.quote_style)
            .with_equals_spacing(self.equals_spacing)
            .with_trim_trailing_whitespace(self.trim_trailing_whitespace)
    }
}

/// A structured lint finding.
///
/// Findings never contain values: only the rule, message, optional value-free
/// detail, key and source span are retained. A finding may include a fix that
/// can be applied through [`apply_fix`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    rule: Rule,
    message: &'static str,
    detail: Option<String>,
    severity: Severity,
    span: Range<usize>,
    line: usize,
    key: Option<String>,
    fix: Option<Fix>,
}

impl Finding {
    pub(crate) fn new(
        rule: Rule,
        message: &'static str,
        severity: Severity,
        span: Range<usize>,
        line: usize,
        key: Option<&str>,
        fix: Option<Fix>,
    ) -> Self {
        Self::with_detail(rule, message, severity, span, line, key, None, fix)
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn with_detail(
        rule: Rule,
        message: &'static str,
        severity: Severity,
        span: Range<usize>,
        line: usize,
        key: Option<&str>,
        detail: Option<&str>,
        fix: Option<Fix>,
    ) -> Self {
        Self {
            rule,
            message,
            detail: detail.map(str::to_owned),
            severity,
            span,
            line,
            key: key.map(str::to_owned),
            fix,
        }
    }
    /// Returns the rule that produced this finding.
    #[must_use]
    pub const fn rule(&self) -> Rule {
        self.rule
    }
    /// Returns the stable, value-free message.
    #[must_use]
    pub const fn message(&self) -> &'static str {
        self.message
    }
    /// Returns optional value-free detail (such as a schema deprecation note or
    /// literal bound expectation), when present.
    #[must_use]
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }
    /// Returns the configured finding severity; warnings by default.
    #[must_use]
    pub const fn severity(&self) -> Severity {
        self.severity
    }
    /// Returns the byte range of the finding in the document source.
    #[must_use]
    pub fn span(&self) -> Range<usize> {
        self.span.clone()
    }
    /// Returns the one-based line of the finding.
    #[must_use]
    pub const fn line(&self) -> usize {
        self.line
    }
    /// Returns the key named by the finding, when there is one.
    #[must_use]
    pub fn key(&self) -> Option<&str> {
        self.key.as_deref()
    }
    /// Returns a verified-fix request for this finding, when one is available.
    #[must_use]
    pub const fn fix(&self) -> Option<&Fix> {
        self.fix.as_ref()
    }
}

/// A fix request for an [`adotenv`] document.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fix {
    /// Sort each group through [`Document::sort`].
    Sort,
    /// Apply a format policy through [`Document::format`].
    Format(FormatOptions),
    /// Rename one declaration through [`Edit::Rename`].
    Rename {
        /// The zero-based entry ID.
        entry: usize,
        /// The replacement key.
        key: String,
    },
    /// Insert a missing required key with an empty value (`KEY=`) through
    /// [`Edit::Insert`]. Never copies values from `.env.example`.
    InsertEmpty {
        /// The missing key name to insert.
        key: String,
    },
}

/// Policy controlling staged batch fix application in
/// [`apply_batch_with_policy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct BatchOptions {
    /// Bounds forwarded to [`Document::edit_with_options`],
    /// [`Document::sort_with_options`], and [`Document::format_with_options`].
    pub edit_options: EditOptions,
    /// Whether [`Fix::InsertEmpty`] scaffolding fixes are applied during batch
    /// runs. Defaults to `false` so automatic style batches and LSP
    /// `source.fixAll` never insert empty `KEY=` stubs unless opted in.
    pub insert_missing: bool,
}

impl BatchOptions {
    /// Creates default batch options (`insert_missing = false`).
    #[must_use]
    pub const fn new() -> Self {
        Self {
            edit_options: EditOptions::new(),
            insert_missing: false,
        }
    }

    /// Sets the [`EditOptions`] limits enforced on every batch stage.
    #[must_use]
    pub const fn with_edit_options(mut self, edit_options: EditOptions) -> Self {
        self.edit_options = edit_options;
        self
    }

    /// Enables or disables applying [`Fix::InsertEmpty`] fixes in this batch.
    #[must_use]
    pub const fn with_insert_missing(mut self, insert_missing: bool) -> Self {
        self.insert_missing = insert_missing;
        self
    }
}

/// A successfully applied fix.
#[derive(Debug)]
#[non_exhaustive]
pub enum FixResult {
    /// The verified result of [`Document::sort`] or [`Document::format`].
    Format(FormatResult),
    /// The verified result of an edit batch.
    Edits(VerifiedEdits),
}

impl FixResult {
    /// Returns the complete verified output text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Format(result) => result.as_str(),
            Self::Edits(result) => result.as_str(),
        }
    }
    /// Returns the verified text edits.
    #[must_use]
    pub fn edits(&self) -> &[adotenv::TextEdit] {
        match self {
            Self::Format(result) => result.edits(),
            Self::Edits(result) => result.edits(),
        }
    }
}

/// The result of applying compatible fixes in stages.
///
/// Each stage is verified against the source at the start of that stage. The
/// final [`output`](Self::output) is the complete result; stage edits are
/// relative to their own stage input, not to the original source.
#[derive(Debug)]
pub struct BatchResult {
    output: String,
    stages: Vec<FixResult>,
    empty: bool,
}

impl BatchResult {
    /// Returns the final verified output text.
    #[must_use]
    pub fn output(&self) -> &str {
        &self.output
    }
    /// Returns the verified stages in application order.
    #[must_use]
    pub fn stages(&self) -> &[FixResult] {
        &self.stages
    }
    /// Returns `true` when no fix changed anything.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.empty
    }
}

struct PlannedFixes {
    renames: Vec<(usize, String)>,
    inserts: Vec<String>,
    format: Option<FormatOptions>,
    sort: bool,
}

fn plan_fixes(fixes: &[Fix]) -> Result<PlannedFixes, LintError> {
    let mut renames: Vec<(usize, String)> = Vec::new();
    let mut rename_positions: BTreeMap<usize, usize> = BTreeMap::new();
    let mut inserts: Vec<String> = Vec::new();
    let mut seen_inserts: BTreeSet<&str> = BTreeSet::new();
    let mut format = None;
    let mut sort = false;
    for fix in fixes {
        match fix {
            Fix::Rename { entry, key } => {
                if let Some(&pos) = rename_positions.get(entry) {
                    if renames[pos].1 != *key {
                        return Err(LintError::Conflict(
                            "one entry has two different replacement keys",
                        ));
                    }
                    continue;
                }
                rename_positions.insert(*entry, renames.len());
                renames.push((*entry, key.clone()));
            }
            Fix::InsertEmpty { key } => {
                if seen_inserts.insert(key.as_str()) {
                    inserts.push(key.clone());
                }
            }
            Fix::Format(options) => {
                if format.is_some_and(|existing: FormatOptions| existing != *options) {
                    return Err(LintError::Conflict(
                        "different format policies cannot be combined",
                    ));
                }
                format = Some(*options);
            }
            Fix::Sort => sort = true,
        }
    }
    Ok(PlannedFixes {
        renames,
        inserts,
        format,
        sort,
    })
}

fn parse_strict_bounded(
    source: &str,
    dialect: Dialect,
    limits: ParseOptions,
) -> Result<Document<'_>, LintError> {
    if limits.max_diagnostics.is_some() {
        let (document, diagnostics) = parse_with_options(source, dialect, limits);
        if let Some(limit) = diagnostics.iter().find_map(Diagnostic::limit) {
            return Err(LintError::Edit(EditError::Limit(limit)));
        }
        if diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity() == Severity::Error)
        {
            return Err(LintError::Parse);
        }
        return Ok(document);
    }
    parse_strict_with_options(source, dialect, limits).map_err(|error| map_parse_error(&error))
}

fn map_format_edit_error(error: EditError) -> LintError {
    match error {
        EditError::WouldChangeMeaning => LintError::Format(FormatError::WouldChangeMeaning),
        other => LintError::Edit(other),
    }
}

fn map_parse_error(error: &Diagnostic) -> LintError {
    error.limit().map_or(LintError::Parse, |limit| {
        LintError::Edit(EditError::Limit(limit))
    })
}

fn needs_two_pass_unquote(options: FormatOptions) -> bool {
    options.quote_style == QuoteStyle::Unquoted
        && (options.equals_spacing != EqualsSpacing::Preserve
            || options.trim_trailing_whitespace
            || options.blank_lines != BlankLines::Preserve
            || options.final_newline != FinalNewline::Preserve)
}

/// Applies renames, sorting and formatting in compatible stages.
///
/// Renames are applied together in one edit batch. Sorting and one format
/// policy can follow; each stage is verified before the next starts. Different
/// format policies and conflicting replacement keys are rejected. When a format
/// policy combines [`QuoteStyle::Unquoted`] with other trivia rewrites,
/// unquoting runs in its own verified stage before the remaining formatting.
/// This is the multi-stage companion to [`apply_fixes`].
///
/// # Errors
///
/// Returns [`LintError`] for conflicting fixes, a rejected edit/format, or an
/// intermediate output that cannot be parsed.
pub fn apply_batch(document: &Document<'_>, fixes: &[Fix]) -> Result<BatchResult, LintError> {
    apply_batch_with_options(document, fixes, EditOptions::new())
}

/// Applies renames, sorting and formatting in compatible stages while
/// enforcing [`EditOptions`] output, reference-scan and verification limits.
///
/// [`Fix::InsertEmpty`] fixes are skipped by default so automatic style batches
/// (and LSP `source.fixAll`) remain non-structural; call
/// [`apply_batch_with_policy`] with [`BatchOptions::with_insert_missing`] set
/// to `true` to also insert missing required keys.
///
/// # Errors
///
/// Returns [`LintError::Edit`] with [`EditError::Limit`] when any configured
/// output, reference or parse limit is exceeded, [`LintError::Conflict`] for
/// incompatible fixes, [`LintError::Format`] when formatting/sorting is
/// refused, or [`LintError::Parse`] when an intermediate output fails strict
/// parsing for non-limit diagnostics.
pub fn apply_batch_with_options(
    document: &Document<'_>,
    fixes: &[Fix],
    edit_options: EditOptions,
) -> Result<BatchResult, LintError> {
    apply_batch_with_policy(
        document,
        fixes,
        BatchOptions::new().with_edit_options(edit_options),
    )
}

/// Applies compatible fixes in verified stages according to [`BatchOptions`].
///
/// Stages run in order: renames, optional missing-key placeholder insertions
/// (only when [`BatchOptions::insert_missing`] is `true`, skipping any key
/// already present after renames), sorting, and formatting (splitting
/// [`QuoteStyle::Unquoted`] into its own stage when combined with trivia
/// rewrites).
///
/// # Errors
///
/// Returns [`LintError`] on conflicting fixes, exceeded [`EditOptions`] limits,
/// rejected edits/formats, or an intermediate output that cannot be parsed.
#[allow(clippy::too_many_lines)]
pub fn apply_batch_with_policy(
    document: &Document<'_>,
    fixes: &[Fix],
    batch_options: BatchOptions,
) -> Result<BatchResult, LintError> {
    let PlannedFixes {
        renames,
        inserts,
        format,
        sort,
    } = plan_fixes(fixes)?;
    let edit_options = batch_options.edit_options;
    let mut output = document.source().to_owned();
    let mut stages = Vec::new();
    if !renames.is_empty() {
        let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
        let edits: Vec<Edit<'_>> = renames
            .iter()
            .map(|(entry, key)| Edit::Rename { entry: *entry, key })
            .collect();
        let result = current
            .edit_with_options(&edits, edit_options)
            .map_err(LintError::Edit)?;
        output.clear();
        output.push_str(result.as_str());
        stages.push(FixResult::Edits(result));
    }
    if batch_options.insert_missing && !inserts.is_empty() {
        let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
        let existing: BTreeSet<&str> = current.entries().map(adotenv::Entry::key).collect();
        let pending: Vec<Edit<'_>> = inserts
            .iter()
            .filter(|key| !existing.contains(key.as_str()))
            .map(|key| Edit::Insert {
                key,
                value: Some(""),
                position: InsertPosition::End,
            })
            .collect();
        if !pending.is_empty() {
            let result = current
                .edit_with_options(&pending, edit_options)
                .map_err(LintError::Edit)?;
            output.clear();
            output.push_str(result.as_str());
            stages.push(FixResult::Edits(result));
        }
    }
    if sort {
        let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
        let result = current
            .sort_with_options(edit_options)
            .map_err(map_format_edit_error)?;
        output.clear();
        output.push_str(result.as_str());
        stages.push(FixResult::Format(result));
    }
    if let Some(options) = format {
        if needs_two_pass_unquote(options) {
            let unquote_only = FormatOptions::default().with_quote_style(QuoteStyle::Unquoted);
            let rest = options.with_quote_style(QuoteStyle::Preserve);
            let current =
                parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
            let pass1 = current
                .format_with_options(&unquote_only, edit_options)
                .map_err(map_format_edit_error)?;
            let pass1_changed = !pass1.is_empty();
            if pass1_changed {
                output.clear();
                output.push_str(pass1.as_str());
                stages.push(FixResult::Format(pass1));
                let mid =
                    parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
                let pass2 = mid
                    .format_with_options(&rest, edit_options)
                    .map_err(map_format_edit_error)?;
                if !pass2.is_empty() {
                    output.clear();
                    output.push_str(pass2.as_str());
                    stages.push(FixResult::Format(pass2));
                }
            } else {
                let pass2 = current
                    .format_with_options(&rest, edit_options)
                    .map_err(map_format_edit_error)?;
                output.clear();
                output.push_str(pass2.as_str());
                stages.push(FixResult::Format(pass2));
            }
        } else {
            let current =
                parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
            let result = current
                .format_with_options(&options, edit_options)
                .map_err(map_format_edit_error)?;
            output.clear();
            output.push_str(result.as_str());
            stages.push(FixResult::Format(result));
        }
    }
    Ok(BatchResult {
        empty: output == document.source(),
        output,
        stages,
    })
}

/// An error while applying a lint fix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LintError {
    /// The formatter or sorter refused the output.
    Format(FormatError),
    /// The verified edit batch was rejected (including [`EditError::Limit`]).
    Edit(EditError),
    /// The supplied fixes cannot be combined in one verified batch.
    Conflict(&'static str),
    /// An intermediate verified output could not be parsed again.
    Parse,
}

impl fmt::Display for LintError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Format(error) => write!(formatter, "cannot apply fix: {error}"),
            Self::Edit(error) => write!(formatter, "cannot apply fix: {error}"),
            Self::Conflict(message) => write!(formatter, "cannot combine fixes: {message}"),
            Self::Parse => formatter.write_str("cannot parse an intermediate fix output"),
        }
    }
}

impl std::error::Error for LintError {}

/// Applies one fix request through the document's verified APIs.
///
/// Format fixes run a single pass of [`Document::format`]. When a policy
/// combines [`QuoteStyle::Unquoted`] with other trivia options, use
/// [`apply_batch`] or [`apply_batch_with_options`] so unquoting runs in its
/// own verified stage before the remaining trivia rewrites.
///
/// # Errors
///
/// Returns [`LintError`] when the formatter/sorter refuses the output or the
/// edit batch is rejected, for example because a rename would collide.
pub fn apply_fix(document: &Document<'_>, fix: &Fix) -> Result<FixResult, LintError> {
    apply_fix_with_options(document, fix, EditOptions::new())
}

/// Applies one fix request through the document's bounded verified APIs.
///
/// Format fixes run a single pass of [`Document::format_with_options`]. When a
/// policy combines [`QuoteStyle::Unquoted`] with other trivia options, use
/// [`apply_batch_with_options`] so unquoting runs in its own verified stage
/// before the remaining trivia rewrites.
///
/// # Errors
///
/// Returns [`LintError::Edit`] with [`EditError::Limit`] when a configured
/// [`EditOptions`] limit is exceeded, [`LintError::Format`] when the formatter
/// or sorter refuses the output, or [`LintError::Edit`] when an edit is
/// rejected.
pub fn apply_fix_with_options(
    document: &Document<'_>,
    fix: &Fix,
    edit_options: EditOptions,
) -> Result<FixResult, LintError> {
    match fix {
        Fix::Sort => document
            .sort_with_options(edit_options)
            .map(FixResult::Format)
            .map_err(map_format_edit_error),
        Fix::Format(options) => document
            .format_with_options(options, edit_options)
            .map(FixResult::Format)
            .map_err(map_format_edit_error),
        Fix::Rename { entry, key } => document
            .edit_with_options(&[Edit::Rename { entry: *entry, key }], edit_options)
            .map(FixResult::Edits)
            .map_err(LintError::Edit),
        Fix::InsertEmpty { key } => document
            .edit_with_options(
                &[Edit::Insert {
                    key,
                    value: Some(""),
                    position: InsertPosition::End,
                }],
                edit_options,
            )
            .map(FixResult::Edits)
            .map_err(LintError::Edit),
    }
}

/// Applies a batch of compatible fixes in one verified operation.
///
/// Multiple renames and empty-key insertions are applied as one
/// [`Document::edit`] batch, so swaps and independent edits are verified
/// together. One formatting or sorting fix can be applied without edits. Mixed
/// edit/format/sort batches and multiple different format policies return
/// [`LintError::Conflict`]; apply those with [`apply_batch`] or
/// [`apply_batch_with_policy`] (which also splits combined
/// [`QuoteStyle::Unquoted`] + trivia policies into two verified stages) or in
/// separate rounds.
///
/// # Errors
///
/// Returns [`LintError`] when the fixes conflict, a rename or insertion
/// collides, or the formatter/sorter refuses the output.
pub fn apply_fixes(document: &Document<'_>, fixes: &[Fix]) -> Result<FixResult, LintError> {
    apply_fixes_with_options(document, fixes, EditOptions::new())
}

/// Applies a batch of compatible fixes in one bounded verified operation.
///
/// This is [`apply_fixes`] with [`EditOptions`] forwarded to
/// [`Document::edit_with_options`], [`Document::format_with_options`], or
/// [`Document::sort_with_options`].
///
/// # Errors
///
/// Returns [`LintError::Edit`] with [`EditError::Limit`] when a configured
/// [`EditOptions`] limit is exceeded, [`LintError::Conflict`] when fixes cannot
/// be combined, [`LintError::Format`] when formatting/sorting is refused, or
/// [`LintError::Edit`] when an edit is rejected.
pub fn apply_fixes_with_options(
    document: &Document<'_>,
    fixes: &[Fix],
    edit_options: EditOptions,
) -> Result<FixResult, LintError> {
    let PlannedFixes {
        renames,
        inserts,
        format,
        sort,
    } = plan_fixes(fixes)?;
    let has_edits = !renames.is_empty() || !inserts.is_empty();
    if has_edits && (format.is_some() || sort) {
        return Err(LintError::Conflict(if inserts.is_empty() {
            "renames cannot be combined with formatting or sorting"
        } else {
            "edits cannot be combined with formatting or sorting"
        }));
    }
    if sort && format.is_some() {
        return Err(LintError::Conflict(
            "sorting and formatting cannot be combined in one batch",
        ));
    }
    if has_edits {
        let mut edits: Vec<Edit<'_>> = Vec::with_capacity(renames.len() + inserts.len());
        edits.extend(
            renames
                .iter()
                .map(|(entry, key)| Edit::Rename { entry: *entry, key }),
        );
        edits.extend(inserts.iter().map(|key| Edit::Insert {
            key,
            value: Some(""),
            position: InsertPosition::End,
        }));
        return document
            .edit_with_options(&edits, edit_options)
            .map(FixResult::Edits)
            .map_err(LintError::Edit);
    }
    if let Some(options) = format {
        return document
            .format_with_options(&options, edit_options)
            .map(FixResult::Format)
            .map_err(map_format_edit_error);
    }
    if sort {
        return document
            .sort_with_options(edit_options)
            .map(FixResult::Format)
            .map_err(map_format_edit_error);
    }
    document
        .edit_with_options(&[], edit_options)
        .map(FixResult::Edits)
        .map_err(LintError::Edit)
}

/// Runs the configured lint rules over `document`.
///
/// Findings are ordered by source position. A finding is policy, not a parse
/// error; parse diagnostics remain available through [`adotenv::parse`].
#[must_use]
pub fn lint(document: &Document<'_>, options: LintOptions) -> Vec<Finding> {
    lint_with_options(document, options, None, EditOptions::new())
}

/// Runs the configured lint rules and an opt-in [`Schema`] policy over
/// `document`.
///
/// Schema findings never contain document values. Missing-key findings attach
/// [`Fix::InsertEmpty`] (which inserts an empty `KEY=` placeholder without
/// copying `.env.example` values and is skipped by [`apply_batch`] unless
/// opted in via [`apply_batch_with_policy`]); all other schema findings have
/// no automatic fix.
#[must_use]
pub fn lint_with_schema(
    document: &Document<'_>,
    options: LintOptions,
    schema: &Schema,
) -> Vec<Finding> {
    lint_with_options(document, options, Some(schema), EditOptions::new())
}

/// Runs the configured lint rules and optional [`Schema`] policy over
/// `document`, using `edit_options` to bound sortability verification for
/// [`Rule::KeyOrder`].
///
/// When `edit_options` prevents a group from being sorted (for example because
/// `max_references` is exceeded), [`Rule::KeyOrder`] still reports the unsorted
/// group without attaching [`Fix::Sort`].
#[must_use]
pub fn lint_with_options(
    document: &Document<'_>,
    options: LintOptions,
    schema: Option<&Schema>,
    edit_options: EditOptions,
) -> Vec<Finding> {
    let line_index = document.line_index();
    let mut findings = Vec::new();

    if options.duplicate_keys {
        let mut entries: BTreeMap<&str, Vec<adotenv::Entry<'_>>> = BTreeMap::new();
        for entry in document.entries() {
            entries.entry(entry.key()).or_default().push(entry);
        }
        for group in entries.values().filter(|group| group.len() > 1) {
            for entry in group.iter().skip(1) {
                findings.push(Finding::new(
                    Rule::DuplicateKey,
                    "key is declared more than once",
                    options.severity_for_rule(Rule::DuplicateKey),
                    entry.key_span(),
                    entry.line(),
                    Some(entry.key()),
                    None,
                ));
            }
        }
    }

    if options.key_order {
        key_order_findings(document, options, edit_options, &line_index, &mut findings);
    }

    for entry in document.entries() {
        if options.key_case != KeyCase::Off {
            let expected = match options.key_case {
                KeyCase::Off => entry.key().to_owned(),
                KeyCase::Lower => entry.key().to_ascii_lowercase(),
                KeyCase::Upper => entry.key().to_ascii_uppercase(),
            };
            if expected != entry.key() {
                findings.push(Finding::new(
                    Rule::KeyCase,
                    "key does not use the configured case",
                    options.severity_for_rule(Rule::KeyCase),
                    entry.key_span(),
                    entry.line(),
                    Some(entry.key()),
                    Some(Fix::Rename {
                        entry: entry.id(),
                        key: expected,
                    }),
                ));
            }
        }

        if let Some(value) = entry.value() {
            if !value.is_empty() {
                let expected = match options.quote_style {
                    QuoteStyle::Double => Quote::Double,
                    QuoteStyle::Single => Quote::Single,
                    QuoteStyle::Unquoted => Quote::None,
                    _ => entry.quote(),
                };
                if entry.quote() != expected {
                    findings.push(Finding::new(
                        Rule::QuoteStyle,
                        "value does not use the configured quote style",
                        options.severity_for_rule(Rule::QuoteStyle),
                        entry.value_span().unwrap_or_else(|| entry.key_span()),
                        entry.line(),
                        Some(entry.key()),
                        Some(Fix::Format(options.format_options())),
                    ));
                }
            }
        }

        if whitespace_differs(document, entry, options) {
            findings.push(Finding::new(
                Rule::Whitespace,
                "assignment spacing or trailing whitespace is not normalized",
                options.severity_for_rule(Rule::Whitespace),
                entry.tokens().key.clone(),
                entry.line(),
                Some(entry.key()),
                Some(Fix::Format(options.format_options())),
            ));
        }
    }

    if let Some(schema) = schema {
        schema::schema_findings(document, options, schema, &mut findings);
    }

    findings.sort_by(|left, right| {
        left.span
            .start
            .cmp(&right.span.start)
            .then_with(|| left.rule.as_str().cmp(right.rule.as_str()))
            .then_with(|| left.key.cmp(&right.key))
    });
    findings
}

fn whitespace_differs(
    document: &Document<'_>,
    entry: adotenv::Entry<'_>,
    options: LintOptions,
) -> bool {
    let tokens = entry.tokens();
    if let Some(_separator) = tokens.eq.as_ref() {
        let before = &document.source()[tokens.space_before_eq.clone()];
        let after = &document.source()[tokens.space_after_eq.clone()];
        match options.equals_spacing {
            EqualsSpacing::None if !before.is_empty() || !after.is_empty() => return true,
            EqualsSpacing::Spaces if before != " " || after != " " => return true,
            _ => {}
        }
    }
    options.trim_trailing_whitespace && !tokens.trailing_space.is_empty()
}

fn key_order_findings(
    document: &Document<'_>,
    options: LintOptions,
    edit_options: EditOptions,
    line_index: &LineIndex<'_>,
    findings: &mut Vec<Finding>,
) {
    // A group that `Document::sort_with_options` refuses to reorder, for example
    // one with a self-reference, a cycle, or an exceeded limit, still has an
    // observable key order. Report it, but only attach the sorting fix when a
    // sort edit exists.
    let sortable = document
        .sort_with_options(edit_options)
        .map(|sorted| {
            sorted
                .edits()
                .iter()
                .map(|edit| edit.range.clone())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    for group in document.groups() {
        let entries: Vec<_> = group.entries().collect();
        if entries.len() < 2 {
            continue;
        }
        let keys: Vec<&str> = entries.iter().map(|entry| entry.key()).collect();
        if keys.windows(2).all(|pair| pair[0] <= pair[1]) {
            continue;
        }
        if keys.iter().any(|key| key.is_empty()) || duplicate_keys(&keys) {
            // Duplicate and empty keys belong to the duplicate-key rule, and
            // `Document::sort` never reorders them.
            continue;
        }
        if group.items().any(|item| {
            !matches!(
                item.kind(),
                adotenv::ItemKind::Entry | adotenv::ItemKind::Comment
            )
        }) {
            continue;
        }
        let span = group.span();
        let fix = sortable.contains(&span).then_some(Fix::Sort);
        findings.push(Finding::new(
            Rule::KeyOrder,
            "declarations are not sorted",
            options.severity_for_rule(Rule::KeyOrder),
            span.clone(),
            line_of(line_index, span.start),
            None,
            fix,
        ));
    }
}

fn duplicate_keys(keys: &[&str]) -> bool {
    let mut seen = BTreeSet::new();
    !keys.iter().all(|key| seen.insert(*key))
}

fn line_of(index: &LineIndex<'_>, offset: usize) -> usize {
    index
        .to_position(offset, ColumnEncoding::Utf8)
        .map_or(1, |position| position.line + 1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use adotenv::{parse_strict, parse_with, Dialect};

    #[test]
    fn defaults_report_only_duplicate_keys() {
        let doc = parse_strict("B=2\nA=1\nA=3\n").unwrap();
        let findings = lint(&doc, LintOptions::default());
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule(), Rule::DuplicateKey);
        assert_eq!(findings[0].line(), 3);
        assert_eq!(findings[0].key(), Some("A"));
    }

    #[test]
    fn key_order_fix_sorts_through_verified_output() {
        let doc = parse_strict("B=2\nA=1\n").unwrap();
        let findings = lint(&doc, LintOptions::new().with_key_order(true));
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule(), Rule::KeyOrder);
        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
        assert_eq!(fixed.as_str(), "A=1\nB=2\n");
    }

    #[test]
    fn key_order_reports_unsortable_groups_without_a_fix() {
        for source in ["B=$B\nA=1\n", "B='$A'\nA=1\n", "B=$A\nA=$B\n"] {
            let doc = parse_strict(source).unwrap();
            let findings = lint(&doc, LintOptions::new().with_key_order(true));
            assert_eq!(findings.len(), 1, "{source:?}");
            assert_eq!(findings[0].rule(), Rule::KeyOrder, "{source:?}");
            assert!(findings[0].fix().is_none(), "{source:?}");
        }
    }

    #[test]
    fn key_case_fix_renames_one_declaration() {
        let doc = parse_strict("lower=1\n").unwrap();
        let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
        assert_eq!(findings.len(), 1);
        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
        assert_eq!(fixed.as_str(), "LOWER=1\n");
    }

    #[test]
    fn quote_style_fix_is_verified() {
        let doc = parse_strict("A='one'\n").unwrap();
        let findings = lint(
            &doc,
            LintOptions::new().with_quote_style(QuoteStyle::Double),
        );
        assert_eq!(findings.len(), 1);
        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
        assert_eq!(fixed.as_str(), "A=\"one\"\n");
    }

    #[test]
    fn whitespace_fix_uses_verified_formatting() {
        let doc = parse_strict("A =  one   \n").unwrap();
        let findings = lint(
            &doc,
            LintOptions::new()
                .with_equals_spacing(EqualsSpacing::None)
                .with_trim_trailing_whitespace(true),
        );
        assert_eq!(findings.len(), 1);
        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
        assert_eq!(fixed.as_str(), "A=one\n");
    }

    #[test]
    fn findings_never_contain_values() {
        let doc = parse_strict("TOKEN=secret\nTOKEN=other\n").unwrap();
        let findings = lint(&doc, LintOptions::default());
        let debug = format!("{findings:?}");
        assert!(!debug.contains("secret"));
        assert!(!debug.contains("other"));
        assert!(debug.contains("TOKEN"));
    }

    #[test]
    fn rename_collision_returns_a_structured_error() {
        let doc = parse_strict("A=1\na=2\n").unwrap();
        let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
        let fix = findings
            .iter()
            .find_map(Finding::fix)
            .expect("the lowercase key has a fix");
        assert!(matches!(
            apply_fix(&doc, fix),
            Err(LintError::Edit(EditError::Duplicate(_)))
        ));
    }

    #[test]
    fn python_quoted_keys_keep_their_case_policy() {
        let doc = parse_with("'A B'=1\n", Dialect::PYTHON_DOTENV).0;
        let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
        assert_eq!(findings.len(), 0);
    }
}

#[cfg(test)]
use adotenv::parse_strict;

#[test]
fn apply_fixes_batches_independent_renames() {
    let doc = parse_strict("a=1\nb=2\n").unwrap();
    let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
    let fixes: Vec<Fix> = findings
        .iter()
        .filter_map(|finding| finding.fix().cloned())
        .collect();
    assert_eq!(fixes.len(), 2);
    let result = apply_fixes(&doc, &fixes).unwrap();
    assert_eq!(result.as_str(), "A=1\nB=2\n");
}

#[test]
fn apply_fixes_reports_mixed_fix_conflicts() {
    let doc = parse_strict("A='one'\n").unwrap();
    let fixes = [
        Fix::Rename {
            entry: 0,
            key: "B".to_owned(),
        },
        Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double)),
    ];
    assert!(matches!(
        apply_fixes(&doc, &fixes),
        Err(LintError::Conflict(
            "renames cannot be combined with formatting or sorting"
        ))
    ));
}

#[test]
fn apply_fixes_reports_two_keys_for_one_entry() {
    let doc = parse_strict("a=1\n").unwrap();
    let fixes = [
        Fix::Rename {
            entry: 0,
            key: "A".to_owned(),
        },
        Fix::Rename {
            entry: 0,
            key: "B".to_owned(),
        },
    ];
    assert!(matches!(
        apply_fixes(&doc, &fixes),
        Err(LintError::Conflict(
            "one entry has two different replacement keys"
        ))
    ));
}

#[test]
fn rule_severity_is_configurable() {
    let doc = parse_strict("A=1\nA=2\n").unwrap();
    let findings = lint(
        &doc,
        LintOptions::new().with_severity(Rule::DuplicateKey, Severity::Error),
    );
    assert_eq!(findings[0].severity(), Severity::Error);
}

#[test]
fn apply_batch_combines_renames_sorting_and_formatting() {
    let doc = parse_strict("b='two'\na='one'\n").unwrap();
    let findings = lint(
        &doc,
        LintOptions::new()
            .with_key_case(KeyCase::Upper)
            .with_key_order(true)
            .with_quote_style(QuoteStyle::Double),
    );
    let fixes: Vec<Fix> = findings
        .iter()
        .filter_map(|finding| finding.fix().cloned())
        .collect();
    let result = apply_batch(&doc, &fixes).unwrap();
    assert_eq!(result.output(), "A=\"one\"\nB=\"two\"\n");
    assert_eq!(result.stages().len(), 3);
}

#[test]
fn apply_batch_rejects_conflicting_renames() {
    let doc = parse_strict("a=1\n").unwrap();
    let fixes = [
        Fix::Rename {
            entry: 0,
            key: "A".to_owned(),
        },
        Fix::Rename {
            entry: 0,
            key: "B".to_owned(),
        },
    ];
    assert!(matches!(
        apply_batch(&doc, &fixes),
        Err(LintError::Conflict(
            "one entry has two different replacement keys"
        ))
    ));
}

#[test]
fn apply_batch_rejects_different_format_policies() {
    let doc = parse_strict("A='one'\n").unwrap();
    let fixes = [
        Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double)),
        Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Single)),
    ];
    assert!(matches!(
        apply_batch(&doc, &fixes),
        Err(LintError::Conflict(
            "different format policies cannot be combined"
        ))
    ));
}

#[test]
fn apply_batch_without_fixes_is_empty() {
    let doc = parse_strict("A=1\n").unwrap();
    let result = apply_batch(&doc, &[]).unwrap();
    assert!(result.is_empty());
    assert_eq!(result.output(), "A=1\n");
}

#[test]
fn apply_batch_reports_no_change_for_a_noop_format() {
    let doc = parse_strict("A='one'\n").unwrap();
    let result = apply_batch(&doc, &[Fix::Format(FormatOptions::default())]).unwrap();
    assert!(result.is_empty());
    assert_eq!(result.output(), "A='one'\n");
}

#[test]
fn mutation_regression_assertions_for_rules_whitespace_quotes_and_order() {
    use adotenv::parse_strict;

    // 1. Distinct Rule::index slots in LintOptions::with_severity.
    let opts = LintOptions::new()
        .with_severity(Rule::DuplicateKey, Severity::Error)
        .with_severity(Rule::KeyOrder, Severity::Info)
        .with_severity(Rule::KeyCase, Severity::Error)
        .with_severity(Rule::QuoteStyle, Severity::Info)
        .with_severity(Rule::Whitespace, Severity::Error);
    assert_eq!(opts.severity_for_rule(Rule::DuplicateKey), Severity::Error);
    assert_eq!(opts.severity_for_rule(Rule::KeyOrder), Severity::Info);
    assert_eq!(opts.severity_for_rule(Rule::KeyCase), Severity::Error);
    assert_eq!(opts.severity_for_rule(Rule::QuoteStyle), Severity::Info);
    assert_eq!(opts.severity_for_rule(Rule::Whitespace), Severity::Error);

    // 2. Finding::message, FixResult::edits, BatchResult::is_empty, LintError::fmt.
    let dup_doc = parse_strict("A=1\nA=2\n").unwrap();
    let dup_findings = lint(&dup_doc, LintOptions::default());
    assert_eq!(dup_findings[0].message(), "key is declared more than once");

    let rename_doc = parse_strict("a=1\n").unwrap();
    let rename_fix = Fix::Rename {
        entry: 0,
        key: "A".to_owned(),
    };
    let fixed = apply_fix(&rename_doc, &rename_fix).unwrap();
    assert_eq!(fixed.edits().len(), 1);
    let batched = apply_batch(&rename_doc, &[rename_fix]).unwrap();
    assert!(!batched.is_empty());
    assert_eq!(
        LintError::Conflict("conflict reason").to_string(),
        "cannot combine fixes: conflict reason"
    );

    // 3. apply_fixes with standalone Fix::Sort and standalone Fix::Format.
    let unsorted = parse_strict("B=2\nA=1\n").unwrap();
    let sorted = apply_fixes(&unsorted, &[Fix::Sort]).unwrap();
    assert_eq!(sorted.as_str(), "A=1\nB=2\n");

    // 4. QuoteStyle::Single and QuoteStyle::Unquoted detection.
    let quoted = parse_strict("A=\"one\"\n").unwrap();
    let single_findings = lint(
        &quoted,
        LintOptions::new().with_quote_style(QuoteStyle::Single),
    );
    assert_eq!(single_findings.len(), 1);
    assert_eq!(single_findings[0].rule(), Rule::QuoteStyle);
    let unquoted_findings = lint(
        &quoted,
        LintOptions::new().with_quote_style(QuoteStyle::Unquoted),
    );
    assert_eq!(unquoted_findings.len(), 1);
    assert_eq!(unquoted_findings[0].rule(), Rule::QuoteStyle);

    // 5. whitespace_differs: EqualsSpacing::None / Spaces (before & after) and trailing space.
    let eq_none = LintOptions::new().with_equals_spacing(EqualsSpacing::None);
    assert_eq!(lint(&parse_strict("A=1\n").unwrap(), eq_none), Vec::new());
    assert_eq!(lint(&parse_strict("A =1\n").unwrap(), eq_none).len(), 1);
    assert_eq!(lint(&parse_strict("A= 1\n").unwrap(), eq_none).len(), 1);

    let eq_spaces = LintOptions::new().with_equals_spacing(EqualsSpacing::Spaces);
    assert_eq!(
        lint(&parse_strict("A = 1\n").unwrap(), eq_spaces),
        Vec::new()
    );
    assert_eq!(lint(&parse_strict("A= 1\n").unwrap(), eq_spaces).len(), 1);
    assert_eq!(lint(&parse_strict("A =1\n").unwrap(), eq_spaces).len(), 1);

    let trim_off = LintOptions::new().with_trim_trailing_whitespace(false);
    let trim_on = LintOptions::new().with_trim_trailing_whitespace(true);
    assert_eq!(lint(&parse_strict("A=1 \n").unwrap(), trim_off), Vec::new());
    assert_eq!(lint(&parse_strict("A=1\n").unwrap(), trim_on), Vec::new());
    assert_eq!(lint(&parse_strict("A=1 \n").unwrap(), trim_on).len(), 1);

    // 6. key_order_findings: 3-entry group, duplicate-key skip, and line_of (> line 1).
    let order_only = LintOptions::new()
        .with_duplicate_keys(false)
        .with_key_order(true);
    let three = parse_strict("# header\n\nC=3\nB=2\nA=1\n").unwrap();
    let three_findings = lint(&three, order_only);
    assert_eq!(three_findings.len(), 1);
    assert_eq!(three_findings[0].line(), 3);

    let with_dups = parse_strict("B=2\nA=1\nA=3\n").unwrap();
    assert_eq!(lint(&with_dups, order_only), Vec::new());
}

#[test]
fn all_ten_rule_indices_names_and_explanations_are_complete() {
    assert_eq!(Rule::ALL.len(), 10);
    let opts = LintOptions::new()
        .with_severity(Rule::DuplicateKey, Severity::Error)
        .with_severity(Rule::KeyOrder, Severity::Info)
        .with_severity(Rule::KeyCase, Severity::Error)
        .with_severity(Rule::QuoteStyle, Severity::Info)
        .with_severity(Rule::Whitespace, Severity::Error)
        .with_severity(Rule::MissingKey, Severity::Info)
        .with_severity(Rule::UnknownKey, Severity::Error)
        .with_severity(Rule::EmptyValue, Severity::Info)
        .with_severity(Rule::InvalidValue, Severity::Error)
        .with_severity(Rule::DeprecatedKey, Severity::Info);
    assert_eq!(opts.severity_for_rule(Rule::MissingKey), Severity::Info);
    assert_eq!(opts.severity_for_rule(Rule::UnknownKey), Severity::Error);
    assert_eq!(opts.severity_for_rule(Rule::EmptyValue), Severity::Info);
    assert_eq!(opts.severity_for_rule(Rule::InvalidValue), Severity::Error);
    assert_eq!(opts.severity_for_rule(Rule::DeprecatedKey), Severity::Info);
    assert_eq!(Rule::MissingKey.as_str(), "missing-key");
    assert_eq!(Rule::UnknownKey.as_str(), "unknown-key");
    assert_eq!(Rule::EmptyValue.as_str(), "empty-value");
    assert_eq!(Rule::InvalidValue.as_str(), "invalid-value");
    assert_eq!(Rule::DeprecatedKey.as_str(), "deprecated-key");

    let mut seen_ids = BTreeSet::new();
    for (idx, &rule) in Rule::ALL.iter().enumerate() {
        assert_eq!(rule.index(), idx);
        assert_eq!(Rule::from_name(rule.as_str()), Some(rule));
        let info = rule.explain();
        assert_eq!(info.id, rule.as_str());
        assert!(seen_ids.insert(info.id));
        assert_ne!(info.summary, "");
        assert_ne!(info.default_behavior, "");
        assert_ne!(info.autofix, "");
        assert_ne!(info.config, "");
        assert_ne!(info.rationale, "");
    }
    assert_eq!(Rule::from_name("not-a-rule"), None);
}

#[test]
fn bounded_apply_fix_fixes_and_batch_enforce_edit_options() {
    use adotenv::{LimitKind, ParseOptions};

    let doc = parse_strict("a='one'\n").unwrap();
    let double = Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double));
    let rename = Fix::Rename {
        entry: 0,
        key: "LONG_KEY_NAME".to_owned(),
    };

    // Output-byte cap on apply_fix_with_options (format and rename).
    let tight_bytes = EditOptions::new().with_max_output_bytes(10);
    assert!(matches!(
        apply_fix_with_options(&doc, &rename, tight_bytes),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
    ));
    let spacing = Fix::Format(FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces));
    assert!(matches!(
        apply_fix_with_options(&doc, &spacing, EditOptions::new().with_max_output_bytes(8)),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
    ));
    assert!(matches!(
        apply_fixes_with_options(
            &doc,
            std::slice::from_ref(&spacing),
            EditOptions::new().with_max_output_bytes(8)
        ),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
    ));
    assert!(matches!(
        apply_batch_with_options(&doc, &[rename, double], tight_bytes),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
    ));

    // Output-line cap on apply_fix_with_options.
    let two_lines = parse_strict("B=2\nA=1\n").unwrap();
    assert!(matches!(
        apply_fix_with_options(
            &two_lines,
            &Fix::Sort,
            EditOptions::new().with_max_output_lines(1),
        ),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::Lines
    ));

    // Reference cap bounds both lint_with_options (KeyOrder fix attachment) and apply_fix/batch.
    let with_ref = parse_strict("C=3\nB=$A\nA=1\n").unwrap();
    let no_refs = EditOptions::new().with_max_references(0);
    let limited_findings = lint_with_options(
        &with_ref,
        LintOptions::new().with_key_order(true),
        None,
        no_refs,
    );
    assert_eq!(limited_findings.len(), 1);
    assert_eq!(limited_findings[0].rule(), Rule::KeyOrder);
    assert!(limited_findings[0].fix().is_none());

    let bounded_ok = lint_with_options(
        &with_ref,
        LintOptions::new().with_key_order(true),
        None,
        EditOptions::new().with_max_references(2),
    );
    assert_eq!(bounded_ok.len(), 1);
    assert_eq!(bounded_ok[0].fix(), Some(&Fix::Sort));

    assert!(matches!(
        apply_fix_with_options(&with_ref, &Fix::Sort, no_refs),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
    ));
    assert!(matches!(
        apply_fixes_with_options(&with_ref, &[Fix::Sort], no_refs),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
    ));
    assert!(matches!(
        apply_batch_with_options(&with_ref, &[Fix::Sort], no_refs),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
    ));

    // Parse-limit cap during apply_batch_with_options maps to EditError::Limit, not Parse.
    let parse_limited = EditOptions::new().with_parse_limits(ParseOptions::new().with_max_lines(1));
    assert!(matches!(
        apply_batch_with_options(&two_lines, &[Fix::Sort], parse_limited),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::Lines
    ));

    // Non-limit parse failure in apply_batch_with_options still maps to LintError::Parse.
    let (invalid_doc, _) = adotenv::parse("BAD LINE\nB=2\nA=1\n");
    assert_eq!(
        apply_batch_with_options(&invalid_doc, &[Fix::Sort], EditOptions::new()).unwrap_err(),
        LintError::Parse
    );
}

#[test]
fn apply_batch_handles_two_pass_unquoted_with_trivia_and_renames() {
    let doc = parse_strict("b = \"two\"   \na = \"one\"\n").unwrap();
    let policy = LintOptions::new()
        .with_key_case(KeyCase::Upper)
        .with_key_order(true)
        .with_quote_style(QuoteStyle::Unquoted)
        .with_equals_spacing(EqualsSpacing::None)
        .with_trim_trailing_whitespace(true);
    let findings = lint(&doc, policy);
    let fixes: Vec<Fix> = findings
        .iter()
        .filter_map(|finding| finding.fix().cloned())
        .collect();
    let batch = apply_batch(&doc, &fixes).unwrap();
    assert_eq!(batch.output(), "A=one\nB=two\n");
    assert!(!batch.is_empty());

    // Pass 1 (unquote) empty, pass 2 (trivia) changes spacing.
    let spacing_only = parse_strict("A = plain   \n").unwrap();
    let fmt_fix = Fix::Format(
        FormatOptions::default()
            .with_quote_style(QuoteStyle::Unquoted)
            .with_equals_spacing(EqualsSpacing::None)
            .with_trim_trailing_whitespace(true),
    );
    let res1 = apply_batch(&spacing_only, std::slice::from_ref(&fmt_fix)).unwrap();
    assert_eq!(res1.output(), "A=plain\n");
    assert_eq!(res1.stages().len(), 1);

    // Pass 1 (unquote) changes quotes, pass 2 (trivia) is already normalized.
    let unquote_only = parse_strict("A=\"plain\"\n").unwrap();
    let res2 = apply_batch(&unquote_only, std::slice::from_ref(&fmt_fix)).unwrap();
    assert_eq!(res2.output(), "A=plain\n");
    assert_eq!(res2.stages().len(), 1);

    // Both passes no-op -> empty batch.
    let clean = parse_strict("A=plain\n").unwrap();
    let res3 = apply_batch(&clean, &[fmt_fix]).unwrap();
    assert!(res3.is_empty());
    assert_eq!(res3.output(), "A=plain\n");

    // Each trivia option combined individually with QuoteStyle::Unquoted uses two-pass convergence.
    let eq_doc = parse_strict("A = \"plain\"\n").unwrap();
    let eq_res = apply_batch(
        &eq_doc,
        &[Fix::Format(
            FormatOptions::default()
                .with_quote_style(QuoteStyle::Unquoted)
                .with_equals_spacing(EqualsSpacing::None),
        )],
    )
    .unwrap();
    assert_eq!(eq_res.output(), "A=plain\n");
    assert_eq!(eq_res.stages().len(), 2);

    let trim_doc = parse_strict("A=\"plain\"   \n").unwrap();
    let trim_res = apply_batch(
        &trim_doc,
        &[Fix::Format(
            FormatOptions::default()
                .with_quote_style(QuoteStyle::Unquoted)
                .with_trim_trailing_whitespace(true),
        )],
    )
    .unwrap();
    assert_eq!(trim_res.output(), "A=plain\n");
    assert_eq!(trim_res.stages().len(), 2);

    let blank_doc = parse_strict("A=\"plain\"\n\n\nB=2\n").unwrap();
    let blank_res = apply_batch(
        &blank_doc,
        &[Fix::Format(
            FormatOptions::default()
                .with_quote_style(QuoteStyle::Unquoted)
                .with_blank_lines(BlankLines::Collapse),
        )],
    )
    .unwrap();
    assert_eq!(blank_res.output(), "A=plain\n\nB=2\n");
    assert_eq!(blank_res.stages().len(), 2);

    let nl_doc = parse_strict("A=\"plain\"").unwrap();
    let nl_res = apply_batch(
        &nl_doc,
        &[Fix::Format(
            FormatOptions::default()
                .with_quote_style(QuoteStyle::Unquoted)
                .with_final_newline(FinalNewline::Ensure),
        )],
    )
    .unwrap();
    assert_eq!(nl_res.output(), "A=plain\n");
    assert_eq!(nl_res.stages().len(), 2);

    // Non-Unquoted quote style with trivia uses a single format stage, not two-pass unquote.
    let double_res = apply_batch(
        &eq_doc,
        &[Fix::Format(
            FormatOptions::default()
                .with_quote_style(QuoteStyle::Single)
                .with_equals_spacing(EqualsSpacing::None),
        )],
    )
    .unwrap();
    assert_eq!(double_res.output(), "A='plain'\n");
    assert_eq!(double_res.stages().len(), 1);
}

#[test]
fn apply_batch_parse_strict_bounded_distinguishes_warnings_from_errors() {
    // parse_strict_bounded with max_diagnostics allows warnings (Severity::Warning)
    // while still rejecting errors (Severity::Error).
    let warn_opts =
        EditOptions::new().with_parse_limits(adotenv::ParseOptions::new().with_max_diagnostics(10));
    let dup_doc = parse_strict("A=1\nA=2\n").unwrap();
    let dup_res = apply_batch_with_options(
        &dup_doc,
        &[Fix::Format(
            FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces),
        )],
        warn_opts,
    )
    .unwrap();
    assert_eq!(dup_res.output(), "A = 1\nA = 2\n");

    let (err_doc, _) = adotenv::parse("BAD KEY=1\nA=1\n");
    assert_eq!(
        apply_batch_with_options(
            &err_doc,
            &[Fix::Format(
                FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces),
            )],
            warn_opts,
        )
        .unwrap_err(),
        LintError::Parse
    );
}

#[test]
fn insert_empty_fix_works_explicitly_and_is_opt_in_for_batches() {
    use adotenv::LimitKind;

    let doc = parse_strict("B=2\n").unwrap();
    let insert_a = Fix::InsertEmpty {
        key: "A".to_owned(),
    };
    let single = apply_fix(&doc, &insert_a).unwrap();
    assert_eq!(single.as_str(), "B=2\nA=\n");
    assert_eq!(single.edits().len(), 1);

    // Bounded apply_fix_with_options enforces output-byte cap on InsertEmpty.
    assert!(matches!(
        apply_fix_with_options(&doc, &insert_a, EditOptions::new().with_max_output_bytes(5)),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
    ));

    // Invalid key for dialect fails cleanly via EditError::InvalidKey.
    assert!(matches!(
        apply_fix(
            &doc,
            &Fix::InsertEmpty {
                key: "BAD KEY".to_owned()
            }
        ),
        Err(LintError::Edit(EditError::InvalidKey))
    ));

    // apply_fixes deduplicates InsertEmpty, combines with Rename, and rejects mixing with Sort/Format.
    let dedup = apply_fixes(&doc, &[insert_a.clone(), insert_a.clone()]).unwrap();
    assert_eq!(dedup.as_str(), "B=2\nA=\n");

    let lower_doc = parse_strict("b=2\n").unwrap();
    let combined_edits = apply_fixes(
        &lower_doc,
        &[
            Fix::Rename {
                entry: 0,
                key: "B".to_owned(),
            },
            insert_a.clone(),
        ],
    )
    .unwrap();
    assert_eq!(combined_edits.as_str(), "B=2\nA=\n");

    assert!(matches!(
        apply_fixes(&doc, &[insert_a.clone(), Fix::Sort]),
        Err(LintError::Conflict(
            "edits cannot be combined with formatting or sorting"
        ))
    ));
    assert!(matches!(
        apply_fixes(
            &doc,
            &[
                insert_a.clone(),
                Fix::Format(FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces))
            ]
        ),
        Err(LintError::Conflict(
            "edits cannot be combined with formatting or sorting"
        ))
    ));
}

#[test]
fn apply_batch_with_policy_gates_insert_missing_and_avoids_rename_collisions() {
    use adotenv::LimitKind;

    let doc = parse_strict("B=2\n").unwrap();
    let insert_a = Fix::InsertEmpty {
        key: "A".to_owned(),
    };

    // Default apply_batch / apply_batch_with_options skip Fix::InsertEmpty (Decision 4).
    let default_batch = apply_batch(&doc, std::slice::from_ref(&insert_a)).unwrap();
    assert!(default_batch.is_empty());
    assert_eq!(default_batch.output(), "B=2\n");
    assert_eq!(default_batch.stages().len(), 0);

    // Opt-in apply_batch_with_policy inserts missing keys, skips keys already satisfied
    // by stage-1 renames, then sorts and formats.
    let rename_and_missing = parse_strict("port='8080'\n").unwrap();
    let schema = Schema::new()
        .with_key("HOST", KeySchema::new())
        .with_key("PORT", KeySchema::new());
    let policy = LintOptions::new()
        .with_key_case(KeyCase::Upper)
        .with_key_order(true)
        .with_quote_style(QuoteStyle::Double);
    let findings = lint_with_schema(&rename_and_missing, policy, &schema);
    let mut fixes: Vec<Fix> = findings.iter().filter_map(|f| f.fix().cloned()).collect();
    fixes.push(Fix::Sort);

    let style_only = apply_batch(&rename_and_missing, &fixes).unwrap();
    assert_eq!(style_only.output(), "PORT=\"8080\"\n");

    let with_missing = apply_batch_with_policy(
        &rename_and_missing,
        &fixes,
        BatchOptions::new().with_insert_missing(true),
    )
    .unwrap();
    assert_eq!(with_missing.output(), "HOST=\nPORT=\"8080\"\n");
    assert_eq!(with_missing.stages().len(), 4);

    // Inserting a key already present in the document is a no-op in staged batch mode.
    let already = parse_strict("A=1\n").unwrap();
    let noop = apply_batch_with_policy(
        &already,
        &[insert_a],
        BatchOptions::new().with_insert_missing(true),
    )
    .unwrap();
    assert!(noop.is_empty());
    assert_eq!(noop.output(), "A=1\n");
    assert_eq!(noop.stages().len(), 0);

    // BatchOptions enforces EditOptions limits on the insert stage as well.
    let tight = BatchOptions::new()
        .with_insert_missing(true)
        .with_edit_options(EditOptions::new().with_max_output_bytes(5));
    assert!(matches!(
        apply_batch_with_policy(
            &doc,
            &[Fix::InsertEmpty {
                key: "LONG_MISSING".to_owned()
            }],
            tight
        ),
        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
    ));
}