doppio 0.2.0

A typed compiler pipeline for plain-text Ledger accounting — parse, resolve, and elaborate .ledger files with a library API built for programmatic use.
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
use std::{
    collections::{BTreeMap, BTreeSet},
    fs::File,
    io::{Read as _, Write as _},
    path::PathBuf,
};

use clap::{Parser, Subcommand};
use regex::Regex;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Parse and compile a ledger source file into a binary `.dop` archive.
    ///
    /// The output is a postcard-serialised, XZ-compressed snapshot of the
    /// elaborated journal. Loading a `.dop` file is much faster than
    /// re-parsing the source, making it suitable for large ledgers that are
    /// queried repeatedly.
    Compile {
        /// Path for the output `.dop` file.
        #[arg(short, long)]
        output: PathBuf,
        /// Path to the root `.ledger` source file (may use `include`).
        source: PathBuf,
    },

    /// Print the running balance for every account, optionally filtered by account name.
    ///
    /// Accepts either a raw `.ledger` source file or a pre-compiled `.dop`
    /// file. Output is formatted with the commodity and value right-aligned,
    /// followed by the account name.
    ///
    /// By default, output is rendered in tree form with indentation. Pass
    /// `--flat` to revert to the classic single-line-per-account format.
    /// `PATTERN` is a case-insensitive regular expression matched against the
    /// account name. Plain substrings are valid regex and match as literals.
    /// Omit it to show all accounts.
    Balance {
        source: PathBuf,
        /// Optional case-insensitive regex filter on account names.
        pattern: Option<String>,
        /// Include only transactions on or after this date (YYYY-MM-DD).
        #[arg(long)]
        begin: Option<String>,
        /// Include only transactions on or before this date (YYYY-MM-DD).
        #[arg(long)]
        end: Option<String>,
        /// Include only cleared transactions.
        #[arg(long)]
        cleared: bool,
        /// Include only transactions tagged with this tag.
        #[arg(long)]
        tag: Option<String>,
        /// Collapse accounts deeper than N colon-separated levels into their parent.
        #[arg(long)]
        depth: Option<usize>,
        /// Print flat output (full account names, no indentation) instead of the
        /// default tree view.
        #[arg(long, default_value_t = false)]
        flat: bool,
        /// Output format: text (default), json, or csv.
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// List individual postings, optionally filtered by account name.
    ///
    /// `PATTERN` is a case-insensitive regular expression matched against the
    /// account name. Plain substrings are valid regex and match as literals.
    /// Omit it to list all postings.
    Register {
        source: PathBuf,
        pattern: Option<String>,
        /// Only include transactions on or after this date (YYYY-MM-DD).
        #[arg(long)]
        begin: Option<String>,
        /// Only include transactions on or before this date (YYYY-MM-DD).
        #[arg(long)]
        end: Option<String>,
        /// Include only cleared transactions.
        #[arg(long, default_value_t = false)]
        cleared: bool,
        /// Include only transactions tagged with this tag.
        #[arg(long)]
        tag: Option<String>,
        /// Output format: text (default), json, or csv.
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// Re-emit the journal as canonical Ledger source text.
    ///
    /// Parses and resolves the source file, then prints each transaction in
    /// canonical Ledger format. Only `.ledger` source files are accepted;
    /// pre-compiled `.dop` files do not preserve the original transaction
    /// structure needed for faithful re-emission.
    Print {
        /// Path to the root `.ledger` source file.
        source: PathBuf,
    },

    /// List all accounts that appear in the journal, one per line.
    ///
    /// Output is sorted alphabetically. Pass `PATTERN` to restrict the list
    /// to accounts whose name contains the pattern (case-insensitive).
    Accounts {
        source: PathBuf,
        /// Optional case-insensitive substring filter on account names.
        pattern: Option<String>,
    },

    /// List all commodity symbols used in the journal, one per line.
    ///
    /// Output is sorted and deduplicated.
    Commodities { source: PathBuf },

    /// Print a summary of the journal: transaction count, unique accounts,
    /// unique commodities, and the date range covered.
    Stats { source: PathBuf },
}

/// The set of supported output formats for `balance` and `register`.
enum OutputFormat {
    Text,
    Json,
    Csv,
}

impl OutputFormat {
    /// Parse the format string, returning an error with valid options listed.
    fn parse(s: &str) -> Result<Self, Box<dyn std::error::Error>> {
        match s {
            "text" => Ok(OutputFormat::Text),
            "json" => Ok(OutputFormat::Json),
            "csv" => Ok(OutputFormat::Csv),
            other => Err(format!(
                "unknown format {:?}; valid options are: text, json, csv",
                other
            )
            .into()),
        }
    }
}

/// Load a [`doppio::Journal`] from either a compiled `.dop` file or a raw
/// `.ledger` source file.
///
/// The file type is detected by extension:
/// - `.dop` — decompress with XZ and deserialise with postcard.
/// - anything else — parse as Ledger source text, resolving `include`
///   directives relative to the file's parent directory.
fn load_journal(path: &PathBuf) -> Result<doppio::Journal, Box<dyn std::error::Error>> {
    if let Some("dop") = path.extension().and_then(|e| e.to_str()) {
        // Pre-compiled binary format: validate 8-byte header, then decompress
        // and deserialise.
        let mut f = File::open(path)?;
        doppio::dop_read_header(&mut f, path)?;
        // The 100 KiB scratch buffer is required by postcard's `from_io` API;
        // it does not limit the total data read.
        let input_xz = xz::read::XzDecoder::new(f);
        let buf_input = std::io::BufReader::new(input_xz);
        let mut buf = vec![0; 102400];
        Ok(postcard::from_io((buf_input, &mut buf))?.0)
    } else {
        let base_path = path.parent().unwrap().to_path_buf();
        let parser = doppio::parser::Parser {
            opener: doppio::file_opener,
            base_path,
        };
        let mut file = String::new();
        File::open(path)?.read_to_string(&mut file)?;
        Ok(doppio::compile(&file, parser)?)
    }
}

/// Truncate an account name to at most `depth` colon-separated components.
///
/// Returns a subslice of `account` ending at the position of the `depth`-th
/// colon, or the full string if it has fewer than `depth` components.
///
/// # Examples
///
/// ```
/// assert_eq!(truncate_account("Expenses:Food:Restaurants", 2), "Expenses:Food");
/// assert_eq!(truncate_account("Assets:Checking", 1), "Assets");
/// assert_eq!(truncate_account("Assets", 1), "Assets");
/// ```
fn truncate_account(account: &str, depth: usize) -> &str {
    let mut colon_pos = None;
    let mut count = 0;
    for (i, c) in account.char_indices() {
        if c == ':' {
            count += 1;
            if count == depth {
                colon_pos = Some(i);
                break;
            }
        }
    }
    match colon_pos {
        Some(pos) => &account[..pos],
        None => account,
    }
}

/// Compile an optional account-filter pattern into a [`Regex`].
///
/// If `pattern` is `None`, returns a regex that matches everything (`.*`).
/// Otherwise wraps the pattern with `(?i)` for case-insensitive matching.
/// Returns an error with a clear message if the regex is syntactically invalid.
fn build_pattern_regex(pattern: Option<String>) -> Result<Regex, Box<dyn std::error::Error>> {
    let raw = match pattern {
        Some(p) => format!("(?i){}", p),
        None => ".*".to_string(),
    };
    Regex::new(&raw).map_err(|e| format!("invalid account pattern: {e}").into())
}

struct JournalFilter {
    pattern: Regex,
    begin_date: Option<chrono::NaiveDate>,
    end_date: Option<chrono::NaiveDate>,
    cleared: bool,
    tag: Option<String>,
}

impl JournalFilter {
    fn new(
        pattern: Option<String>,
        begin: Option<&str>,
        end: Option<&str>,
        cleared: bool,
        tag: Option<String>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let pattern = build_pattern_regex(pattern)?;

        let begin_date = begin
            .map(|s| {
                chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|_| {
                    format!("invalid --begin date '{}': expected format YYYY-MM-DD", s)
                })
            })
            .transpose()?;

        let end_date = end
            .map(|s| {
                chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
                    .map_err(|_| format!("invalid --end date '{}': expected format YYYY-MM-DD", s))
            })
            .transpose()?;

        Ok(JournalFilter {
            pattern,
            begin_date,
            end_date,
            cleared,
            tag,
        })
    }

    fn matches_transaction(&self, txn: &doppio::elaboration::ResolvedTransaction) -> bool {
        if self.cleared && !matches!(txn.state, doppio::elaboration::TransactionState::Cleared) {
            return false;
        }

        if let Some(ref t) = self.tag
            && !txn.tags.iter().any(|tag| tag == t)
            && !txn
                .postings
                .iter()
                .any(|p| p.tags.iter().any(|tag| tag == t))
        {
            return false;
        }

        if self.begin_date.is_some() || self.end_date.is_some() {
            let unix_epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
            let txn_date = unix_epoch.checked_add_signed(chrono::Duration::days(txn.date as i64));
            if let Some(txn_date) = txn_date {
                if let Some(begin) = self.begin_date
                    && txn_date < begin
                {
                    return false;
                }
                if let Some(end) = self.end_date
                    && txn_date > end
                {
                    return false;
                }
            }
        }

        true
    }

    fn matches_account(&self, account: &str) -> bool {
        self.pattern.is_match(account)
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Compile { output, source } => {
            let base_path = source.parent().unwrap().to_path_buf();
            let parser = doppio::parser::Parser {
                opener: doppio::file_opener,
                base_path,
            };
            let mut file = String::new();
            File::open(source)?.read_to_string(&mut file)?;
            let journal = doppio::compile(&file, parser)?;
            let mut out_file = File::create(output)?;
            // Write the 8-byte header: magic (4) + version LE (2) + reserved (2).
            doppio::dop_write_header(&mut out_file)?;
            let mut output_xz = xz::write::XzEncoder::new(out_file, 1);
            {
                let mut buf = std::io::BufWriter::new(&mut output_xz);
                postcard::to_io(&journal, &mut buf)?;
                buf.flush()?;
            }
            output_xz.finish()?;
        }
        Commands::Register {
            source,
            pattern,
            begin,
            end,
            cleared,
            tag,
            format,
        } => {
            let format = OutputFormat::parse(&format)?;
            let filter =
                JournalFilter::new(pattern, begin.as_deref(), end.as_deref(), cleared, tag)?;
            let journal = load_journal(&source)?;

            // Per-commodity running total across all matching postings.
            let mut running: BTreeMap<String, rust_decimal::Decimal> = BTreeMap::new();

            // Build an iterator over transactions filtered by cleared, date range, and tag.
            let filtered_txns: Vec<_> = journal
                .transactions
                .iter()
                .filter(|txn| filter.matches_transaction(txn))
                .collect();

            match format {
                OutputFormat::Text => {
                    for txn in &filtered_txns {
                        // txn.date is Unix epoch days (1970-01-01 = 0); convert back to a
                        // human-readable date string for display.
                        let date = epoch_days_to_string(txn.date);

                        for posting in txn.postings.iter() {
                            if !filter.matches_account(&posting.account) {
                                continue;
                            }

                            // Accumulate every commodity in this posting into the running total.
                            for (commodity, amount) in posting.amount.0.iter() {
                                *running.entry(commodity.clone()).or_default() += amount;
                            }

                            // Print one output line per commodity in the posting.
                            // The first line carries date, description, and account;
                            // subsequent commodity lines are blank in those columns.
                            let mut commodities_iter = posting.amount.0.iter();
                            if let Some((commodity, amount)) = commodities_iter.next() {
                                let amount_str =
                                    display_amount(commodity, *amount, &journal.commodities);
                                let running_str = display_amount(
                                    commodity,
                                    running.get(commodity).copied().unwrap_or_default(),
                                    &journal.commodities,
                                );
                                println!(
                                    "{:<10}  {:<20}  {:<30}  {:>15}  {:>15}",
                                    date,
                                    txn.description.chars().take(20).collect::<String>(),
                                    posting.account,
                                    amount_str,
                                    running_str,
                                );
                            }
                            for (commodity, amount) in commodities_iter {
                                let amount_str =
                                    display_amount(commodity, *amount, &journal.commodities);
                                let running_str = display_amount(
                                    commodity,
                                    running.get(commodity).copied().unwrap_or_default(),
                                    &journal.commodities,
                                );
                                println!(
                                    "{:<10}  {:<20}  {:<30}  {:>15}  {:>15}",
                                    "", "", "", amount_str, running_str,
                                );
                            }
                        }
                    }
                }
                OutputFormat::Json => {
                    let mut rows: Vec<serde_json::Value> = Vec::new();
                    for txn in &filtered_txns {
                        let date = epoch_days_to_string(txn.date);
                        for posting in txn.postings.iter() {
                            if !filter.matches_account(&posting.account) {
                                continue;
                            }
                            for (commodity, amount) in posting.amount.0.iter() {
                                *running.entry(commodity.clone()).or_default() += amount;
                                let running_total =
                                    running.get(commodity).copied().unwrap_or_default();
                                rows.push(serde_json::json!({
                                    "date": date,
                                    "description": txn.description,
                                    "account": posting.account,
                                    "commodity": commodity,
                                    "amount": amount.to_string(),
                                    "running_total": running_total.to_string(),
                                }));
                            }
                        }
                    }
                    println!("{}", serde_json::to_string_pretty(&rows)?);
                }
                OutputFormat::Csv => {
                    println!("date,description,account,commodity,amount,running_total");
                    for txn in &filtered_txns {
                        let date = epoch_days_to_string(txn.date);
                        for posting in txn.postings.iter() {
                            if !filter.matches_account(&posting.account) {
                                continue;
                            }
                            for (commodity, amount) in posting.amount.0.iter() {
                                *running.entry(commodity.clone()).or_default() += amount;
                                let running_total =
                                    running.get(commodity).copied().unwrap_or_default();
                                println!(
                                    "{},{},{},{},{},{}",
                                    csv_field(&date),
                                    csv_field(&txn.description),
                                    csv_field(&posting.account),
                                    csv_field(commodity),
                                    amount,
                                    running_total,
                                );
                            }
                        }
                    }
                }
            }
        }
        Commands::Print { source } => {
            if let Some("dop") = source.extension().and_then(|e| e.to_str()) {
                return Err("print only works with .ledger source files; \
                     .dop binary archives do not preserve the original transaction structure"
                    .into());
            }
            let base_path = source.parent().unwrap().to_path_buf();
            let mut parser = doppio::parser::Parser {
                opener: doppio::file_opener,
                base_path,
            };
            let mut file = String::new();
            File::open(&source)?.read_to_string(&mut file)?;
            let ast_journal: doppio::ast::Journal = parser.parse(&file)?;
            let hir: doppio::resolution::HIR = ast_journal.try_into()?;
            doppio::write_ledger(hir.transactions(), &mut std::io::stdout())?;
        }
        Commands::Accounts { source, pattern } => {
            let journal = load_journal(&source)?;
            let pattern = pattern.map(|p| p.to_lowercase()).unwrap_or_default();
            for account in journal.accounts.keys() {
                if account.to_lowercase().contains(&pattern) {
                    println!("{}", account);
                }
            }
        }
        Commands::Commodities { source } => {
            let journal = load_journal(&source)?;
            let commodities: BTreeSet<&String> = journal
                .transactions
                .iter()
                .flat_map(|txn| txn.postings.iter())
                .flat_map(|posting| posting.amount.0.keys())
                .collect();
            for commodity in commodities {
                println!("{}", commodity);
            }
        }
        Commands::Stats { source } => {
            let journal = load_journal(&source)?;

            let commodities: BTreeSet<&String> = journal
                .transactions
                .iter()
                .flat_map(|txn| txn.postings.iter())
                .flat_map(|posting| posting.amount.0.keys())
                .collect();

            // txn.date is Unix epoch days (1970-01-01 = 0).
            let unix_epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
            let first_date = journal.transactions.first().and_then(|txn| {
                unix_epoch.checked_add_signed(chrono::Duration::days(txn.date as i64))
            });
            let last_date = journal.transactions.last().and_then(|txn| {
                unix_epoch.checked_add_signed(chrono::Duration::days(txn.date as i64))
            });

            println!("Transactions: {}", journal.transactions.len());
            println!("Accounts:     {}", journal.accounts.len());
            println!("Commodities:  {}", commodities.len());
            match (first_date, last_date) {
                (Some(first), Some(last)) => {
                    println!("First date:   {}", first);
                    println!("Last date:    {}", last);
                }
                _ => {
                    println!("First date:   N/A");
                    println!("Last date:    N/A");
                }
            }
        }
        Commands::Balance {
            source,
            pattern,
            begin,
            end,
            cleared,
            tag,
            depth,
            flat,
            format,
        } => {
            let format = OutputFormat::parse(&format)?;
            let filter =
                JournalFilter::new(pattern, begin.as_deref(), end.as_deref(), cleared, tag)?;
            let journal = load_journal(&source)?;

            // Balances keyed by owned account name so depth-truncation can
            // produce new strings that aren't borrowed from the journal.
            let mut balances: BTreeMap<String, BTreeMap<String, rust_decimal::Decimal>> =
                BTreeMap::new();

            for txn in journal.transactions.iter() {
                if !filter.matches_transaction(txn) {
                    continue;
                }

                for posting in txn.postings.iter() {
                    if !filter.matches_account(&posting.account) {
                        continue;
                    }
                    let account = match depth {
                        Some(d) => truncate_account(&posting.account, d).to_owned(),
                        None => posting.account.clone(),
                    };
                    for (commodity, amount) in posting.amount.0.iter() {
                        *(balances
                            .entry(account.clone())
                            .or_default()
                            .entry(commodity.clone())
                            .or_default()) += *amount;
                    }
                }
            }

            match format {
                OutputFormat::Text => {
                    for (account, commodities) in balances.iter() {
                        let indent_depth = account.chars().filter(|&c| c == ':').count();
                        let label: &str = if flat || indent_depth == 0 {
                            account.as_str()
                        } else {
                            // Show only the last component in tree mode.
                            account
                                .rsplit_once(':')
                                .map(|(_, last)| last)
                                .unwrap_or(account.as_str())
                        };
                        let indent = if flat { 0 } else { indent_depth * 2 };
                        let prefix = " ".repeat(indent);

                        let mut commodities_iter = commodities.iter();
                        if let Some((commodity, value)) = commodities_iter.next() {
                            let balance = display_amount(commodity, *value, &journal.commodities);
                            println!("{balance:>20}  {prefix}{label}");
                        }
                        for (commodity, value) in commodities_iter {
                            let balance = display_amount(commodity, *value, &journal.commodities);
                            println!("{balance:>20}");
                        }
                    }
                }
                OutputFormat::Json => {
                    let rows: Vec<serde_json::Value> = balances
                        .iter()
                        .map(|(account, acct_balances)| {
                            let commodity_amounts: Vec<serde_json::Value> = acct_balances
                                .iter()
                                .map(|(commodity, amount)| {
                                    serde_json::json!({
                                        "commodity": commodity,
                                        "amount": amount.to_string(),
                                    })
                                })
                                .collect();
                            serde_json::json!({
                                "account": account,
                                "balances": commodity_amounts,
                            })
                        })
                        .collect();
                    println!("{}", serde_json::to_string_pretty(&rows)?);
                }
                OutputFormat::Csv => {
                    println!("account,commodity,amount");
                    for (account, acct_balances) in balances.iter() {
                        for (commodity, amount) in acct_balances.iter() {
                            println!("{},{},{}", csv_field(account), csv_field(commodity), amount,);
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Format an amount according to a commodity's declared format string.
///
/// The format encodes prefix/suffix position, thousand separator, decimal
/// separator, and decimal places. Falls back to `"COMMODITY VALUE"` if the
/// format string cannot be parsed.
///
/// Examples:
/// - `"$1,000.00"` → prefix `$`, thousands `,`, decimal `.`, 2 places
/// - `"1.000,00 EUR"` → suffix ` EUR`, thousands `.`, decimal `,`, 2 places
/// - `"100 USD"` → suffix ` USD`, no thousands, no decimal
fn format_amount(commodity: &str, value: rust_decimal::Decimal, format: &str) -> String {
    // Determine prefix vs suffix by scanning for digit/sign characters.
    // Everything before the first digit/sign is the prefix; after the last
    // digit is the suffix (including any space).
    let first_digit = format
        .char_indices()
        .find(|(_, c)| c.is_ascii_digit() || *c == '-')
        .map(|(i, _)| i);
    let last_digit = format
        .char_indices()
        .rfind(|(_, c)| c.is_ascii_digit())
        .map(|(i, _)| i);

    let (prefix, number_part, suffix) = match (first_digit, last_digit) {
        (Some(s), Some(e)) => (&format[..s], &format[s..=e], &format[e + 1..]),
        _ => return format!("{commodity} {value}"),
    };

    // Detect the decimal separator: the last `.` or `,` in the number portion,
    // if it is followed by exactly N non-separator digits.
    let (decimal_sep, thousand_sep, decimal_places) = detect_separators(number_part);

    apply_format(
        commodity,
        value,
        prefix,
        suffix,
        decimal_sep,
        thousand_sep,
        decimal_places,
    )
}

/// Returns `(decimal_sep, thousand_sep, decimal_places)` by inspecting the
/// example number in the format string.
fn detect_separators(number: &str) -> (Option<char>, Option<char>, usize) {
    // Find the last occurrence of '.' or ',' — that's the decimal separator.
    let last_dot = number.rfind('.');
    let last_comma = number.rfind(',');

    let (decimal_sep, decimal_places) = match (last_dot, last_comma) {
        (Some(di), Some(ci)) if di > ci => {
            // dot comes last → decimal separator is '.', thousands is ','
            let places = number.len() - di - 1;
            (Some('.'), places)
        }
        (Some(di), Some(ci)) if ci > di => {
            // comma comes last → decimal separator is ',', thousands is '.'
            let places = number.len() - ci - 1;
            (Some(','), places)
        }
        (Some(di), None) => {
            // Single '.' with nothing else. Per ledger convention, a lone
            // separator followed by exactly 3 digits (e.g. `1.000`) is a
            // thousands separator, not a decimal point.
            let trailing = number.len() - di - 1;
            if trailing == 3 {
                (None, 0) // treat as thousands sep; decimal_sep stays None
            } else {
                (Some('.'), trailing)
            }
        }
        (None, Some(ci)) => {
            // Same logic for a lone ',': `1,000` → thousands sep.
            let trailing = number.len() - ci - 1;
            if trailing == 3 {
                (None, 0)
            } else {
                (Some(','), trailing)
            }
        }
        _ => (None, 0),
    };

    let thousand_sep = match decimal_sep {
        Some('.') if number.contains(',') => Some(','),
        Some(',') if number.contains('.') => Some('.'),
        None if number.contains(',') => Some(','),
        None if number.contains('.') => Some('.'),
        _ => None,
    };

    (decimal_sep, thousand_sep, decimal_places)
}

/// Render `value` using the parsed format components.
fn apply_format(
    commodity: &str,
    value: rust_decimal::Decimal,
    prefix: &str,
    suffix: &str,
    decimal_sep: Option<char>,
    thousand_sep: Option<char>,
    decimal_places: usize,
) -> String {
    use rust_decimal::prelude::ToPrimitive as _;

    // Re-scale the decimal to the correct number of places.
    let scaled = value.round_dp(decimal_places as u32);
    let is_neg = scaled.is_sign_negative();
    let abs = scaled.abs();

    // Split into integer and fractional parts.
    let integer_part = abs.trunc().to_u64().unwrap_or(0);
    let frac_str = if decimal_places > 0 {
        // Produce the fractional digits by taking the remainder and padding.
        let frac = abs.fract();
        let multiplier = rust_decimal::Decimal::from(10u64.pow(decimal_places as u32));
        let frac_digits = (frac * multiplier).to_u64().unwrap_or(0);
        format!("{frac_digits:0>width$}", width = decimal_places)
    } else {
        String::new()
    };

    // Format integer part with optional thousand separator.
    let int_str = if let Some(sep) = thousand_sep {
        let s = integer_part.to_string();
        let mut out = String::new();
        for (i, ch) in s.chars().rev().enumerate() {
            if i > 0 && i % 3 == 0 {
                out.push(sep);
            }
            out.push(ch);
        }
        out.chars().rev().collect::<String>()
    } else {
        integer_part.to_string()
    };

    // Assemble number string.
    let number = if decimal_places > 0 {
        format!("{int_str}{}{frac_str}", decimal_sep.unwrap_or('.'))
    } else {
        int_str
    };

    let sign = if is_neg { "-" } else { "" };

    // The prefix/suffix may already contain the commodity symbol. Use the
    // format's prefix/suffix as-is if non-empty, otherwise fall back.
    //
    // Sign placement: for prefix formats (e.g. `$`) the sign goes before the
    // prefix so the result is `-$100`, not `$-100`.
    if !prefix.is_empty() || !suffix.is_empty() {
        format!("{sign}{prefix}{number}{suffix}")
    } else {
        // No prefix/suffix in format (shouldn't happen, but safe fallback).
        format!("{sign}{number} {commodity}")
    }
}

/// Format an amount using the commodity's declared format if available,
/// otherwise fall back to `"COMMODITY VALUE"`.
fn display_amount(
    commodity: &str,
    value: rust_decimal::Decimal,
    commodities: &std::collections::BTreeMap<String, doppio::elaboration::CommodityProperties>,
) -> String {
    if let Some(fmt) = commodities.get(commodity).and_then(|p| p.format.as_deref()) {
        format_amount(commodity, value, fmt)
    } else {
        format!("{commodity} {value}")
    }
}

/// Convert Unix epoch days to a `YYYY-MM-DD` string.
fn epoch_days_to_string(days: i32) -> String {
    chrono::NaiveDate::from_ymd_opt(1970, 1, 1)
        .and_then(|epoch| epoch.checked_add_signed(chrono::Duration::days(days as i64)))
        .map(|d| d.to_string())
        .unwrap_or_else(|| "????-??-??".to_string())
}

/// Escape a field for CSV output.
///
/// If the value contains a comma, double-quote, or newline it is wrapped in
/// double-quotes with internal double-quotes doubled per RFC 4180.
fn csv_field(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}