rustledger 0.16.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
//! Add transactions to beancount files.
//!
//! Provides interactive and quick modes for adding transactions:
//!
//! - **Interactive mode**: Prompts for date, payee, accounts, amounts with tab completion
//! - **Quick mode**: One-liner for scripting and automation
//!
//! # Usage
//!
//! ```bash
//! # Interactive mode (default)
//! rledger add ledger.beancount
//!
//! # Quick mode
//! rledger add -q "Coffee Shop" "Morning coffee" Expenses:Food 4.50USD Assets:Checking
//!
//! # Dry run (preview without appending)
//! rledger add -n -q "Store" "Groceries" Expenses:Food 25USD Assets:Cash
//!
//! # Skip confirmation prompt
//! rledger add -y -q "Coffee" "" Expenses:Food 5USD Assets:Checking
//! ```
//!
//! # Options
//!
//! - `-d, --date <DATE>`: Transaction date (YYYY-MM-DD, "today", "yesterday", "+1", "-1")
//! - `-n, --dry-run`: Preview transaction without appending to file
//! - `-y, --yes`: Skip confirmation prompt
//! - `-q, --quick <ARGS>`: Quick mode with inline arguments
//! - `--no-completion`: Disable account tab completion in interactive mode

pub(crate) mod parsing;

use anyhow::{Context, Result, bail};
use clap::Parser;
use parsing::{calculate_balance, parse_amount, parse_date};
use rustledger_core::NaiveDate;
use rustledger_core::format::FormatConfig;
use rustledger_core::{Amount, Directive, Posting, Transaction};
use rustledger_parser::format::canonicalize_directives;
use rustledger_parser::parse;
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::{CmdKind, Highlighter};
use rustyline::hint::Hinter;
use rustyline::history::DefaultHistory;
use rustyline::validate::Validator;
use rustyline::{Editor, Helper};
use std::borrow::Cow;
use std::fs::{self, File, OpenOptions};
use std::io::{Read as IoRead, Seek, SeekFrom, Write};
use std::path::PathBuf;
#[cfg(test)]
use {rust_decimal::Decimal, std::str::FromStr};

/// Add transactions to beancount files.
#[derive(Parser, Debug)]
#[command(name = "add")]
pub struct Args {
    /// File to append transaction to.
    #[arg(value_name = "FILE")]
    pub file: Option<PathBuf>,

    /// Transaction date (YYYY-MM-DD, "today", "yesterday", "+1", "-1").
    #[arg(short, long)]
    pub date: Option<String>,

    /// Print transaction without appending.
    #[arg(short = 'n', long)]
    pub dry_run: bool,

    /// Skip confirmation prompt.
    #[arg(short, long)]
    pub yes: bool,

    /// Quick mode: payee narration account amount \[account \[amount\]\]...
    #[arg(short, long, num_args = 4.., value_name = "ARGS")]
    pub quick: Option<Vec<String>>,

    /// Disable account tab completion.
    #[arg(long)]
    pub no_completion: bool,
}

/// Account completer for interactive mode.
///
/// Provides tab completion for account names extracted from the ledger file.
struct AccountCompleter {
    accounts: Vec<String>,
}

impl AccountCompleter {
    /// Create a new completer with the given list of accounts.
    const fn new(accounts: Vec<String>) -> Self {
        Self { accounts }
    }

    /// Create an empty completer (no completion).
    const fn empty() -> Self {
        Self {
            accounts: Vec::new(),
        }
    }
}

impl Completer for AccountCompleter {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        let prefix = &line[..pos];

        // Find matches - both prefix and substring matches
        let mut matches: Vec<Pair> = self
            .accounts
            .iter()
            .filter(|a| a.starts_with(prefix) || a.to_lowercase().contains(&prefix.to_lowercase()))
            .map(|a| Pair {
                display: a.clone(),
                replacement: a.clone(),
            })
            .collect();

        // Sort: prefix matches first, then alphabetically
        matches.sort_by(|a, b| {
            let a_prefix = a.replacement.starts_with(prefix);
            let b_prefix = b.replacement.starts_with(prefix);
            match (a_prefix, b_prefix) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => a.replacement.cmp(&b.replacement),
            }
        });

        Ok((0, matches))
    }
}

/// Helper for rustyline editor with account completion.
struct AddHelper {
    completer: AccountCompleter,
}

impl AddHelper {
    const fn new(completer: AccountCompleter) -> Self {
        Self { completer }
    }
}

impl Helper for AddHelper {}

impl Completer for AddHelper {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        self.completer.complete(line, pos, ctx)
    }
}

impl Hinter for AddHelper {
    type Hint = String;

    fn hint(&self, _line: &str, _pos: usize, _ctx: &rustyline::Context<'_>) -> Option<String> {
        None
    }
}

impl Highlighter for AddHelper {
    fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
        Cow::Borrowed(line)
    }

    fn highlight_char(&self, _line: &str, _pos: usize, _kind: CmdKind) -> bool {
        false
    }
}

impl Validator for AddHelper {}

/// Thin wrapper around the parser's canonical-emit helper. Lives
/// here only to keep call-site ergonomics tight; all the
/// synth-then-canonicalize machinery is in
/// [`rustledger_parser::format::canonicalize_directives`].
fn canonical_format_directive(directive: &Directive, config: &FormatConfig) -> Result<String> {
    canonicalize_directives(std::iter::once(directive), config)
        .map_err(|e| anyhow::anyhow!(e.to_string()))
}

/// Run the add command in quick mode (writes to stdout).
fn run_quick_mode(args: &Args, file: &PathBuf, date: NaiveDate) -> Result<()> {
    let mut stdout = std::io::stdout().lock();
    run_quick_mode_with_writer(args, file, date, &mut stdout)
}

/// Quick-mode entry point for the agent-native `ag-rledger` binary.
///
/// Parses the date the same way [`run`] does, then runs quick mode with
/// output written to `out`. This path never prompts on stdin: it requires
/// `--yes` (append) or `--dry-run` (preview) and returns an error if neither
/// is set, rather than blocking on a TTY or silently defaulting to "yes" on
/// EOF. The `ag-rledger` add handler enforces the same precondition before
/// calling this, so the error here is a defensive backstop. Behavior
/// otherwise matches `run` + quick mode.
///
/// # Errors
/// Returns an error when neither `--yes` nor `--dry-run` is set, and
/// propagates date-parse, formatting, and file-append errors.
pub fn run_quick_with_writer<W: std::io::Write>(
    args: &Args,
    file: &PathBuf,
    out: &mut W,
) -> Result<()> {
    if !args.yes && !args.dry_run {
        bail!(
            "ag-rledger add requires --yes (to append) or --dry-run (to preview); \
             the agent path never prompts interactively"
        );
    }
    let date = if let Some(ref d) = args.date {
        parse_date(d)?
    } else {
        jiff::Zoned::now().date()
    };
    run_quick_mode_with_writer(args, file, date, out)
}

/// Run the add command in quick mode, writing preview/result lines to
/// `out`.
fn run_quick_mode_with_writer<W: std::io::Write>(
    args: &Args,
    file: &PathBuf,
    date: NaiveDate,
    out: &mut W,
) -> Result<()> {
    let quick_args = args.quick.as_ref().expect("quick mode args");

    if quick_args.len() < 4 {
        bail!("Quick mode requires at least: payee narration account amount");
    }

    let payee = &quick_args[0];
    let narration = &quick_args[1];

    // Parse account/amount pairs
    let mut postings: Vec<Posting> = Vec::new();
    let mut amounts: Vec<Amount> = Vec::new();
    let mut i = 2;

    while i < quick_args.len() {
        let account = &quick_args[i];
        i += 1;

        if i < quick_args.len() {
            // Try to parse as amount
            if let Ok(amount) = parse_amount(&quick_args[i]) {
                postings.push(Posting::new(account.as_str(), amount.clone()));
                amounts.push(amount);
                i += 1;
            } else {
                // No amount for this account - will be auto-balanced
                postings.push(Posting::auto(account.as_str()));
            }
        } else {
            // Last account with no amount - auto-balance
            postings.push(Posting::auto(account.as_str()));
        }
    }

    // Validate postings
    if postings.len() < 2 {
        bail!(
            "Quick mode requires at least two postings (accounts), but only {} provided.",
            postings.len()
        );
    }

    // Check that at most one posting lacks units, and it must be the last one
    let missing_units: Vec<usize> = postings
        .iter()
        .enumerate()
        .filter(|(_, p)| !p.has_units())
        .map(|(idx, _)| idx)
        .collect();

    if missing_units.len() > 1 {
        bail!(
            "Quick mode supports at most one posting without an explicit amount, \
             but {} postings lack amounts.",
            missing_units.len()
        );
    }

    if let Some(&idx) = missing_units.first()
        && idx != postings.len() - 1
    {
        bail!(
            "A posting without an amount must be the last posting, \
             but posting {} (of {}) lacks an amount.",
            idx + 1,
            postings.len()
        );
    }

    // If the last posting has no amount, calculate and set it
    if let Some(last) = postings.last_mut()
        && !last.has_units()
    {
        if amounts.is_empty() {
            bail!("Cannot auto-balance: no explicit amounts were provided for any posting.");
        }
        let balance = calculate_balance(&amounts)?;
        *last = Posting::new(last.account.as_str(), balance);
    }

    // Build the transaction
    let mut txn = Transaction::new(date, narration.as_str()).with_flag('*');

    if !payee.is_empty() {
        txn = txn.with_payee(payee.as_str());
    }

    for posting in postings {
        txn = txn.with_synthesized_posting(posting);
    }

    // Format and display. Two-pass: synthesize via the typed-
    // directive emitter, then run it through the canonical CST
    // formatter so the appended bytes match what `rledger format`
    // would write on the same content (single canonical form
    // across the toolchain).
    let config = FormatConfig::default();
    let directive = Directive::Transaction(txn);
    let formatted = canonical_format_directive(&directive, &config)?;

    if args.dry_run {
        writeln!(out, "{formatted}")?;
        return Ok(());
    }

    // Show preview and confirm
    if !args.yes {
        writeln!(out, "Preview:")?;
        writeln!(out, "{formatted}")?;
        write!(out, "Append to {}? [Y/n] ", file.display())?;
        out.flush()?;

        let mut response = String::new();
        std::io::stdin().read_line(&mut response)?;
        let response = response.trim().to_lowercase();

        if !response.is_empty() && response != "y" && response != "yes" {
            writeln!(out, "Cancelled.")?;
            return Ok(());
        }
    }

    // Append to file
    append_transaction(file, &formatted)?;

    writeln!(out, "Transaction appended to {}", file.display())?;
    Ok(())
}

/// Extract all account names from a beancount file.
///
/// Parses the file and extracts accounts from Open, Close, Balance,
/// Pad, and Transaction directives.
fn extract_accounts(file: &PathBuf) -> Vec<String> {
    if !file.exists() {
        return Vec::new();
    }

    let content = match fs::read_to_string(file) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };

    let parse_result = parse(&content);
    let mut accounts = Vec::new();

    for spanned in &parse_result.directives {
        match &spanned.value {
            Directive::Open(open) => {
                accounts.push(open.account.to_string());
            }
            Directive::Close(close) => {
                accounts.push(close.account.to_string());
            }
            Directive::Balance(bal) => {
                accounts.push(bal.account.to_string());
            }
            Directive::Pad(pad) => {
                accounts.push(pad.account.to_string());
                accounts.push(pad.source_account.to_string());
            }
            Directive::Transaction(txn) => {
                for posting in &txn.postings {
                    accounts.push(posting.account.to_string());
                }
            }
            _ => {}
        }
    }

    accounts.sort();
    accounts.dedup();
    accounts
}

/// Prompt for input with a default value.
///
/// Returns the trimmed input, or the default if input is empty.
fn prompt_with_default(
    rl: &mut Editor<AddHelper, DefaultHistory>,
    prompt: &str,
    default: &str,
) -> Result<String> {
    let full_prompt = if default.is_empty() {
        format!("{prompt}: ")
    } else {
        format!("{prompt} [{default}]: ")
    };

    match rl.readline(&full_prompt) {
        Ok(line) => {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                Ok(default.to_string())
            } else {
                Ok(trimmed.to_string())
            }
        }
        Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
            bail!("Cancelled.");
        }
        Err(e) => Err(e.into()),
    }
}

/// Run the add command in interactive mode.
fn run_interactive_mode(args: &Args, file: &PathBuf, date: NaiveDate) -> Result<()> {
    // Set up completer with accounts from the ledger file
    let completer = if args.no_completion {
        AccountCompleter::empty()
    } else {
        let accounts = extract_accounts(file);
        AccountCompleter::new(accounts)
    };

    let helper = AddHelper::new(completer);
    let mut rl: Editor<AddHelper, DefaultHistory> = Editor::new()?;
    rl.set_helper(Some(helper));

    // Prompt for date
    let date_default = date.to_string();
    let date_input = prompt_with_default(&mut rl, "Date", &date_default)?;
    let transaction_date = parse_date(&date_input)?;

    // Prompt for payee
    let payee = prompt_with_default(&mut rl, "Payee", "")?;

    // Prompt for narration
    let narration = prompt_with_default(&mut rl, "Narration", "")?;

    // Collect postings
    let mut postings: Vec<Posting> = Vec::new();
    let mut amounts: Vec<Amount> = Vec::new();
    let mut posting_num = 1;

    loop {
        // Prompt for account
        let account_prompt = format!("Account {posting_num}");
        let account = match rl.readline(&format!("{account_prompt}: ")) {
            Ok(line) => {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    if posting_num == 1 {
                        bail!("At least one account is required.");
                    }
                    break;
                }
                trimmed.to_string()
            }
            Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
                if posting_num == 1 {
                    bail!("Cancelled.");
                }
                break;
            }
            Err(e) => return Err(e.into()),
        };

        // Calculate auto-balance suggestion for display
        let balance_hint = if amounts.is_empty() {
            String::new()
        } else {
            match calculate_balance(&amounts) {
                Ok(bal) => format!("auto: {} {}", bal.number, bal.currency),
                Err(_) => String::new(),
            }
        };

        // Prompt for amount
        let amount_prompt = format!("Amount {posting_num}");
        let amount_default = if posting_num > 1 && !balance_hint.is_empty() {
            balance_hint
        } else {
            String::new()
        };

        let amount_input = prompt_with_default(&mut rl, &amount_prompt, &amount_default)?;

        if amount_input.is_empty() || amount_input == "none" {
            // No amount - will be auto-balanced by beancount
            postings.push(Posting::auto(&account));
        } else if amount_input.starts_with("auto:") {
            // User accepted auto-balance
            let balance = calculate_balance(&amounts)?;
            postings.push(Posting::new(&account, balance));
        } else {
            // Parse the amount
            let amount = parse_amount(&amount_input)?;
            postings.push(Posting::new(&account, amount.clone()));
            amounts.push(amount);
        }

        posting_num += 1;

        // Ask if user wants to add another posting
        if posting_num > 2 {
            let more = prompt_with_default(&mut rl, "Add another posting?", "n")?;
            if more.to_lowercase() != "y" && more.to_lowercase() != "yes" {
                break;
            }
        }
    }

    // Validate we have at least 2 postings for a balanced transaction
    if postings.len() < 2 {
        bail!(
            "At least two postings are required for a balanced transaction, but only {} provided.",
            postings.len()
        );
    }

    // If we have amounts and the last posting has no units, auto-balance it
    if let Some(last) = postings.last_mut()
        && !last.has_units()
        && !amounts.is_empty()
    {
        let balance = calculate_balance(&amounts)?;
        *last = Posting::new(last.account.as_str(), balance);
    }

    // Build the transaction
    let mut txn = Transaction::new(transaction_date, &narration).with_flag('*');

    if !payee.is_empty() {
        txn = txn.with_payee(&payee);
    }

    for posting in postings {
        txn = txn.with_synthesized_posting(posting);
    }

    // Format and display preview (see comment in add_cmd's
    // synthesize/format pass for why this is two-pass).
    let config = FormatConfig::default();
    let directive = Directive::Transaction(txn);
    let formatted = canonical_format_directive(&directive, &config)?;

    if args.dry_run {
        println!("\n{formatted}");
        return Ok(());
    }

    // Show preview and confirm
    println!("\nPreview:");
    println!("{formatted}");

    if !args.yes {
        print!("Append to {}? [Y/n] ", file.display());
        std::io::stdout().flush()?;

        let mut response = String::new();
        std::io::stdin().read_line(&mut response)?;
        let response = response.trim().to_lowercase();

        if !response.is_empty() && response != "y" && response != "yes" {
            println!("Cancelled.");
            return Ok(());
        }
    }

    // Append to file
    append_transaction(file, &formatted)?;

    println!("Transaction appended to {}", file.display());
    Ok(())
}

/// Read the last N bytes of a file, or fewer if the file is smaller.
fn read_file_tail(file: &PathBuf, n: u64) -> Result<Vec<u8>> {
    let mut f = File::open(file).with_context(|| format!("Failed to open {}", file.display()))?;
    let len = f.metadata()?.len();

    if len == 0 {
        return Ok(Vec::new());
    }

    let read_len = len.min(n);
    let seek_pos = len.saturating_sub(n);

    f.seek(SeekFrom::Start(seek_pos))?;
    let mut buf = vec![0u8; read_len as usize];
    f.read_exact(&mut buf)?;

    Ok(buf)
}

/// Append a formatted transaction to a file.
fn append_transaction(file: &PathBuf, formatted: &str) -> Result<()> {
    // Check if file exists
    if !file.exists() {
        // Create the file with just the transaction
        fs::write(file, formatted)
            .with_context(|| format!("Failed to create {}", file.display()))?;
        return Ok(());
    }

    // Read only the last 2 bytes to check for trailing newlines
    let tail = read_file_tail(file, 2)?;

    let mut f = OpenOptions::new()
        .append(true)
        .open(file)
        .with_context(|| format!("Failed to open {} for appending", file.display()))?;

    // Add blank line separator based on file ending
    // Skip separator for empty files
    if !tail.is_empty() {
        let ends_with_newline = tail.last() == Some(&b'\n');
        let ends_with_double_newline =
            tail.len() >= 2 && tail[tail.len() - 2] == b'\n' && tail[tail.len() - 1] == b'\n';

        if !ends_with_double_newline {
            writeln!(f)?;
            if !ends_with_newline {
                writeln!(f)?;
            }
        }
    }

    write!(f, "{formatted}")?;

    Ok(())
}

/// Run the add command.
pub fn run(args: &Args, file: &PathBuf) -> Result<()> {
    // Parse the date
    let date = if let Some(ref d) = args.date {
        parse_date(d)?
    } else {
        jiff::Zoned::now().date()
    };

    // Check if file exists, offer to create if not
    if !file.exists() && !args.dry_run {
        if !args.yes {
            print!("File {} does not exist. Create it? [y/N] ", file.display());
            std::io::stdout().flush()?;

            let mut response = String::new();
            std::io::stdin().read_line(&mut response)?;
            let response = response.trim().to_lowercase();

            if response != "y" && response != "yes" {
                bail!("File does not exist: {}", file.display());
            }
        }
        // Create parent directories if needed
        if let Some(parent) = file.parent()
            && !parent.exists()
        {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }
    }

    // Dispatch to appropriate mode
    if args.quick.is_some() {
        run_quick_mode(args, file, date)
    } else {
        run_interactive_mode(args, file, date)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_date_today() {
        let today = jiff::Zoned::now().date();
        assert_eq!(parse_date("today").unwrap(), today);
        assert_eq!(parse_date("").unwrap(), today);
        assert_eq!(parse_date("TODAY").unwrap(), today);
    }

    #[test]
    fn test_parse_date_yesterday() {
        let yesterday = jiff::Zoned::now().date().yesterday().ok().unwrap();
        assert_eq!(parse_date("yesterday").unwrap(), yesterday);
        assert_eq!(parse_date("YESTERDAY").unwrap(), yesterday);
    }

    #[test]
    fn test_parse_date_relative() {
        let today = jiff::Zoned::now().date();
        let tomorrow = today.tomorrow().ok().unwrap();
        let yesterday = today.yesterday().ok().unwrap();

        assert_eq!(parse_date("+1").unwrap(), tomorrow);
        assert_eq!(parse_date("-1").unwrap(), yesterday);
        assert_eq!(
            parse_date("+7").unwrap(),
            today.checked_add(jiff::ToSpan::days(7)).ok().unwrap()
        );
    }

    #[test]
    fn test_parse_date_explicit() {
        assert_eq!(
            parse_date("2026-03-21").unwrap(),
            rustledger_core::naive_date(2026, 3, 21).unwrap()
        );
        assert_eq!(
            parse_date("2024-01-01").unwrap(),
            rustledger_core::naive_date(2024, 1, 1).unwrap()
        );
    }

    #[test]
    fn test_parse_date_invalid() {
        assert!(parse_date("not-a-date").is_err());
        assert!(parse_date("2026/03/21").is_err());
        assert!(parse_date("03-21-2026").is_err());
    }

    #[test]
    fn test_parse_amount_with_space() {
        let amt = parse_amount("123.45 USD").unwrap();
        assert_eq!(amt.number, Decimal::from_str("123.45").unwrap());
        assert_eq!(amt.currency.as_str(), "USD");
    }

    #[test]
    fn test_parse_amount_no_space() {
        let amt = parse_amount("123.45USD").unwrap();
        assert_eq!(amt.number, Decimal::from_str("123.45").unwrap());
        assert_eq!(amt.currency.as_str(), "USD");
    }

    #[test]
    fn test_parse_amount_negative() {
        let amt = parse_amount("-50.00 EUR").unwrap();
        assert_eq!(amt.number, Decimal::from_str("-50.00").unwrap());
        assert_eq!(amt.currency.as_str(), "EUR");
    }

    #[test]
    fn test_parse_amount_integer() {
        let amt = parse_amount("100 BTC").unwrap();
        assert_eq!(amt.number, Decimal::from_str("100").unwrap());
        assert_eq!(amt.currency.as_str(), "BTC");
    }

    #[test]
    fn test_parse_amount_invalid() {
        assert!(parse_amount("123.45").is_err()); // No currency
        assert!(parse_amount("USD").is_err()); // No number
        assert!(parse_amount("abc USD").is_err()); // Invalid number
    }

    #[test]
    fn test_calculate_balance_simple() {
        let amounts = vec![Amount::new(Decimal::from_str("100.00").unwrap(), "USD")];
        let balance = calculate_balance(&amounts).unwrap();
        assert_eq!(balance.number, Decimal::from_str("-100.00").unwrap());
        assert_eq!(balance.currency.as_str(), "USD");
    }

    #[test]
    fn test_calculate_balance_multiple() {
        let amounts = vec![
            Amount::new(Decimal::from_str("50.00").unwrap(), "USD"),
            Amount::new(Decimal::from_str("25.00").unwrap(), "USD"),
        ];
        let balance = calculate_balance(&amounts).unwrap();
        assert_eq!(balance.number, Decimal::from_str("-75.00").unwrap());
    }

    #[test]
    fn test_calculate_balance_mixed_currencies() {
        let amounts = vec![
            Amount::new(Decimal::from_str("100.00").unwrap(), "USD"),
            Amount::new(Decimal::from_str("50.00").unwrap(), "EUR"),
        ];
        assert!(calculate_balance(&amounts).is_err());
    }

    #[test]
    fn test_calculate_balance_empty() {
        let amounts: Vec<Amount> = vec![];
        assert!(calculate_balance(&amounts).is_err());
    }

    #[test]
    fn test_account_completer_prefix_match() {
        let completer = AccountCompleter::new(vec![
            "Assets:Bank:Checking".to_string(),
            "Assets:Bank:Savings".to_string(),
            "Assets:Cash".to_string(),
            "Expenses:Food".to_string(),
            "Expenses:Transport".to_string(),
        ]);

        // Test prefix matching
        let history = rustyline::history::DefaultHistory::new();
        let ctx = rustyline::Context::new(&history);
        let (start, matches) = completer.complete("Assets", 6, &ctx).unwrap();
        assert_eq!(start, 0);
        assert_eq!(matches.len(), 3);
        assert!(matches.iter().any(|p| p.display == "Assets:Bank:Checking"));
        assert!(matches.iter().any(|p| p.display == "Assets:Bank:Savings"));
        assert!(matches.iter().any(|p| p.display == "Assets:Cash"));
    }

    #[test]
    fn test_account_completer_substring_match() {
        let completer = AccountCompleter::new(vec![
            "Assets:Bank:Checking".to_string(),
            "Expenses:Food".to_string(),
            "Liabilities:CreditCard".to_string(),
        ]);

        // Test substring matching (case insensitive)
        let history = rustyline::history::DefaultHistory::new();
        let ctx = rustyline::Context::new(&history);
        let (start, matches) = completer.complete("bank", 4, &ctx).unwrap();
        assert_eq!(start, 0);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].display, "Assets:Bank:Checking");
    }

    #[test]
    fn test_account_completer_empty() {
        let completer = AccountCompleter::empty();

        let history = rustyline::history::DefaultHistory::new();
        let ctx = rustyline::Context::new(&history);
        let (start, matches) = completer.complete("Assets", 6, &ctx).unwrap();
        assert_eq!(start, 0);
        assert!(matches.is_empty());
    }

    #[test]
    fn test_extract_accounts_from_string() {
        // Create a temporary file with beancount content
        let content = r#"
2024-01-01 open Assets:Checking
2024-01-01 open Expenses:Food
2024-01-02 * "Store" "Groceries"
  Expenses:Food  50.00 USD
  Assets:Checking
"#;
        let temp_file = unique_temp_file("extract_accounts");
        std::fs::write(&temp_file, content).unwrap();

        let accounts = extract_accounts(&temp_file);
        assert!(accounts.contains(&"Assets:Checking".to_string()));
        assert!(accounts.contains(&"Expenses:Food".to_string()));

        // Clean up
        std::fs::remove_file(&temp_file).ok();
    }

    #[test]
    fn test_extract_accounts_nonexistent_file() {
        let nonexistent = PathBuf::from("/nonexistent/file.beancount");
        let accounts = extract_accounts(&nonexistent);
        assert!(accounts.is_empty());
    }

    #[test]
    fn test_parse_amount_stock_ticker() {
        // Test stock tickers with dots like BRK.B
        let amt = parse_amount("10 BRK.B").unwrap();
        assert_eq!(amt.number, Decimal::from_str("10").unwrap());
        assert_eq!(amt.currency.as_str(), "BRK.B");
    }

    #[test]
    fn test_parse_amount_futures_contract() {
        // Test futures contracts with / prefix
        let amt = parse_amount("5 /ESM24").unwrap();
        assert_eq!(amt.number, Decimal::from_str("5").unwrap());
        assert_eq!(amt.currency.as_str(), "/ESM24");
    }

    #[test]
    fn test_parse_amount_no_space_complex() {
        // Test no-space format with complex currency
        let amt = parse_amount("100.5BRK.B").unwrap();
        assert_eq!(amt.number, Decimal::from_str("100.5").unwrap());
        assert_eq!(amt.currency.as_str(), "BRK.B");
    }

    /// Generate a unique temp file path to avoid race conditions in parallel tests.
    fn unique_temp_file(name: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);

        let temp_dir = std::env::temp_dir();
        temp_dir.join(format!(
            "rustledger_test_{}_{}_{}.beancount",
            name,
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        ))
    }

    #[test]
    fn test_append_transaction_new_file() {
        let temp_file = unique_temp_file("append_new");

        // Clean up any existing file
        std::fs::remove_file(&temp_file).ok();

        let txn = "2024-01-01 * \"Test\"\n  Assets:Cash  100 USD\n  Expenses:Test\n";
        append_transaction(&temp_file, txn).unwrap();

        let content = std::fs::read_to_string(&temp_file).unwrap();
        assert_eq!(content, txn);

        std::fs::remove_file(&temp_file).ok();
    }

    #[test]
    fn test_append_transaction_empty_file() {
        let temp_file = unique_temp_file("append_empty");

        // Create empty file
        std::fs::write(&temp_file, "").unwrap();

        let txn = "2024-01-01 * \"Test\"\n  Assets:Cash  100 USD\n";
        append_transaction(&temp_file, txn).unwrap();

        let content = std::fs::read_to_string(&temp_file).unwrap();
        // Empty file should not get separator
        assert_eq!(content, txn);

        std::fs::remove_file(&temp_file).ok();
    }

    #[test]
    fn test_append_transaction_with_newline() {
        let temp_file = unique_temp_file("append_newline");

        // File ending with single newline
        std::fs::write(&temp_file, "2024-01-01 open Assets:Cash\n").unwrap();

        let txn = "2024-01-02 * \"Test\"\n  Assets:Cash  100 USD\n";
        append_transaction(&temp_file, txn).unwrap();

        let content = std::fs::read_to_string(&temp_file).unwrap();
        // Should add one more newline for blank line separator
        assert!(content.contains("\n\n2024-01-02"));

        std::fs::remove_file(&temp_file).ok();
    }

    #[test]
    fn test_append_transaction_with_double_newline() {
        let temp_file = unique_temp_file("append_double_newline");

        // File already ending with double newline
        std::fs::write(&temp_file, "2024-01-01 open Assets:Cash\n\n").unwrap();

        let txn = "2024-01-02 * \"Test\"\n";
        append_transaction(&temp_file, txn).unwrap();

        let content = std::fs::read_to_string(&temp_file).unwrap();
        // Should not add extra newlines
        assert!(!content.contains("\n\n\n"));

        std::fs::remove_file(&temp_file).ok();
    }
}