rustledger 0.21.0

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

mod config;
mod duplicate;
mod suggest;

use crate::cmd::completions::ShellType;
use anyhow::{Context, Result, anyhow};
use clap::Parser;
use config::{
    apply_column, build_config_from_entry, find_importers_config, find_matching_importers,
    load_importers_config,
};
// Used only by the WASM-importer-dir resolution path (gated below).
#[cfg(feature = "python-plugin-wasm")]
use config::expand_tilde;
use duplicate::load_existing_transactions;
use format_num_pattern::Locale;
use rustledger_core::{Directive, FormatConfig};
use rustledger_importer::config::CsvConfigBuilder;
use rustledger_importer::{Importer, ImporterConfig, ImporterRegistry, csv_importer::CsvImporter};
use rustledger_parser::format::canonicalize_directives;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

/// Extract transactions from bank files.
#[derive(Parser, Debug)]
#[command(name = "extract")]
#[command(author, version, about, long_about = None)]
pub struct Args {
    /// Generate shell completions and exit
    #[arg(long, value_name = "SHELL", hide = true)]
    pub generate_completions: Option<ShellType>,

    /// The file to extract transactions from
    #[arg(value_name = "FILE")]
    pub file: Option<PathBuf>,

    /// Use a named importer from importers.toml
    #[arg(long, short = 'i')]
    pub importer: Option<String>,

    /// Path to importers.toml configuration file
    #[arg(long, alias = "importers-config")]
    pub config: Option<PathBuf>,

    /// List available importers from config file and exit
    #[arg(long = "list-importers")]
    pub list_importers: bool,

    /// Target account for imported transactions
    #[arg(short, long, default_value = "Assets:Bank:Checking")]
    pub account: String,

    /// Currency for amounts (default: USD)
    #[arg(short, long, default_value = "USD")]
    pub currency: String,

    /// Date column name or index
    #[arg(long, default_value = "Date")]
    pub date_column: String,

    /// Date format (strftime-style)
    #[arg(long, default_value = "%Y-%m-%d")]
    pub date_format: String,

    /// Narration/description column name or index
    #[arg(long, default_value = "Description")]
    pub narration_column: String,

    /// Payee column name (optional)
    #[arg(long)]
    pub payee_column: Option<String>,

    /// Amount column name or index
    #[arg(long, default_value = "Amount")]
    pub amount_column: String,

    /// Per-row currency column name or index (optional). When set, each row's
    /// currency is read from this column instead of the single `--currency`.
    #[arg(long)]
    pub currency_column: Option<String>,

    /// Locale used to parse amounts, e.g. `en_US`
    #[arg(long)]
    pub amount_locale: Option<String>,

    /// Custom formatting for parsing amounts.
    #[arg(long)]
    pub amount_format: Option<String>,

    /// Debit column (for separate debit/credit columns)
    #[arg(long)]
    pub debit_column: Option<String>,

    /// Credit column (for separate debit/credit columns)
    #[arg(long)]
    pub credit_column: Option<String>,

    /// CSV delimiter
    #[arg(long, default_value = ",")]
    pub delimiter: char,

    /// Number of header rows to skip
    #[arg(long, default_value = "0")]
    pub skip_rows: usize,

    /// Invert sign of amounts
    #[arg(long)]
    pub invert_sign: bool,

    /// Preserve rows whose amount is exactly zero (e.g. balance markers).
    /// Default behavior drops them, matching most banks' use of zero rows
    /// as status filler — see issue #972.
    #[arg(long)]
    pub include_zero_amounts: bool,

    /// Auto-detect CSV format (delimiter, columns, date format)
    #[arg(long, conflicts_with_all = [
        "date_column", "date_format", "narration_column", "amount_column",
        "delimiter", "skip_rows", "no_header", "debit_column", "credit_column",
        "payee_column", "currency_column",
    ])]
    pub auto: bool,

    /// CSV has no header row
    #[arg(long)]
    pub no_header: bool,

    /// Categorize transactions using the built-in merchant dictionary
    /// (e.g. NETFLIX → Expenses:Subscriptions:Streaming) instead of leaving
    /// unmatched rows at Expenses:Unknown. Can also be set per-importer in
    /// importers.toml via `use_merchant_dict = true`.
    #[arg(long)]
    pub use_merchant_dict: bool,

    /// Write output to a file instead of stdout
    #[arg(short, long, value_name = "FILE")]
    pub output: Option<PathBuf>,

    /// Existing ledger file for duplicate detection
    #[arg(long, value_name = "FILE")]
    pub existing: Option<PathBuf>,

    /// Use ML to suggest accounts for transactions the rules engine didn't
    /// categorize. Trains a Naive Bayes model on the `--existing` ledger and
    /// replaces the configured fallback contra-accounts (the importer's
    /// `default_expense` and `default_income`, defaulting to
    /// `Expenses:Unknown` / `Income:Unknown`) with the prediction.
    /// Requires `--existing`.
    #[arg(long, requires = "existing")]
    pub suggest_categories: bool,

    /// Append a balance assertion with the given amount (e.g., "1234.56")
    #[arg(long, value_name = "AMOUNT")]
    pub balance: Option<String>,

    /// Date for the balance assertion (defaults to today)
    #[arg(long, value_name = "DATE")]
    pub balance_date: Option<String>,

    /// Register a specific WASM importer module ahead of the built-in
    /// CSV/OFX importers. May be specified multiple times. Each
    /// `<PATH>` must be a `.wasm` file. User-specified modules take
    /// precedence over discovered ones and over built-ins — this is
    /// the right flag for ad-hoc one-off usage.
    #[arg(long, value_name = "PATH")]
    pub wasm_importer: Vec<PathBuf>,

    /// Scan a directory for `*.wasm` importer modules at startup. May
    /// be specified multiple times for multi-dir setups. Overrides
    /// `wasm_importer_dir` from `importers.toml` entirely when any
    /// `--wasm-importer-dir` flag is present. Non-`.wasm` files are
    /// silently skipped; subdirectories are not recursed into.
    #[arg(long, value_name = "DIR")]
    pub wasm_importer_dir: Vec<PathBuf>,
}

/// List available importers — both TOML profiles and engines.
///
/// TOML profiles (for `--importer <name>`) and registered engines
/// (built-in CSV/OFX plus any `--wasm-importer`/scanned modules) are
/// orthogonal concepts: a TOML profile is a pre-configured
/// [`ImporterConfig`] driven by `CsvImporter`; an engine is the actual
/// trait implementation that consumes a config.
pub fn list_importers(args: &Args) -> Result<()> {
    let mut stdout = io::stdout().lock();
    list_importers_with_writer(args, &mut stdout)
}

/// List available importers, writing the listing to `out`.
///
/// Writer-injectable variant of [`list_importers`] used by `ag-rledger`.
/// Behavior is otherwise identical.
pub fn list_importers_with_writer<W: Write>(args: &Args, out: &mut W) -> Result<()> {
    // ===== TOML profiles =====
    //
    // Optional: if no config file is present we still want to list
    // the registered engines, so this is a soft find rather than the
    // hard "must have config" error the original code had.
    if let Some(config_path) = find_importers_config(args.config.as_deref())? {
        let config = load_importers_config(&config_path)?;
        if config.importers.is_empty() {
            writeln!(out, "No TOML profiles in {}", config_path.display())?;
        } else {
            writeln!(out, "TOML profiles in {}:", config_path.display())?;
            for imp in &config.importers {
                if let Some(pattern) = &imp.filename_pattern {
                    writeln!(
                        out,
                        "  {} (pattern: {}) -> {}",
                        imp.name,
                        pattern,
                        imp.account.as_deref().unwrap_or("(default)")
                    )?;
                } else {
                    writeln!(
                        out,
                        "  {} -> {}",
                        imp.name,
                        imp.account.as_deref().unwrap_or("(default)")
                    )?;
                }
            }
        }
    } else {
        writeln!(
            out,
            "(no importers.toml found — listing registered engines only)"
        )?;
    }
    writeln!(out)?;

    // ===== Registered importer engines =====
    //
    // Always shown — at minimum CSV + OFX, plus any WASM-discovered
    // modules. Build a fresh registry from args so users see exactly
    // what this invocation would dispatch through.
    let registry = build_registry(args)?;
    writeln!(out, "Registered importer engines:")?;
    for (name, description) in registry.list_importers() {
        writeln!(out, "  {name} - {description}")?;
    }

    Ok(())
}

/// Pick the importer for a given file + CLI args.
///
/// - If the user explicitly chose a TOML entry (`--importer <name>`),
///   force [`CsvImporter`]: TOML profiles are CSV-only by definition
///   of [`rustledger_importer::config::ImporterType`] today, and the
///   profile's column mappings would be lost if registry-identify
///   silently routed the file to a different engine (e.g. a
///   `.ofx`-named file picked up by `OfxImporter`).
/// - Otherwise let the registry identify by extension. This is the
///   path WASM importers reach via `--wasm-importer` /
///   `--wasm-importer-dir` — including when combined with
///   `--config` for pattern-matched TOML profiles. (Earlier this
///   function also force-CSV'd when `--config` was set alone; that
///   meant `--wasm-importer my.wasm --config x.toml` silently
///   ignored the WASM module. Fixed by limiting the force-CSV path
///   to `--importer`.)
/// - Fall back to [`CsvImporter`] for unknown extensions (e.g. `.qbo`
///   Quicken exports) so users with custom-extension TOML entries
///   keep working.
fn select_importer(registry: &ImporterRegistry, file: &Path, args: &Args) -> Arc<dyn Importer> {
    if args.importer.is_some() {
        Arc::new(CsvImporter)
    } else {
        registry
            .identify(file)
            .unwrap_or_else(|| Arc::new(CsvImporter) as Arc<dyn Importer>)
    }
}

/// Resolve the list of directories to scan for WASM importers.
///
/// Top-level dispatcher; the two real branches are
/// [`resolve_scan_dirs_explicit`] (user named a config file with
/// `--config`, errors propagate) and [`resolve_scan_dirs_implicit`]
/// (no flag, soft-discover from default locations, errors warn-and-
/// degrade). CLI `--wasm-importer-dir` flags override both and
/// short-circuit the toml lookup entirely.
#[cfg(feature = "python-plugin-wasm")]
fn resolve_scan_dirs(args: &Args) -> Result<Vec<PathBuf>> {
    if !args.wasm_importer_dir.is_empty() {
        return Ok(args.wasm_importer_dir.clone());
    }
    match args.config.as_deref() {
        Some(path) => resolve_scan_dirs_explicit(path),
        None => Ok(resolve_scan_dirs_implicit()),
    }
}

/// User passed `--config <path>` explicitly. Missing or malformed
/// file is a real error — the user asked for this file by name, so
/// silently degrading would hide the bug they want to know about.
#[cfg(feature = "python-plugin-wasm")]
fn resolve_scan_dirs_explicit(path: &Path) -> Result<Vec<PathBuf>> {
    let cfg_path = find_importers_config(Some(path))?
        .ok_or_else(|| anyhow!("Importers config not found: {}", path.display()))?;
    let cfg = load_importers_config(&cfg_path)?;
    Ok(cfg
        .wasm_importer_dir
        .into_vec()
        .into_iter()
        .map(|p| expand_tilde(&p))
        .collect())
}

/// No `--config` flag — soft-discover in default locations
/// (cwd `importers.toml` then `~/.config/rledger/importers.toml`).
/// A missing file is expected; a malformed file is unusual but not
/// fatal (the user didn't explicitly point at it). Print a warning
/// for the malformed case so the user can find their mistake.
#[cfg(feature = "python-plugin-wasm")]
fn resolve_scan_dirs_implicit() -> Vec<PathBuf> {
    let cfg_path = match find_importers_config(None) {
        Ok(Some(p)) => p,
        Ok(None) | Err(_) => return Vec::new(),
    };
    match load_importers_config(&cfg_path) {
        Ok(cfg) => cfg
            .wasm_importer_dir
            .into_vec()
            .into_iter()
            .map(|p| expand_tilde(&p))
            .collect(),
        Err(e) => {
            // Visible warning instead of silent loss — the user's
            // wasm_importer_dir setting would otherwise vanish with
            // no signal that the file even exists.
            eprintln!(
                "warning: implicit importers.toml at {} failed to parse: {e:#}; ignoring wasm_importer_dir",
                cfg_path.display()
            );
            Vec::new()
        }
    }
}

/// Build an [`ImporterRegistry`] with WASM importers registered ahead
/// of the built-in CSV/OFX importers, so user-discovered modules win
/// the `identify()` race. Priority (highest first):
///
/// 1. CLI `--wasm-importer <PATH>` (explicit per-invocation,
///    repeatable)
/// 2. CLI `--wasm-importer-dir <DIR>` (repeatable) OR
///    `wasm_importer_dir` from `importers.toml` (CLI flags win
///    entirely — they're not merged with the toml setting)
/// 3. Built-in CSV + OFX importers (always present, registered last)
///
/// Per-dir scan failures (a single malformed `.wasm` among many) are
/// logged to stderr but don't abort startup — see [`register_wasm_dir`]'s
/// skip-and-collect semantics.
#[cfg_attr(not(feature = "python-plugin-wasm"), allow(unused_variables))]
fn build_registry(args: &Args) -> Result<ImporterRegistry> {
    let mut registry = ImporterRegistry::new();

    // 1 + 2. WASM importer loading (sandboxed `.wasm` importers). Gated behind
    //    `python-plugin-wasm` so a `--no-default-features` build carries no
    //    `wasmtime`/cranelift dependency (#1427); without the feature the
    //    `--wasm-importer`/`--wasm-importer-dir` flags are accepted but inert.
    #[cfg(feature = "python-plugin-wasm")]
    {
        // 1. CLI --wasm-importer paths (explicit precedence — registered
        //    first so they win identify()). Single-file failures abort
        //    because the user explicitly named this path; if it's wrong,
        //    silently skipping would be worse than erroring out.
        for path in &args.wasm_importer {
            let name = registry
                .register_wasm_from_path(path)
                .with_context(|| format!("failed to load WASM importer {}", path.display()))?;
            eprintln!("loaded WASM importer `{name}` from {}", path.display());
        }

        // 2. Directory scan(s): CLI flags override toml entirely.
        //    Multiple dirs are scanned in order. `~` is expanded for
        //    toml-supplied paths (CLI paths get shell expansion).
        let scan_dirs: Vec<PathBuf> = resolve_scan_dirs(args)?;
        for dir in &scan_dirs {
            let report = registry.register_wasm_dir(dir).with_context(|| {
                format!("failed to scan WASM importer directory {}", dir.display())
            })?;
            if !report.loaded.is_empty() || !report.failures.is_empty() {
                eprintln!(
                    "WASM importer scan {}: loaded {}, failed {}",
                    dir.display(),
                    report.loaded.len(),
                    report.failures.len(),
                );
            }
            for (failed_path, err) in &report.failures {
                eprintln!("  warning: failed to load {}: {err}", failed_path.display());
            }
        }
    }

    // 3. Built-ins last so any user importer takes precedence on
    //    identify() collisions.
    registry.register(rustledger_importer::OfxImporter);
    registry.register(rustledger_importer::csv_importer::CsvImporter);

    Ok(registry)
}

/// Parse an `--amount-locale` value (e.g. `de_DE`, `en_US`) into a [`Locale`],
/// with a consistent error for an unrecognized name. Shared by the `--auto`
/// and raw-CLI config paths.
fn parse_amount_locale(name: &str) -> Result<Locale> {
    Locale::from_str(name).map_err(|_| anyhow!("{name} is not a valid locale"))
}

/// Run the extract command with the given arguments, writing extracted
/// directives to stdout.
///
/// Thin wrapper over [`run_with_writer`] for the synchronous `rledger`
/// binary; `ag-rledger` calls `run_with_writer` with a buffer.
pub fn run(args: &Args, file: &Path) -> Result<()> {
    let mut stdout = io::stdout().lock();
    run_with_writer(args, file, &mut stdout)
}

/// Run the extract command, writing extracted directives to `out`.
///
/// Behavior matches the original `run()`: a `--output <file>` flag still
/// writes to disk (and the "Wrote output to ..." note still goes to
/// stderr), and progress/warning lines still go to stderr. Only the
/// default stdout sink for the formatted directives is redirected to the
/// injected writer.
pub fn run_with_writer<W: Write>(args: &Args, file: &Path, out: &mut W) -> Result<()> {
    let registry = build_registry(args)?;

    // Pick the dispatcher BEFORE building config: only `CsvImporter`
    // needs the elaborate `--importer`/`--config`/`--auto` config
    // path. WASM importers and `OfxImporter` consume a minimal default
    // config (account + currency; the rest is either projected via
    // the WASM wire format's `options` map or ignored). Building the
    // CSV config eagerly would error on "No importers defined" when a
    // user runs e.g. `--config x.toml --wasm-importer my.wasm` with
    // an x.toml that only sets `wasm_importer_dir`.
    let importer = select_importer(&registry, file, args);

    // Stringly-typed dispatcher check: `CsvImporter::name()` returns
    // the literal "CSV". Acceptable coupling for a CLI-internal
    // routing decision; a trait method would be over-design for one
    // call site.
    let dispatcher_needs_minimal_config = importer.name() != "CSV";

    // Build the per-call ImporterConfig + fallback-account list.
    //
    // - Non-CSV dispatcher (OFX, WASM, future builtins): minimal
    //   default config — account + currency, empty CsvConfig carrier
    //   the WASM wire format projects via `options`.
    // - CSV dispatcher: builds the full CsvConfig from
    //   --importer/--config/--auto/raw-args sources.
    let (config, fallback_accounts) = if dispatcher_needs_minimal_config {
        let cfg = rustledger_importer::ImporterConfig {
            account: args.account.clone(),
            currency: Some(args.currency.clone()),
            importer_type: rustledger_importer::config::ImporterType::Csv(
                rustledger_importer::config::CsvConfig::default(),
            ),
        };
        // OFX importer routes negative amounts to `Expenses:Unknown`
        // and positive amounts to `Income:Unknown` (ofx_importer.rs's
        // `parse_transaction`). Both must be in the fallback list so
        // `--suggest-categories` re-categorizes income as well as
        // expense transactions. WASM importers may produce their own
        // fallbacks; the host defaults are used when they don't.
        (
            cfg,
            vec!["Expenses:Unknown".to_string(), "Income:Unknown".to_string()],
        )
    } else {
        // CSV branch: determine import config from --importer flag,
        // explicit --config, --auto, or raw CLI args.
        let config = if let Some(ref importer_name) = args.importer {
            // Explicit --importer: require config file, find named entry
            let config_path = find_importers_config(args.config.as_deref())?
                .ok_or_else(|| anyhow!(
                    "No importers.toml found. Create one in the current directory or at ~/.config/rledger/importers.toml"
                ))?;

            let importers_file = load_importers_config(&config_path)?;

            let entry = importers_file
                .importers
                .iter()
                .find(|e| e.name == *importer_name)
                .ok_or_else(|| {
                    let available: Vec<&str> = importers_file
                        .importers
                        .iter()
                        .map(|e| e.name.as_str())
                        .collect();
                    anyhow!(
                        "Importer '{}' not found in {}. Available: {}",
                        importer_name,
                        config_path.display(),
                        available.join(", ")
                    )
                })?;

            eprintln!(
                "Using importer '{}' from {}",
                importer_name,
                config_path.display()
            );
            build_config_from_entry(entry)?
        } else if args.config.is_some() {
            // Explicit --config without --importer: try auto-identification by filename
            let config_path = find_importers_config(args.config.as_deref())?
                .ok_or_else(|| anyhow!(
                    "No importers.toml found. Create one in the current directory or at ~/.config/rledger/importers.toml"
                ))?;

            let importers_file = load_importers_config(&config_path)?;

            if importers_file.importers.is_empty() {
                return Err(anyhow!("No importers defined in {}", config_path.display()));
            }

            // Try auto-identification by filename pattern
            let filename = file
                .file_name()
                .map(|s| s.to_string_lossy())
                .unwrap_or_default();
            let matches = find_matching_importers(&importers_file, &filename);

            let entry = match matches.len() {
                1 => {
                    eprintln!(
                        "Auto-identified importer '{}' from filename pattern",
                        matches[0].name
                    );
                    matches[0]
                }
                0 if importers_file.importers.len() == 1 => {
                    // No pattern match but only one importer - use it
                    &importers_file.importers[0]
                }
                0 => {
                    let available: Vec<&str> = importers_file
                        .importers
                        .iter()
                        .map(|e| e.name.as_str())
                        .collect();
                    return Err(anyhow!(
                        "No importer matches file '{}'. Use --importer to select one: {}",
                        filename,
                        available.join(", ")
                    ));
                }
                _ => {
                    let names: Vec<&str> = matches.iter().map(|e| e.name.as_str()).collect();
                    return Err(anyhow!(
                        "Multiple importers match file '{}': {}. Use --importer to select one.",
                        filename,
                        names.join(", ")
                    ));
                }
            };

            eprintln!(
                "Using importer '{}' from {}",
                entry.name,
                config_path.display()
            );
            build_config_from_entry(entry)?
        } else if args.auto {
            // Auto-detect CSV format
            let content = std::fs::read_to_string(file)
                .with_context(|| format!("Failed to read file: {}", file.display()))?;

            let inferred = rustledger_importer::csv_inference::infer_csv_config(&content)
                .ok_or_else(|| anyhow!(
                    "Could not auto-detect CSV format for {}. Try specifying columns explicitly.",
                    file.display()
                ))?;

            eprintln!(
                "Auto-detected format (confidence: {:.0}%):",
                inferred.confidence * 100.0
            );
            eprintln!("  delimiter: {:?}", inferred.delimiter);
            eprintln!("  date_format: {}", inferred.date_format);
            eprintln!("  has_header: {}", inferred.has_header);

            let mut csv_config = inferred.to_csv_config();
            if args.include_zero_amounts {
                csv_config.skip_zero_amounts = false;
            }
            if args.use_merchant_dict {
                csv_config.use_merchant_dict = true;
            }
            // An explicit --amount-locale / --amount-format overrides the
            // separator locale inferred from the data. Report the *effective*
            // locale (override if given, otherwise the inferred one) so the
            // printed summary matches what's actually used.
            if let Some(locale) = &args.amount_locale {
                let locale = parse_amount_locale(locale)?;
                csv_config.amount_locale = Some(locale);
                eprintln!("  amount_locale: {locale:?} (from --amount-locale)");
            } else if let Some(locale) = inferred.amount_locale {
                eprintln!("  amount_locale: {locale:?} (inferred)");
            }
            if let Some(format) = &args.amount_format {
                csv_config.amount_format = Some(format.clone());
            }
            ImporterConfig {
                account: args.account.clone(),
                currency: Some(args.currency.clone()),
                importer_type: rustledger_importer::config::ImporterType::Csv(csv_config),
            }
        } else {
            // No config file: build from CLI arguments
            let mut builder = ImporterConfig::csv()
                .account(&args.account)
                .currency(&args.currency)
                .date_format(&args.date_format)
                .delimiter(args.delimiter)
                .skip_rows(args.skip_rows)
                .invert_sign(args.invert_sign)
                .skip_zero_amounts(!args.include_zero_amounts)
                .has_header(!args.no_header)
                .use_merchant_dict(args.use_merchant_dict);

            // Column flags accept either a header name or a 0-based index (see
            // `apply_column`), so headerless CSVs can be imported positionally.
            builder = apply_column(
                builder,
                &args.date_column,
                CsvConfigBuilder::date_column_index,
                |b, n| b.date_column(n),
            );
            builder = apply_column(
                builder,
                &args.narration_column,
                CsvConfigBuilder::narration_column_index,
                |b, n| b.narration_column(n),
            );
            builder = apply_column(
                builder,
                &args.amount_column,
                CsvConfigBuilder::amount_column_index,
                |b, n| b.amount_column(n),
            );

            if let Some(payee) = &args.payee_column {
                builder = apply_column(
                    builder,
                    payee,
                    CsvConfigBuilder::payee_column_index,
                    |b, n| b.payee_column(n),
                );
            }

            if let Some(currency_col) = &args.currency_column {
                builder = apply_column(
                    builder,
                    currency_col,
                    CsvConfigBuilder::currency_column_index,
                    |b, n| b.currency_column(n),
                );
            }

            if let Some(debit) = &args.debit_column {
                builder = builder.debit_column(debit);
            }

            if let Some(credit) = &args.credit_column {
                builder = builder.credit_column(credit);
            }

            if let Some(locale) = &args.amount_locale {
                builder = builder.amount_locale(parse_amount_locale(locale)?);
            }

            if let Some(format) = &args.amount_format {
                builder = builder.amount_format(format);
            }

            builder.build()?
        };

        // Apply --include-zero-amounts uniformly across all config sources
        // (--importer entry, explicit --config, --auto, raw CLI). Without this,
        // the flag silently has no effect when the config came from a TOML
        // entry — see Copilot review on PR #982.
        let config = if args.include_zero_amounts {
            let mut config = config;
            let rustledger_importer::config::ImporterType::Csv(csv) = &mut config.importer_type;
            csv.skip_zero_amounts = false;
            config
        } else {
            config
        };

        let rustledger_importer::config::ImporterType::Csv(csv) = &config.importer_type;
        let fallbacks = vec![
            csv.default_expense
                .clone()
                .unwrap_or_else(|| "Expenses:Unknown".to_string()),
            csv.default_income
                .clone()
                .unwrap_or_else(|| "Income:Unknown".to_string()),
        ];
        (config, fallbacks)
    };

    // `importer` was selected earlier so we could route config-
    // building correctly; here it's used for the actual dispatch.
    let result = importer.extract(file, &config)?;

    // Print warnings
    for warning in &result.warnings {
        eprintln!("warning: {warning}");
    }

    // Fail loudly when the importer produced no transactions — before
    // duplicate filtering (`--existing`) or `--balance` augmentation, either of
    // which would otherwise mask the real cause (all-duplicates, or a lone
    // balance directive with zero transactions). A garbage / wrong-type /
    // empty file otherwise makes a scripted `extract … >> ledger.beancount`
    // silently append nothing and still exit 0.
    let extracted_txns = result
        .directives
        .iter()
        .filter(|d| matches!(d, Directive::Transaction(_)))
        .count();
    if extracted_txns == 0 {
        anyhow::bail!(
            "no transactions were extracted from {}\n  \
             the file may not match a recognized importer format, be empty, or \
             use unexpected columns\n  \
             try: --auto, an explicit importer (--importer), or column flags \
             (--date-column, --amount-column, …)",
            file.display()
        );
    }

    // Filter duplicates if --existing is specified, and optionally apply
    // ML-based account suggestions for transactions the rules engine left
    // pointing at a fallback account.
    let directives = if let Some(ref existing_path) = args.existing {
        let existing_txns = load_existing_transactions(existing_path)?;
        let before_count = result.directives.len();
        // Build the dedup config once, not once per filtered directive.
        let dedup_config = rustledger_ops::dedup::FuzzyDedupConfig::default();
        let mut filtered: Vec<_> = result
            .directives
            .into_iter()
            .filter(|d| {
                if let Directive::Transaction(txn) = d {
                    !rustledger_ops::dedup::is_duplicate(txn, &existing_txns, &dedup_config)
                } else {
                    true
                }
            })
            .collect();
        let dupes = before_count - filtered.len();
        if dupes > 0 {
            eprintln!("Filtered {dupes} duplicate transaction(s)");
        }
        if args.suggest_categories {
            suggest::apply_ml_suggestions_with_summary(
                &mut filtered,
                &existing_txns,
                &fallback_accounts,
            )?;
        }
        filtered
    } else {
        result.directives
    };

    // Append balance assertion if --balance is specified
    let directives = if let Some(ref balance_amount) = args.balance {
        use rust_decimal::Decimal;
        use std::str::FromStr;

        let amount = Decimal::from_str(balance_amount)
            .with_context(|| format!("Invalid balance amount: {balance_amount}"))?;
        let date_str = args
            .balance_date
            .clone()
            .unwrap_or_else(|| jiff::Zoned::now().date().to_string());
        let date = date_str
            .parse::<rustledger_core::NaiveDate>()
            .with_context(|| format!("Invalid balance date: {date_str}"))?;

        let balance = rustledger_ops::reconcile::StatementBalance {
            date,
            account: args.account.clone(),
            number: amount,
            currency: args.currency.clone(),
        };
        // `create_balance_directive` returns a core `Directive` directly now — no
        // `DirectiveWrapper` round-trip through `wrapper_to_directive`.
        let balance_directive = rustledger_ops::reconcile::create_balance_directive(&balance);

        let mut with_balance = directives;
        with_balance.push(balance_directive);
        with_balance
    } else {
        directives
    };

    // Render every directive in the canonical form `rledger format`
    // would write. canonicalize_directives is the single source of
    // truth for the synthesize-then-canonicalize pipeline (legacy
    // typed-AST emitter → parse → opinionated formatter), with a
    // built-in parse-error guard so a divergence between the two
    // emitters surfaces as a hard error rather than silent data
    // loss.
    let fmt_config = FormatConfig::default();
    let formatted = canonicalize_directives(directives.iter(), &fmt_config)
        .map_err(|e| anyhow::anyhow!(e.to_string()))?;

    if let Some(ref output_path) = args.output {
        let mut out_file = fs::File::create(output_path)
            .with_context(|| format!("Failed to create output file: {}", output_path.display()))?;
        out_file.write_all(formatted.as_bytes())?;
        eprintln!("Wrote output to {}", output_path.display());
    } else {
        out.write_all(formatted.as_bytes())?;
    }

    let written_txns = directives
        .iter()
        .filter(|d| matches!(d, Directive::Transaction(_)))
        .count();
    eprintln!(
        "Extracted {written_txns} transactions from {}",
        file.display()
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::config::{ImporterEntry, parse_column_value};
    use super::*;
    use rustledger_importer::config::ImporterType;
    use std::collections::HashMap;

    fn write_temp_config(content: &str) -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("importers.toml");
        std::fs::write(&path, content).unwrap();
        (dir, path)
    }

    #[test]
    fn test_load_importers_config_basic() {
        let (_dir, path) = write_temp_config(
            r#"
[[importers]]
name = "chase"
account = "Assets:Bank:Chase"
date_column = "Transaction Date"
amount_column = "Amount"
"#,
        );

        let config = load_importers_config(&path).unwrap();
        assert_eq!(config.importers.len(), 1);
        assert_eq!(config.importers[0].name, "chase");
        assert_eq!(
            config.importers[0].account.as_deref(),
            Some("Assets:Bank:Chase")
        );
    }

    #[test]
    fn test_load_importers_config_with_mappings() {
        let (_dir, path) = write_temp_config(
            r#"
[[importers]]
name = "checking"
account = "Assets:Bank:Checking"

[importers.mappings]
"AMAZON" = "Expenses:Shopping"
"WHOLE FOODS" = "Expenses:Groceries"
"#,
        );

        let config = load_importers_config(&path).unwrap();
        assert_eq!(config.importers[0].mappings.len(), 2);
        assert_eq!(
            config.importers[0].mappings.get("AMAZON"),
            Some(&"Expenses:Shopping".to_string())
        );
    }

    #[test]
    fn test_load_importers_config_multiple_importers() {
        let (_dir, path) = write_temp_config(
            r#"
[[importers]]
name = "checking"
account = "Assets:Bank:Checking"

[[importers]]
name = "credit_card"
account = "Liabilities:CreditCard"
invert_amounts = true
"#,
        );

        let config = load_importers_config(&path).unwrap();
        assert_eq!(config.importers.len(), 2);
        assert_eq!(config.importers[1].name, "credit_card");
        assert_eq!(config.importers[1].invert_amounts, Some(true));
    }

    #[test]
    fn test_load_importers_config_integer_columns() {
        let (_dir, path) = write_temp_config(
            r#"
[[importers]]
name = "noheader"
account = "Assets:Bank"
date_column = 0
amount_column = 3
narration_column = 1
"#,
        );

        let config = load_importers_config(&path).unwrap();
        let entry = &config.importers[0];
        assert_eq!(
            parse_column_value(entry.date_column.as_ref().unwrap()),
            Some("0".to_string())
        );
        assert_eq!(
            parse_column_value(entry.amount_column.as_ref().unwrap()),
            Some("3".to_string())
        );
    }

    #[test]
    fn test_cli_numeric_column_args_extract_by_index() {
        // Regression: numeric --date-column/--amount-column/--payee-column
        // values are treated as 0-based indices (flags documented as "name or
        // index"), so a headerless CSV imports instead of every row being
        // dropped because no header matches "0"/"1"/"2".
        use clap::Parser;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("noheader.csv");
        std::fs::write(&path, "2024-01-15,Coffee,-5.00\n2024-01-16,Lunch,-12.00\n").unwrap();

        let args = Args::parse_from([
            "extract",
            "--no-header",
            "--date-column",
            "0",
            "--payee-column",
            "1",
            "--amount-column",
            "2",
            path.to_str().unwrap(),
        ]);
        let mut out = Vec::new();
        run_with_writer(&args, &path, &mut out).unwrap();
        let text = String::from_utf8(out).unwrap();

        assert!(text.contains("Coffee"), "first row not imported: {text}");
        assert!(text.contains("-5.00"), "first amount missing: {text}");
        assert!(text.contains("Lunch"), "second row not imported: {text}");
        assert_eq!(
            text.matches("2024-01-").count(),
            2,
            "both rows should import via positional indices: {text}"
        );
    }

    #[test]
    fn test_load_importers_config_invalid_toml() {
        let (_dir, path) = write_temp_config("this is not valid toml [[[");
        assert!(load_importers_config(&path).is_err());
    }

    #[test]
    fn test_load_importers_config_missing_file() {
        let path = PathBuf::from("/nonexistent/importers.toml");
        assert!(load_importers_config(&path).is_err());
    }

    #[test]
    fn test_build_config_from_entry_basic() {
        let entry = ImporterEntry {
            name: "test".to_string(),
            account: Some("Assets:Bank:Test".to_string()),
            currency: Some("EUR".to_string()),
            date_column: Some(toml::Value::String("Date".to_string())),
            date_format: Some("%m/%d/%Y".to_string()),
            narration_column: Some(toml::Value::String("Description".to_string())),
            payee_column: None,
            amount_column: Some(toml::Value::String("Amount".to_string())),
            currency_column: None,
            debit_column: None,
            credit_column: None,
            secondary_date_column: None,
            secondary_date_format: None,
            secondary_date_key: None,
            amount_locale: None,
            amount_format: None,
            delimiter: None,
            skip_rows: None,
            skip_header: None,
            invert_amounts: None,
            default_expense: None,
            default_income: None,
            mappings: HashMap::new(),
            filename_pattern: None,
            use_merchant_dict: None,
        };

        let config = build_config_from_entry(&entry).unwrap();
        assert_eq!(config.account, "Assets:Bank:Test");
        assert_eq!(config.currency, Some("EUR".to_string()));
    }

    #[test]
    fn test_build_config_from_entry_with_mappings() {
        let mut mappings = HashMap::new();
        mappings.insert("AMAZON".to_string(), "Expenses:Shopping".to_string());
        mappings.insert("WHOLE FOODS".to_string(), "Expenses:Groceries".to_string());

        let entry = ImporterEntry {
            name: "test".to_string(),
            account: Some("Assets:Bank".to_string()),
            currency: None,
            date_column: None,
            date_format: None,
            narration_column: None,
            payee_column: None,
            amount_column: None,
            currency_column: None,
            debit_column: None,
            credit_column: None,
            secondary_date_column: None,
            secondary_date_format: None,
            secondary_date_key: None,
            amount_locale: None,
            amount_format: None,
            delimiter: None,
            skip_rows: None,
            skip_header: None,
            invert_amounts: None,
            default_expense: None,
            default_income: None,
            mappings,
            filename_pattern: None,
            use_merchant_dict: None,
        };

        let config = build_config_from_entry(&entry).unwrap();
        let ImporterType::Csv(csv_config) = &config.importer_type;
        assert_eq!(csv_config.mappings.len(), 2);
        // Patterns should be lowercased and sorted longest-first
        assert_eq!(csv_config.mappings[0].0, "whole foods");
        assert_eq!(csv_config.mappings[1].0, "amazon");
    }

    #[test]
    fn test_build_config_from_entry_with_default_expense() {
        let entry = ImporterEntry {
            name: "test".to_string(),
            account: Some("Assets:Bank".to_string()),
            currency: None,
            date_column: None,
            date_format: None,
            narration_column: None,
            payee_column: None,
            amount_column: None,
            currency_column: None,
            debit_column: None,
            credit_column: None,
            secondary_date_column: None,
            secondary_date_format: None,
            secondary_date_key: None,
            amount_locale: None,
            amount_format: None,
            delimiter: None,
            skip_rows: None,
            skip_header: None,
            invert_amounts: None,
            default_expense: Some("Expenses:Uncategorized".to_string()),
            default_income: Some("Income:Other".to_string()),
            mappings: HashMap::new(),
            filename_pattern: None,
            use_merchant_dict: None,
        };

        let config = build_config_from_entry(&entry).unwrap();
        let ImporterType::Csv(csv_config) = &config.importer_type;
        assert_eq!(
            csv_config.default_expense.as_deref(),
            Some("Expenses:Uncategorized")
        );
        assert_eq!(csv_config.default_income.as_deref(), Some("Income:Other"));
    }

    #[test]
    fn test_build_config_from_entry_all_options() {
        let entry = ImporterEntry {
            name: "full".to_string(),
            account: Some("Assets:Bank".to_string()),
            currency: Some("GBP".to_string()),
            date_column: Some(toml::Value::Integer(0)),
            date_format: Some("%d/%m/%Y".to_string()),
            narration_column: Some(toml::Value::Integer(2)),
            payee_column: Some(toml::Value::String("Payee".to_string())),
            amount_column: None,
            currency_column: None,
            debit_column: Some(toml::Value::String("Debit".to_string())),
            credit_column: Some(toml::Value::String("Credit".to_string())),
            secondary_date_column: Some("Settle Date".to_string()),
            secondary_date_format: None,
            secondary_date_key: None,
            amount_locale: None,
            amount_format: None,
            delimiter: Some(";".to_string()),
            skip_rows: Some(2),
            skip_header: Some(true),
            invert_amounts: Some(true),
            default_expense: None,
            default_income: None,
            mappings: HashMap::new(),
            filename_pattern: None,
            use_merchant_dict: None,
        };

        let config = build_config_from_entry(&entry).unwrap();
        assert_eq!(config.currency, Some("GBP".to_string()));
        let ImporterType::Csv(csv_config) = &config.importer_type;
        assert_eq!(csv_config.delimiter, ';');
        assert_eq!(csv_config.skip_rows, 2);
        assert!(!csv_config.has_header); // skip_header=true → has_header=false
        assert!(csv_config.invert_sign);
        // Secondary date: format defaults to date_format, key to a column slug.
        let sd = csv_config
            .secondary_date
            .as_ref()
            .expect("secondary_date_column should produce a secondary date");
        assert_eq!(sd.format, "%d/%m/%Y");
        assert_eq!(sd.meta_key, "settle_date");
    }

    #[test]
    fn test_find_importers_config_explicit_missing_returns_error() {
        let result = find_importers_config(Some(Path::new("/nonexistent/importers.toml")));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Importers config not found"));
    }

    #[test]
    fn test_find_importers_config_explicit_exists() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("importers.toml");
        std::fs::write(&path, "[[importers]]\nname = \"test\"\n").unwrap();

        let result = find_importers_config(Some(&path)).unwrap();
        assert_eq!(result, Some(path));
    }

    #[test]
    fn test_find_importers_config_none_returns_ok() {
        // When no explicit path is given, the function should not error
        // (it may or may not find a file depending on the environment)
        let result = find_importers_config(None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_end_to_end_extract_with_config() {
        let dir = tempfile::tempdir().unwrap();

        // Write importers.toml
        let config_path = dir.path().join("importers.toml");
        std::fs::write(
            &config_path,
            r#"
[[importers]]
name = "mybank"
account = "Assets:Bank:MyBank"
currency = "USD"
date_column = "Date"
narration_column = "Description"
amount_column = "Amount"
default_expense = "Expenses:Uncategorized"

[importers.mappings]
"GROCERY" = "Expenses:Food"
"#,
        )
        .unwrap();

        // Write CSV (negative amounts = money out = expenses)
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n\
             2024-01-15,GROCERY STORE,-50.00\n\
             2024-01-16,RANDOM PURCHASE,-25.00\n",
        )
        .unwrap();

        // Load config and extract
        let importers_file = load_importers_config(&config_path).unwrap();
        let entry = importers_file
            .importers
            .iter()
            .find(|e| e.name == "mybank")
            .unwrap();
        let config = build_config_from_entry(entry).unwrap();
        let result = rustledger_importer::csv_importer::CsvImporter
            .extract_file(&csv_path, &config)
            .unwrap();

        assert_eq!(result.directives.len(), 2);

        // First should map to Expenses:Food via mapping
        if let rustledger_core::Directive::Transaction(txn) = &result.directives[0] {
            assert_eq!(txn.postings[0].account.as_str(), "Assets:Bank:MyBank");
            assert_eq!(txn.postings[1].account.as_str(), "Expenses:Food");
        } else {
            panic!("Expected transaction");
        }

        // Second should use default_expense since no mapping matches
        if let rustledger_core::Directive::Transaction(txn) = &result.directives[1] {
            assert_eq!(txn.postings[1].account.as_str(), "Expenses:Uncategorized");
        } else {
            panic!("Expected transaction");
        }
    }

    // Note: the `is_ofx_file` helper was removed when the OFX-
    // specific branch in `run()` was unified into the generic
    // "non-CSV dispatcher" path. OFX extension matching is now
    // owned entirely by `OfxImporter::identify` (via the registry),
    // so no separate helper exists to test.

    // ===== Importer dispatch (select_importer) =====
    //
    // These pin the four interesting cases for which Importer the CLI
    // selects for a given (file, args) combination. The bug they guard
    // against is the regression where `--importer <toml-csv-entry>` on a
    // `.ofx`-named file would silently dispatch to `OfxImporter` and drop
    // the user's column mappings.

    #[test]
    fn test_select_importer_csv_extension_picks_csv() {
        let registry = ImporterRegistry::with_builtins();
        let args = Args::parse_from(["extract", "ignored.csv"]);
        let imp = select_importer(&registry, Path::new("foo.csv"), &args);
        assert_eq!(imp.name(), "CSV");
    }

    #[test]
    fn test_select_importer_ofx_extension_picks_ofx() {
        let registry = ImporterRegistry::with_builtins();
        let args = Args::parse_from(["extract", "ignored.ofx"]);
        let imp = select_importer(&registry, Path::new("foo.ofx"), &args);
        assert_eq!(imp.name(), "OFX/QFX");
    }

    #[test]
    fn test_select_importer_explicit_importer_flag_forces_csv_even_on_ofx_file() {
        // Regression guard: prior to this PR, `--importer chase` on a
        // `.ofx`-named file took the CSV path correctly. After Wave 2.2,
        // registry.identify() picks OfxImporter from the extension — which
        // would silently drop the CSV column mappings. select_importer
        // must override this case.
        let registry = ImporterRegistry::with_builtins();
        let args = Args::parse_from(["extract", "ignored.ofx", "--importer", "chase"]);
        let imp = select_importer(&registry, Path::new("foo.ofx"), &args);
        assert_eq!(
            imp.name(),
            "CSV",
            "TOML --importer entries must force CSV dispatch regardless of file extension"
        );
    }

    #[test]
    fn test_select_importer_unknown_extension_falls_back_to_csv() {
        // .qbo Quicken exports are a common case: user has a TOML CSV
        // entry to parse them. Even without --importer, the fallback
        // path should choose CSV rather than erroring.
        let registry = ImporterRegistry::with_builtins();
        let args = Args::parse_from(["extract", "ignored.qbo"]);
        let imp = select_importer(&registry, Path::new("foo.qbo"), &args);
        assert_eq!(imp.name(), "CSV");
    }

    #[test]
    fn test_select_importer_config_alone_does_not_force_csv() {
        // Regression: `--config x.toml` alone (no --importer) used to
        // force CSV dispatch, which silently broke combinations like
        // `--config x.toml --wasm-importer my-mt940.wasm foo.mt940`
        // (registered WASM was never consulted). With the fix,
        // --config alone consults the registry so WASM importers stay
        // reachable. A .csv file still resolves to CSV via
        // registry.identify, not via the force-CSV path.
        use rustledger_importer::test_fixtures::identifying_wat;
        let tmp = tempfile::tempdir().unwrap();
        let wasm_path = tmp.path().join("mt.wasm");
        std::fs::write(
            &wasm_path,
            wat::parse_str(identifying_wat("mt9")).expect("WAT parses"),
        )
        .unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let cfg_path = cfg_dir.path().join("importers.toml");
        std::fs::write(&cfg_path, "").unwrap(); // empty but valid toml

        let args = Args::parse_from([
            "extract",
            "foo.mt940",
            "--config",
            cfg_path.to_str().unwrap(),
            "--wasm-importer",
            wasm_path.to_str().unwrap(),
        ]);
        let registry = build_registry(&args).expect("builds");
        let imp = select_importer(&registry, Path::new("foo.mt940"), &args);
        assert_eq!(
            imp.name(),
            "mt9",
            "WASM importer should win when --config is set alone (no --importer)"
        );
    }

    #[test]
    #[cfg(feature = "python-plugin-wasm")]
    fn resolve_scan_dirs_propagates_error_for_explicit_missing_config() {
        // --config /missing.toml should error loudly, not silently
        // degrade to "no WASM scan dirs".
        let args = Args::parse_from([
            "extract",
            "--config",
            "/this/path/does/not/exist/importers.toml",
        ]);
        let result = resolve_scan_dirs(&args);
        let Err(err) = result else {
            panic!("explicit missing --config should error");
        };
        let msg = format!("{err:#}");
        assert!(
            msg.contains("does/not/exist"),
            "error should name the missing path: {msg}"
        );
    }

    #[test]
    #[cfg(feature = "python-plugin-wasm")]
    fn resolve_scan_dirs_soft_fails_for_implicit_missing_config() {
        // No --config provided, no importers.toml in cwd/XDG → empty
        // scan dirs, no error. This is the right behavior because
        // the user didn't ask for any config; absence is expected.
        let args = Args::parse_from(["extract"]);
        let dirs = resolve_scan_dirs(&args).expect("implicit missing is soft-fail");
        // Could be empty or non-empty depending on whether a real
        // ~/.config/rledger/importers.toml exists in this test env.
        // What we're asserting is that it didn't error.
        let _ = dirs;
    }

    #[test]
    fn run_dispatches_to_wasm_importer_with_config_set_but_no_toml_profiles() {
        // End-to-end regression for the bug my earlier
        // select_importer fix didn't fully close: a user runs
        // `extract foo.X --config wasm-only.toml --wasm-importer my.wasm`
        // where wasm-only.toml has *no* [[importers]] entries. The
        // dispatcher should be the WASM module; the CSV-branch
        // config-building must NOT fire and error out on "No
        // importers defined". Run through run() (not just
        // select_importer) so the dispatcher-first config-selection
        // path is actually exercised.
        use rustledger_importer::test_fixtures::identifying_wat;
        let tmp = tempfile::tempdir().unwrap();

        // WAT importer that identifies every file as its own (so it
        // wins .mt940 dispatch against the CSV fallback) and returns
        // an empty ImporterOutput for extract.
        let wasm_path = tmp.path().join("my.wasm");
        std::fs::write(
            &wasm_path,
            wat::parse_str(identifying_wat("mt9")).expect("WAT"),
        )
        .unwrap();

        // wasm-only.toml: sets wasm_importer_dir to nothing useful,
        // critically has NO [[importers]] entries. Pre-fix, the CSV
        // branch would load this and error "No importers defined".
        let cfg_path = tmp.path().join("wasm-only.toml");
        std::fs::write(&cfg_path, "").unwrap();

        // Source file the WASM importer will be asked to handle.
        // The actual contents don't matter — the WAT extract()
        // returns (ptr=0, len=0) which decodes to an empty output.
        let src_path = tmp.path().join("statement.mt940");
        std::fs::write(&src_path, b"any bytes").unwrap();

        let out_path = tmp.path().join("out.beancount");
        let args = Args::parse_from([
            "extract",
            src_path.to_str().unwrap(),
            "--config",
            cfg_path.to_str().unwrap(),
            "--wasm-importer",
            wasm_path.to_str().unwrap(),
            "--output",
            out_path.to_str().unwrap(),
        ]);

        // The bug shape: run() previously errored with "No importers
        // defined in ...". With the dispatcher-first fix, run()
        // completes successfully and writes the empty output.
        // (Empty msgpack from the WAT extract() decodes to an empty
        // PluginOutput → no directives → empty .beancount file.)
        if let Err(e) = run(&args, &src_path) {
            let msg = format!("{e:#}");
            assert!(
                !msg.contains("No importers defined"),
                "regression: CSV-branch error fired before WASM dispatch: {msg}"
            );
            // Other errors (e.g. wasmtime decode of `(0, 0)`) are
            // unrelated to the bug under test — what we're pinning
            // is that we don't error out before reaching the WASM
            // importer.
        }
    }

    #[test]
    fn test_load_existing_transactions() {
        let dir = tempfile::tempdir().unwrap();
        let ledger_path = dir.path().join("ledger.beancount");
        std::fs::write(
            &ledger_path,
            r#"2024-01-15 * "GROCERY STORE" "Weekly groceries"
  Assets:Bank:Checking  -50.00 USD
  Expenses:Food          50.00 USD

2024-01-16 * "NETFLIX" "Monthly subscription"
  Assets:Bank:Checking  -15.99 USD
  Expenses:Entertainment 15.99 USD
"#,
        )
        .unwrap();

        let txns = load_existing_transactions(&ledger_path).unwrap();
        assert_eq!(txns.len(), 2);
        assert_eq!(
            txns[0].date,
            rustledger_core::naive_date(2024, 1, 15).unwrap()
        );
        assert_eq!(
            txns[1].date,
            rustledger_core::naive_date(2024, 1, 16).unwrap()
        );
    }

    #[test]
    fn test_load_existing_resolves_includes_and_interpolates() {
        // Regression: a raw parse only saw the top file and left elided amounts
        // as None. Routing through the loader pipeline makes `include`d
        // transactions visible AND fills the interpolated amount — both needed so
        // dedup compares against the user's real (resolved, booked) ledger.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("sub.beancount"),
            "2024-02-01 * \"PHONE BILL\" \"Monthly\"\n  \
             Assets:Bank:Checking  -40.00 USD\n  Expenses:Phone\n",
        )
        .unwrap();
        let main_path = dir.path().join("main.beancount");
        std::fs::write(
            &main_path,
            "include \"sub.beancount\"\n\n2024-01-15 * \"GROCERY STORE\" \"Weekly\"\n  \
             Assets:Bank:Checking  -50.00 USD\n  Expenses:Food          50.00 USD\n",
        )
        .unwrap();

        let txns = load_existing_transactions(&main_path).unwrap();
        // The INCLUDED transaction is visible (a raw parse missed it entirely).
        assert_eq!(txns.len(), 2, "included transaction must be loaded");
        let phone = txns
            .iter()
            .find(|t| t.narration.as_str() == "Monthly")
            .expect("included PHONE BILL transaction must be present");
        // Its elided `Expenses:Phone` posting was interpolated (raw parse: None).
        let amount = phone
            .postings
            .iter()
            .find(|p| p.account.as_str() == "Expenses:Phone")
            .and_then(|p| p.units.as_ref())
            .and_then(rustledger_core::IncompleteAmount::number);
        assert_eq!(
            amount,
            Some("40.00".parse::<rust_decimal::Decimal>().unwrap()),
            "elided posting must be interpolated by booking",
        );
    }

    #[test]
    fn test_end_to_end_output_file() {
        let dir = tempfile::tempdir().unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,5.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("2024-01-15"));
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_end_to_end_existing_dedup() {
        let dir = tempfile::tempdir().unwrap();

        // Write existing ledger
        let ledger_path = dir.path().join("ledger.beancount");
        std::fs::write(
            &ledger_path,
            r#"2024-01-15 * "Coffee"
  Assets:Bank:Checking  5.00 USD
  Expenses:Unknown      -5.00 USD
"#,
        )
        .unwrap();

        // Write CSV with same + new transaction
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n\
             2024-01-15,Coffee,5.00\n\
             2024-01-16,Lunch,12.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--existing",
            ledger_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        // The Coffee transaction should be filtered as duplicate
        assert!(!output.contains("Coffee"));
        // The Lunch transaction should remain
        assert!(output.contains("Lunch"));
    }

    #[test]
    fn test_parse_column_value_unsupported_type() {
        // Boolean TOML values should return None
        assert_eq!(parse_column_value(&toml::Value::Boolean(true)), None);
        // Float TOML values should return None
        assert_eq!(parse_column_value(&toml::Value::Float(1.5)), None);
    }

    #[test]
    fn test_run_with_importer_config() {
        let dir = tempfile::tempdir().unwrap();

        // Write importers.toml
        let config_path = dir.path().join("importers.toml");
        std::fs::write(
            &config_path,
            r#"
[[importers]]
name = "mybank"
account = "Assets:Bank:MyBank"
currency = "USD"
date_column = "Date"
narration_column = "Description"
amount_column = "Amount"
"#,
        )
        .unwrap();

        // Write CSV
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,5.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--importer",
            "mybank",
            "--config",
            config_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("Assets:Bank:MyBank"));
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_run_with_importer_not_found() {
        let dir = tempfile::tempdir().unwrap();

        let config_path = dir.path().join("importers.toml");
        std::fs::write(
            &config_path,
            "[[importers]]\nname = \"other\"\naccount = \"Assets:Bank\"\n",
        )
        .unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(&csv_path, "Date,Description,Amount\n").unwrap();

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--importer",
            "nonexistent",
            "--config",
            config_path.to_str().unwrap(),
        ]);

        let err = run(&args, &csv_path).unwrap_err();
        assert!(err.to_string().contains("not found"));
        assert!(err.to_string().contains("other"));
    }

    #[test]
    fn test_run_with_importer_no_config_file() {
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(&csv_path, "Date,Description,Amount\n").unwrap();

        // Point --config to a non-existent file
        let config_path = dir.path().join("nonexistent.toml");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--importer",
            "mybank",
            "--config",
            config_path.to_str().unwrap(),
        ]);

        let err = run(&args, &csv_path).unwrap_err();
        assert!(err.to_string().contains("Importers config not found"));
    }

    #[test]
    fn test_run_stdout_output() {
        // Test the stdout path (no -o flag) — just ensure it doesn't error
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,5.00\n",
        )
        .unwrap();

        let args = Args::parse_from(["extract", csv_path.to_str().unwrap()]);
        // Should succeed writing to stdout
        run(&args, &csv_path).unwrap();
    }

    #[test]
    fn test_run_with_optional_cli_args() {
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Payee,Description,Debit,Credit\n\
             2024-01-15,Store,Coffee,5.00,\n\
             2024-01-16,Employer,Salary,,1000.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--payee-column",
            "Payee",
            "--debit-column",
            "Debit",
            "--credit-column",
            "Credit",
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("2024-01-15"));
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_load_existing_transactions_nonexistent_file() {
        let result = load_existing_transactions(Path::new("/nonexistent/ledger.beancount"));
        assert!(result.is_err());
    }

    #[test]
    fn test_load_existing_transactions_with_non_txn_directives() {
        let dir = tempfile::tempdir().unwrap();
        let ledger_path = dir.path().join("ledger.beancount");
        std::fs::write(
            &ledger_path,
            r#"2024-01-01 open Assets:Bank:Checking USD

2024-01-15 * "Coffee"
  Assets:Bank:Checking  -5.00 USD
  Expenses:Food          5.00 USD

2024-01-31 balance Assets:Bank:Checking 1000.00 USD
"#,
        )
        .unwrap();

        let txns = load_existing_transactions(&ledger_path).unwrap();
        // Only the transaction should be loaded, not open/balance
        assert_eq!(txns.len(), 1);
    }

    #[test]
    fn test_end_to_end_dedup_no_duplicates() {
        let dir = tempfile::tempdir().unwrap();

        let ledger_path = dir.path().join("ledger.beancount");
        std::fs::write(
            &ledger_path,
            r#"2024-01-10 * "Old transaction"
  Assets:Bank:Checking  10.00 USD
  Expenses:Unknown     -10.00 USD
"#,
        )
        .unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,5.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--existing",
            ledger_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        // No duplicates, so Coffee should remain
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_run_with_importers_config_alias() {
        // Test that --importers-config alias still works
        let dir = tempfile::tempdir().unwrap();

        let config_path = dir.path().join("importers.toml");
        std::fs::write(
            &config_path,
            r#"
[[importers]]
name = "test"
account = "Assets:Bank"
date_column = "Date"
narration_column = "Description"
amount_column = "Amount"
"#,
        )
        .unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(&csv_path, "Date,Description,Amount\n2024-01-15,Test,5.00\n").unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--importer",
            "test",
            "--importers-config",
            config_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("Assets:Bank"));
    }

    #[test]
    fn test_run_with_ofx_file() {
        let dir = tempfile::tempdir().unwrap();
        let ofx_path = dir.path().join("statement.ofx");
        std::fs::write(
            &ofx_path,
            r"OFXHEADER:100
DATA:OFXSGML
VERSION:102
SECURITY:NONE
ENCODING:USASCII
CHARSET:1252
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE

<OFX>
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<DTSERVER>20240115120000
<LANGUAGE>ENG
</SONRS>
</SIGNONMSGSRSV1>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>1001
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<STMTRS>
<CURDEF>USD
<BANKACCTFROM>
<BANKID>123456789
<ACCTID>987654321
<ACCTTYPE>CHECKING
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>20240101
<DTEND>20240131
<STMTTRN>
<TRNTYPE>DEBIT
<DTPOSTED>20240115
<TRNAMT>-50.00
<FITID>2024011501
<NAME>GROCERY STORE
<MEMO>Weekly groceries
</STMTTRN>
</BANKTRANLIST>
<LEDGERBAL>
<BALAMT>5000.00
<DTASOF>20240131
</LEDGERBAL>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            ofx_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &ofx_path).unwrap();
        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("2024-01-15"));
        assert!(output.contains("GROCERY STORE"));
    }

    #[test]
    fn test_run_with_amount_format_arg() {
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.tsv");
        // Use tab delimiter to avoid conflict with comma decimal separator
        std::fs::write(
            &csv_path,
            "Date\tDescription\tAmount\n2024-01-15\tCoffee\t1.234,56\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--amount-format",
            "#.##0,00",
            "--delimiter",
            "\t",
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();
        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_run_with_amount_locale_arg() {
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,5.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--amount-locale",
            "en_US",
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();
        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("5.00"));
    }

    #[test]
    fn test_run_with_invalid_locale() {
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,5.00\n",
        )
        .unwrap();

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--amount-locale",
            "invalid_LOCALE_xyz",
        ]);

        let err = run(&args, &csv_path).unwrap_err();
        assert!(err.to_string().contains("not a valid locale"));
    }

    #[test]
    fn test_run_with_csv_that_generates_warnings() {
        let dir = tempfile::tempdir().unwrap();
        let csv_path = dir.path().join("statement.csv");
        // Include a row with an invalid date to trigger a warning
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n\
             2024-01-15,Coffee,5.00\n\
             not-a-date,Bad Row,10.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        // Should succeed — bad row generates warning but doesn't fail
        run(&args, &csv_path).unwrap();
        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_run_auto_select_sole_importer() {
        let dir = tempfile::tempdir().unwrap();

        // Config with exactly one importer — should auto-select
        let config_path = dir.path().join("importers.toml");
        std::fs::write(
            &config_path,
            r#"
[[importers]]
name = "mybank"
account = "Assets:Bank:Auto"
date_column = "Date"
narration_column = "Description"
amount_column = "Amount"
"#,
        )
        .unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(
            &csv_path,
            "Date,Description,Amount\n2024-01-15,Coffee,-5.00\n",
        )
        .unwrap();

        let output_path = dir.path().join("output.beancount");

        // No --importer flag, but --config points to a single-importer file
        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--config",
            config_path.to_str().unwrap(),
            "-o",
            output_path.to_str().unwrap(),
        ]);

        run(&args, &csv_path).unwrap();

        let output = std::fs::read_to_string(&output_path).unwrap();
        assert!(output.contains("Assets:Bank:Auto"));
        assert!(output.contains("Coffee"));
    }

    #[test]
    fn test_run_auto_select_errors_on_multiple_importers() {
        let dir = tempfile::tempdir().unwrap();

        // Both importers have filename patterns that match "statement.csv"
        let config_path = dir.path().join("importers.toml");
        std::fs::write(
            &config_path,
            r#"
[[importers]]
name = "checking"
account = "Assets:Bank:Checking"
filename_pattern = "*.csv"

[[importers]]
name = "credit"
account = "Liabilities:CreditCard"
filename_pattern = "statement*"
"#,
        )
        .unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(&csv_path, "Date,Description,Amount\n").unwrap();

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--config",
            config_path.to_str().unwrap(),
        ]);

        let err = run(&args, &csv_path).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Multiple importers"));
        assert!(msg.contains("checking"));
        assert!(msg.contains("credit"));
    }

    #[test]
    fn test_run_auto_select_errors_on_empty_config() {
        let dir = tempfile::tempdir().unwrap();

        let config_path = dir.path().join("importers.toml");
        std::fs::write(&config_path, "importers = []\n").unwrap();

        let csv_path = dir.path().join("statement.csv");
        std::fs::write(&csv_path, "Date,Description,Amount\n").unwrap();

        let args = Args::parse_from([
            "extract",
            csv_path.to_str().unwrap(),
            "--config",
            config_path.to_str().unwrap(),
        ]);

        let err = run(&args, &csv_path).unwrap_err();
        assert!(err.to_string().contains("No importers defined"));
    }

    // ===== build_registry / WASM discovery integration tests =====

    /// Wrapper around the shared
    /// [`rustledger_importer::test_fixtures::metadata_wat`] helper so
    /// tests below can write WAT bytes in one call. Single source of
    /// truth for the WAT shape lives in `rustledger-importer`; the
    /// CLI tests just consume it.
    fn wasm_importer_with_name(name: &str) -> Vec<u8> {
        let wat = rustledger_importer::test_fixtures::metadata_wat(name);
        wat::parse_str(&wat).expect("WAT parses")
    }

    #[test]
    fn build_registry_defaults_to_builtins_only() {
        // No --wasm-importer, no --wasm-importer-dir, no toml.
        let args = Args::parse_from(["extract"]);
        let registry = build_registry(&args).expect("builds");
        // OFX + CSV.
        assert_eq!(registry.len(), 2);
        assert!(registry.find_by_name("CSV").is_some());
        assert!(registry.find_by_name("OFX").is_some());
    }

    #[test]
    fn build_registry_loads_cli_wasm_importer_ahead_of_builtins() {
        let tmp = tempfile::tempdir().unwrap();
        let wasm_path = tmp.path().join("ad-hoc.wasm");
        std::fs::write(&wasm_path, wasm_importer_with_name("usr")).unwrap();

        let args = Args::parse_from(["extract", "--wasm-importer", wasm_path.to_str().unwrap()]);
        let registry = build_registry(&args).expect("builds");
        // 1 user-WASM + 2 built-ins.
        assert_eq!(registry.len(), 3);
        assert!(registry.find_by_name("usr").is_some());
        // Built-ins still present so CSV/OFX dispatch keeps working.
        assert!(registry.find_by_name("CSV").is_some());
        assert!(registry.find_by_name("OFX").is_some());
    }

    #[test]
    fn build_registry_scans_directory_from_cli_flag() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("aaa.wasm"), wasm_importer_with_name("aaa")).unwrap();
        std::fs::write(tmp.path().join("bbb.wasm"), wasm_importer_with_name("bbb")).unwrap();

        let args = Args::parse_from([
            "extract",
            "--wasm-importer-dir",
            tmp.path().to_str().unwrap(),
        ]);
        let registry = build_registry(&args).expect("builds");
        // 2 scanned + 2 built-ins.
        assert_eq!(registry.len(), 4);
        assert!(registry.find_by_name("aaa").is_some());
        assert!(registry.find_by_name("bbb").is_some());
    }

    #[test]
    fn build_registry_reads_wasm_importer_dir_from_importers_toml() {
        // Two temp dirs: one for the .wasm modules, one for the
        // importers.toml that points at the wasm dir.
        let wasm_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            wasm_dir.path().join("xyz.wasm"),
            wasm_importer_with_name("xyz"),
        )
        .unwrap();

        let cfg_dir = tempfile::tempdir().unwrap();
        let cfg_path = cfg_dir.path().join("importers.toml");
        std::fs::write(
            &cfg_path,
            format!("wasm_importer_dir = \"{}\"\n", wasm_dir.path().display()),
        )
        .unwrap();

        let args = Args::parse_from(["extract", "--config", cfg_path.to_str().unwrap()]);
        let registry = build_registry(&args).expect("builds");
        assert!(
            registry.find_by_name("xyz").is_some(),
            "xyz should be loaded via importers.toml's wasm_importer_dir"
        );
    }

    #[test]
    fn build_registry_cli_dir_flag_overrides_importers_toml_setting() {
        // toml setting points at a dir with 'tom.wasm'; CLI flag
        // points at a different dir with 'cli.wasm'. Only the CLI one
        // should load.
        let toml_only_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            toml_only_dir.path().join("tom.wasm"),
            wasm_importer_with_name("tom"),
        )
        .unwrap();

        let cli_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            cli_dir.path().join("cli.wasm"),
            wasm_importer_with_name("cli"),
        )
        .unwrap();

        let cfg_dir = tempfile::tempdir().unwrap();
        let cfg_path = cfg_dir.path().join("importers.toml");
        std::fs::write(
            &cfg_path,
            format!(
                "wasm_importer_dir = \"{}\"\n",
                toml_only_dir.path().display()
            ),
        )
        .unwrap();

        let args = Args::parse_from([
            "extract",
            "--config",
            cfg_path.to_str().unwrap(),
            "--wasm-importer-dir",
            cli_dir.path().to_str().unwrap(),
        ]);
        let registry = build_registry(&args).expect("builds");
        assert!(
            registry.find_by_name("cli").is_some(),
            "CLI-flag dir should be scanned"
        );
        assert!(
            registry.find_by_name("tom").is_none(),
            "toml-setting dir should be skipped when CLI flag is set"
        );
    }

    #[test]
    fn build_registry_propagates_cli_wasm_importer_load_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let bad_path = tmp.path().join("bogus.wasm");
        std::fs::write(&bad_path, b"not valid wasm").unwrap();

        let args = Args::parse_from(["extract", "--wasm-importer", bad_path.to_str().unwrap()]);
        // ImporterRegistry doesn't impl Debug, so destructure manually
        // instead of `.expect_err`.
        let Err(err) = build_registry(&args) else {
            panic!("bogus wasm should fail to load");
        };
        let msg = format!("{err:#}");
        assert!(
            msg.contains("bogus.wasm"),
            "error should name the failing path: {msg}"
        );
    }

    #[test]
    fn build_registry_scans_multiple_cli_dirs_in_order() {
        // --wasm-importer-dir is repeatable; both dirs should be
        // scanned, with registration order = arg order.
        let dir_a = tempfile::tempdir().unwrap();
        std::fs::write(
            dir_a.path().join("aaa.wasm"),
            wasm_importer_with_name("aaa"),
        )
        .unwrap();
        let dir_b = tempfile::tempdir().unwrap();
        std::fs::write(
            dir_b.path().join("bbb.wasm"),
            wasm_importer_with_name("bbb"),
        )
        .unwrap();

        let args = Args::parse_from([
            "extract",
            "--wasm-importer-dir",
            dir_a.path().to_str().unwrap(),
            "--wasm-importer-dir",
            dir_b.path().to_str().unwrap(),
        ]);
        let registry = build_registry(&args).expect("builds");
        assert!(registry.find_by_name("aaa").is_some(), "first dir loaded");
        assert!(registry.find_by_name("bbb").is_some(), "second dir loaded");
    }

    #[test]
    fn build_registry_accepts_toml_dir_as_list() {
        // wasm_importer_dir = ["a", "b"] in importers.toml.
        let dir_a = tempfile::tempdir().unwrap();
        std::fs::write(
            dir_a.path().join("one.wasm"),
            wasm_importer_with_name("one"),
        )
        .unwrap();
        let dir_b = tempfile::tempdir().unwrap();
        std::fs::write(
            dir_b.path().join("two.wasm"),
            wasm_importer_with_name("two"),
        )
        .unwrap();

        let cfg_dir = tempfile::tempdir().unwrap();
        let cfg_path = cfg_dir.path().join("importers.toml");
        std::fs::write(
            &cfg_path,
            format!(
                "wasm_importer_dir = [\"{}\", \"{}\"]\n",
                dir_a.path().display(),
                dir_b.path().display()
            ),
        )
        .unwrap();

        let args = Args::parse_from(["extract", "--config", cfg_path.to_str().unwrap()]);
        let registry = build_registry(&args).expect("builds");
        assert!(registry.find_by_name("one").is_some());
        assert!(registry.find_by_name("two").is_some());
    }

    #[test]
    fn build_registry_skip_and_collect_loads_good_modules_past_failures() {
        // Mix one valid and one invalid .wasm in a scanned dir. The
        // valid one should still register; the failure is logged to
        // stderr (not asserted here — we just check the registry
        // didn't abort).
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("good.wasm"), wasm_importer_with_name("aaa")).unwrap();
        std::fs::write(tmp.path().join("bad-zzz.wasm"), b"not valid wasm").unwrap();

        let args = Args::parse_from([
            "extract",
            "--wasm-importer-dir",
            tmp.path().to_str().unwrap(),
        ]);
        let registry = build_registry(&args).expect("scan continues past failure");
        assert!(
            registry.find_by_name("aaa").is_some(),
            "good module loaded despite sibling failure"
        );
    }

    #[test]
    fn build_registry_cli_wasm_importer_wins_over_dir_scanned_same_name() {
        // Duplicate metadata.name from a CLI flag vs a scanned dir.
        // CLI registration is first, so find_by_name returns it. The
        // dir-scanned same-named module is also registered (both
        // exist in the list) but unreachable via find_by_name.
        let cli_dir = tempfile::tempdir().unwrap();
        let cli_path = cli_dir.path().join("cli.wasm");
        std::fs::write(&cli_path, wasm_importer_with_name("dup")).unwrap();

        let scan_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            scan_dir.path().join("scanned.wasm"),
            wasm_importer_with_name("dup"),
        )
        .unwrap();

        let args = Args::parse_from([
            "extract",
            "--wasm-importer",
            cli_path.to_str().unwrap(),
            "--wasm-importer-dir",
            scan_dir.path().to_str().unwrap(),
        ]);
        let registry = build_registry(&args).expect("builds");
        // Both registered.
        assert_eq!(registry.len(), 4, "1 CLI + 1 dir-scanned + 2 builtins");
        // CLI one wins find_by_name because it's first.
        assert!(registry.find_by_name("dup").is_some());
        // Two entries with the same name in list_importers.
        let dup_count = registry
            .list_importers()
            .iter()
            .filter(|(name, _)| *name == "dup")
            .count();
        assert_eq!(dup_count, 2, "both same-named modules are registered");
    }

    #[test]
    #[cfg(feature = "python-plugin-wasm")]
    fn expand_tilde_resolves_tilde_prefix() {
        use super::config::expand_tilde;
        if let Some(home) = dirs::home_dir() {
            assert_eq!(expand_tilde(Path::new("~")), home);
            assert_eq!(
                expand_tilde(Path::new("~/foo/bar")),
                home.join("foo").join("bar")
            );
        }
        // No leading tilde → identity.
        assert_eq!(expand_tilde(Path::new("/abs/path")), Path::new("/abs/path"));
        assert_eq!(expand_tilde(Path::new("rel/path")), Path::new("rel/path"));
        // ~user is not supported — left as-is.
        assert_eq!(
            expand_tilde(Path::new("~other/foo")),
            Path::new("~other/foo")
        );
    }
}