base-d 3.0.34

Universal base encoder: Encode binary data to 33+ dictionaries including RFC standards, hieroglyphs, emoji, and more
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
use base_d::{DictionaryRegistry, decode, encode};
use std::fs;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use std::time::Duration;

use crossterm::event::{Event, KeyCode, KeyEvent, poll, read};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};

use super::config::{
    BuiltDictionary, create_any_dictionary, create_dictionary, get_compression_level,
    load_xxhash_config,
};

pub enum SwitchInterval {
    Time(Duration),
    PerLine,
}

pub enum SwitchMode {
    Static,
    Cycle(SwitchInterval),
    Random(SwitchInterval),
}

/// Parse interval string like "5s", "500ms", or "line"
pub fn parse_interval(s: &str) -> Result<SwitchInterval, Box<dyn std::error::Error>> {
    if s == "line" {
        return Ok(SwitchInterval::PerLine);
    }

    // Parse duration strings
    let s = s.trim();

    // Try to find where digits end
    let split_pos = s
        .chars()
        .position(|c| !c.is_ascii_digit())
        .ok_or("Invalid duration format")?;

    let (num_str, unit) = s.split_at(split_pos);
    let value: u64 = num_str.parse()?;

    let duration = match unit {
        "ms" => Duration::from_millis(value),
        "s" => Duration::from_secs(value),
        "m" => Duration::from_secs(value * 60),
        _ => return Err(format!("Unknown duration unit: {}", unit).into()),
    };

    Ok(SwitchInterval::Time(duration))
}

/// Select a random dictionary from the registry.
/// Only selects from dictionaries with `common=true` (renders consistently across platforms).
/// Optionally prints a warning message to stderr based on the `print_message` flag.
/// Returns the dictionary name.
pub fn select_random_dictionary(
    config: &DictionaryRegistry,
    print_message: bool,
) -> Result<String, Box<dyn std::error::Error>> {
    use rand::prelude::IndexedRandom;
    let mut rng = rand::rng();

    // Filter to only common dictionaries (those that render consistently across platforms)
    let dict_names: Vec<&String> = config
        .dictionaries
        .iter()
        .filter(|(_, cfg)| cfg.common)
        .map(|(name, _)| name)
        .collect();

    let random_dict = dict_names
        .choose(&mut rng)
        .ok_or("No common dictionaries available")?;

    if print_message {
        eprintln!(
            "Note: Using randomly selected dictionary '{}' (use --encode={} to fix)",
            random_dict, random_dict
        );
    }

    Ok(random_dict.to_string())
}

/// Available hash algorithms for random selection
#[allow(dead_code)]
pub const HASH_ALGORITHMS: &[&str] = &[
    "md5", "sha256", "sha512", "blake3", "ascon", "k12", "xxh64", "xxh3",
];

/// Available compression algorithms for random selection
pub const COMPRESS_ALGORITHMS: &[&str] = &["gzip", "zstd", "brotli", "lz4"];

/// Select a random hash algorithm
#[allow(dead_code)]
pub fn select_random_hash(quiet: bool) -> &'static str {
    use rand::prelude::IndexedRandom;
    let selected = HASH_ALGORITHMS.choose(&mut rand::rng()).unwrap();
    if !quiet {
        eprintln!(
            "Note: Using randomly selected hash '{}' (use --hash={} to fix)",
            selected, selected
        );
    }
    selected
}

/// Select a random compression algorithm
pub fn select_random_compress(quiet: bool) -> &'static str {
    use rand::prelude::IndexedRandom;
    let selected = COMPRESS_ALGORITHMS.choose(&mut rand::rng()).unwrap();
    if !quiet {
        eprintln!(
            "Note: Using randomly selected compression '{}' (use --compress={} to fix)",
            selected, selected
        );
    }
    selected
}

/// Generate a line of random words from a word dictionary that fits within terminal width.
///
/// Picks random words and joins them with the dictionary's delimiter until
/// the line would exceed the terminal width.
fn generate_word_line<R: rand::Rng>(
    rng: &mut R,
    word_dict: &base_d::WordDictionary,
    term_width: usize,
) -> String {
    use rand::prelude::IndexedRandom;

    let words: Vec<&str> = word_dict.words().collect();
    if words.is_empty() {
        return String::new();
    }

    let delimiter = word_dict.delimiter();
    let mut line = String::new();
    let mut current_len = 0;

    loop {
        let word = words.choose(rng).unwrap();
        let word_len = word.chars().count();
        let delimiter_len = if line.is_empty() {
            0
        } else {
            delimiter.chars().count()
        };

        // Check if adding this word would exceed terminal width
        if current_len + delimiter_len + word_len > term_width {
            // If we have no words yet, add a truncated first word
            if line.is_empty() && term_width > 0 {
                return word.chars().take(term_width).collect();
            }
            break;
        }

        if !line.is_empty() {
            line.push_str(delimiter);
            current_len += delimiter_len;
        }
        line.push_str(word);
        current_len += word_len;
    }

    line
}

/// Generate a line of random words from an alternating word dictionary.
///
/// Alternates between sub-dictionaries (like PGP even/odd) for each word.
fn generate_alternating_word_line<R: rand::Rng>(
    rng: &mut R,
    alt_dict: &base_d::AlternatingWordDictionary,
    term_width: usize,
) -> String {
    use rand::prelude::IndexedRandom;

    let num_dicts = alt_dict.num_dicts();
    if num_dicts == 0 {
        return String::new();
    }

    let delimiter = alt_dict.delimiter();
    let mut line = String::new();
    let mut current_len = 0;
    let mut word_position = 0;

    loop {
        let current_dict = alt_dict.dict_at(word_position);
        let words: Vec<&str> = current_dict.words().collect();

        if words.is_empty() {
            break;
        }

        let word = words.choose(rng).unwrap();
        let word_len = word.chars().count();
        let delimiter_len = if line.is_empty() {
            0
        } else {
            delimiter.chars().count()
        };

        // Check if adding this word would exceed terminal width
        if current_len + delimiter_len + word_len > term_width {
            // If we have no words yet, add a truncated first word
            if line.is_empty() && term_width > 0 {
                return word.chars().take(term_width).collect();
            }
            break;
        }

        if !line.is_empty() {
            line.push_str(delimiter);
            current_len += delimiter_len;
        }
        line.push_str(word);
        current_len += word_len;

        word_position += 1;
    }

    line
}

/// Matrix mode: Stream random data as Matrix-style falling code
pub fn matrix_mode(
    config: &DictionaryRegistry,
    initial_dictionary: &str,
    switch_mode: SwitchMode,
    no_color: bool,
    quiet: bool,
    superman: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::thread;
    use std::time::Instant;

    // Enable raw mode for keyboard input
    enable_raw_mode()?;

    if !no_color {
        print!("\x1b[2J\x1b[H"); // Clear screen
        print!("\x1b[32m"); // Green text
    }

    // Iconic Matrix messages
    let messages = [
        "Wake up, Neo...",
        "The Matrix has you...",
        "Follow the white rabbit.",
        "Knock, knock, Neo.",
    ];

    'intro_loop: for message in &messages {
        for ch in message.chars() {
            print!("{}", ch);
            io::stdout().flush()?;

            // Check for ESC/Space/Enter to skip intro
            if poll(Duration::from_millis(100))? {
                if let Event::Key(KeyEvent { code, .. }) = read()?
                    && matches!(code, KeyCode::Esc | KeyCode::Char(' ') | KeyCode::Enter)
                {
                    if !no_color {
                        print!("\r\x1b[K");
                    } else {
                        print!("\r");
                    }
                    break 'intro_loop;
                }
            } else {
                thread::sleep(Duration::from_millis(100));
            }
        }
        thread::sleep(Duration::from_millis(800));
        if !no_color {
            print!("\r\x1b[K");
        } else {
            print!("\r");
        }
        io::stdout().flush()?;
        thread::sleep(Duration::from_millis(200));
    }

    thread::sleep(Duration::from_millis(500));

    // Setup for switching
    let mut current_dictionary_name = initial_dictionary.to_string();

    // For cycling: build sorted dictionary list
    let sorted_dicts: Vec<String> = if matches!(switch_mode, SwitchMode::Cycle(_)) {
        let mut names: Vec<String> = config.dictionaries.keys().cloned().collect();
        names.sort();
        names
    } else {
        Vec::new()
    };

    let mut cycle_index = sorted_dicts
        .iter()
        .position(|n| n == &current_dictionary_name)
        .unwrap_or(0);

    let mut last_switch = Instant::now();
    let mut rng = rand::rng();

    // Build sorted dictionary list for keyboard controls
    let dict_names: Vec<String> = {
        let mut names: Vec<_> = config.dictionaries.keys().cloned().collect();
        names.sort();
        names
    };
    let mut current_index = dict_names
        .iter()
        .position(|n| n == &current_dictionary_name)
        .unwrap_or(0);

    // Display current dictionary name
    if !quiet {
        if !no_color {
            eprint!("\x1b[32mDictionary: {}\x1b[0m\r\n", current_dictionary_name);
        } else {
            eprint!("Dictionary: {}\r\n", current_dictionary_name);
        }
    }

    loop {
        // Load current dictionary (supports both char and word dictionaries)
        let built_dictionary = create_any_dictionary(config, &current_dictionary_name)?;

        // Check if we need to switch (time-based)
        let should_switch = match &switch_mode {
            SwitchMode::Cycle(SwitchInterval::Time(d))
            | SwitchMode::Random(SwitchInterval::Time(d)) => last_switch.elapsed() >= *d,
            _ => false,
        };

        if should_switch {
            match &switch_mode {
                SwitchMode::Cycle(_) => {
                    cycle_index = (cycle_index + 1) % sorted_dicts.len();
                    current_dictionary_name = sorted_dicts[cycle_index].clone();
                }
                SwitchMode::Random(_) => {
                    current_dictionary_name = select_random_dictionary(config, false)?;
                }
                _ => {}
            }
            if !quiet {
                if !no_color {
                    eprint!("\x1b[32mDictionary: {}\x1b[0m\r\n", current_dictionary_name);
                } else {
                    eprint!("Dictionary: {}\r\n", current_dictionary_name);
                }
            }
            last_switch = Instant::now();
            continue; // Reload dictionary
        }

        // Check for line-based switching
        let switch_per_line = matches!(
            &switch_mode,
            SwitchMode::Cycle(SwitchInterval::PerLine)
                | SwitchMode::Random(SwitchInterval::PerLine)
        );

        if switch_per_line {
            match &switch_mode {
                SwitchMode::Cycle(SwitchInterval::PerLine) => {
                    cycle_index = (cycle_index + 1) % sorted_dicts.len();
                    current_dictionary_name = sorted_dicts[cycle_index].clone();
                }
                SwitchMode::Random(SwitchInterval::PerLine) => {
                    current_dictionary_name = select_random_dictionary(config, false)?;
                }
                _ => {}
            }
            if !quiet {
                if !no_color {
                    eprint!("\x1b[32mDictionary: {}\x1b[0m\r\n", current_dictionary_name);
                } else {
                    eprint!("Dictionary: {}\r\n", current_dictionary_name);
                }
            }
            continue; // Reload for next line
        }

        // Get current terminal width (re-check each line for resize detection)
        let term_width = match terminal_size::terminal_size() {
            Some((terminal_size::Width(w), _)) => w as usize,
            None => 80,
        };

        // Generate display line based on dictionary type
        let display = match &built_dictionary {
            BuiltDictionary::Char(dictionary) => {
                // Character-based: encode random bytes
                let base = dictionary.base();
                let bits_per_char = (base as f64).log2();
                let bytes_per_line = ((term_width as f64 * bits_per_char) / 8.0).ceil() as usize;
                let mut random_bytes = vec![0u8; bytes_per_line.max(1)];

                use rand::RngCore;
                rng.fill_bytes(&mut random_bytes);

                let encoded = encode(&random_bytes, dictionary);
                encoded.chars().take(term_width).collect::<String>()
            }
            BuiltDictionary::Word(word_dict) => {
                // Word-based: pick random words to fill the line
                generate_word_line(&mut rng, word_dict, term_width)
            }
            BuiltDictionary::Alternating(alt_dict) => {
                // Alternating word-based: pick random words from alternating dictionaries
                generate_alternating_word_line(&mut rng, alt_dict, term_width)
            }
        };

        print!("{}\r\n", display);
        io::stdout().flush()?;

        // Handle keyboard input (all modes)
        if poll(Duration::from_millis(25))?
            && let Event::Key(key_event) = read()?
        {
            match key_event.code {
                KeyCode::Char('c')
                    if key_event
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    // Ctrl+C to exit
                    disable_raw_mode()?;
                    if !no_color {
                        print!("\x1b[0m"); // Reset color
                    }
                    std::process::exit(0);
                }
                KeyCode::Esc => {
                    // ESC to exit
                    disable_raw_mode()?;
                    if !no_color {
                        print!("\x1b[0m"); // Reset color
                    }
                    std::process::exit(0);
                }
                KeyCode::Char(' ') => {
                    // Random switch
                    current_dictionary_name = select_random_dictionary(config, false)?;
                    current_index = dict_names
                        .iter()
                        .position(|n| n == &current_dictionary_name)
                        .unwrap_or(0);
                    if !quiet {
                        if !no_color {
                            eprint!("\r\x1b[32m[Matrix: {}]\x1b[0m\r\n", current_dictionary_name);
                        } else {
                            eprint!("\r[Matrix: {}]\r\n", current_dictionary_name);
                        }
                    }
                    continue; // Reload dictionary
                }
                KeyCode::Left => {
                    // Previous dictionary
                    current_index = if current_index == 0 {
                        dict_names.len() - 1
                    } else {
                        current_index - 1
                    };
                    current_dictionary_name = dict_names[current_index].clone();
                    if !quiet {
                        if !no_color {
                            eprint!("\r\x1b[32m[Matrix: {}]\x1b[0m\r\n", current_dictionary_name);
                        } else {
                            eprint!("\r[Matrix: {}]\r\n", current_dictionary_name);
                        }
                    }
                    continue; // Reload dictionary
                }
                KeyCode::Right => {
                    // Next dictionary
                    current_index = (current_index + 1) % dict_names.len();
                    current_dictionary_name = dict_names[current_index].clone();
                    if !quiet {
                        if !no_color {
                            eprint!("\r\x1b[32m[Matrix: {}]\x1b[0m\r\n", current_dictionary_name);
                        } else {
                            eprint!("\r[Matrix: {}]\r\n", current_dictionary_name);
                        }
                    }
                    continue; // Reload dictionary
                }
                _ => {}
            }
        }

        if !superman {
            thread::sleep(Duration::from_millis(250));
        }
    }
}

/// Auto-detect dictionary from input and decode
pub fn detect_mode(
    config: &DictionaryRegistry,
    file: Option<&PathBuf>,
    show_candidates: Option<usize>,
    decompress: Option<&String>,
    max_size: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    use base_d::DictionaryDetector;

    // Read input
    let input = if let Some(file_path) = file {
        // Check file size BEFORE reading
        let metadata = fs::metadata(file_path)?;
        let file_size = metadata.len() as usize;

        if max_size > 0 && file_size > max_size {
            return Err(format!(
                "File size ({} bytes) exceeds limit ({} bytes). Use --force to process anyway.",
                file_size, max_size
            )
            .into());
        }

        fs::read_to_string(file_path)?
    } else {
        let mut buffer = String::new();
        io::stdin().read_to_string(&mut buffer)?;

        // Check stdin size AFTER reading (can't pre-check stdin)
        if max_size > 0 && buffer.len() > max_size {
            return Err(format!(
                "Input size ({} bytes) exceeds maximum ({} bytes). Use --file with --force for large inputs.",
                buffer.len(),
                max_size
            ).into());
        }

        buffer
    };

    // Create detector and detect
    let detector = DictionaryDetector::new(config)?;
    let matches = detector.detect(input.trim());

    if matches.is_empty() {
        eprintln!("Could not detect dictionary - no matches found.");
        eprintln!("The input may not be encoded data, or uses an unknown dictionary.");
        std::process::exit(1);
    }

    // If --show-candidates is specified, show top N candidates
    if let Some(n) = show_candidates {
        println!("Top {} candidate dictionaries:\n", n);
        for (i, m) in matches.iter().take(n).enumerate() {
            println!(
                "{}. {} (confidence: {:.1}%)",
                i + 1,
                m.name,
                m.confidence * 100.0
            );
        }
        return Ok(());
    }

    // Otherwise, use the best match to decode
    let best_match = &matches[0];

    // Show what was detected (to stderr so it doesn't interfere with output)
    eprintln!(
        "Detected: {} (confidence: {:.1}%)",
        best_match.name,
        best_match.confidence * 100.0
    );

    // If confidence is low, warn the user
    if best_match.confidence < 0.7 {
        eprintln!("Warning: Low confidence detection. Results may be incorrect.");
    }

    // Decode using the detected dictionary
    let decoded = decode(input.trim(), &best_match.dictionary)?;

    // Handle decompression if requested
    let output = if let Some(decompress_name) = decompress {
        let algo = base_d::CompressionAlgorithm::from_str(decompress_name)?;
        base_d::decompress(&decoded, algo)?
    } else {
        decoded
    };

    // Output the decoded data
    io::stdout().write_all(&output)?;

    Ok(())
}

/// Streaming decode mode
#[allow(clippy::too_many_arguments)]
pub fn streaming_decode(
    config: &DictionaryRegistry,
    decode_name: &str,
    file: Option<&PathBuf>,
    decompress: Option<String>,
    hash: Option<String>,
    xxhash_seed: Option<u64>,
    xxhash_secret_stdin: bool,
    encode: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    use base_d::StreamingDecoder;

    let decode_dictionary = create_dictionary(config, decode_name)?;
    let mut decoder = StreamingDecoder::new(&decode_dictionary, io::stdout());

    // Add decompression if specified
    if let Some(algo_name) = decompress {
        let algo = base_d::CompressionAlgorithm::from_str(&algo_name)?;
        decoder = decoder.with_decompression(algo);
    }

    // Add hashing if specified
    if let Some(hash_name) = &hash {
        let hash_algo = base_d::HashAlgorithm::from_str(hash_name)?;
        decoder = decoder.with_hashing(hash_algo);

        // Add xxHash config
        let xxhash_config =
            load_xxhash_config(xxhash_seed, xxhash_secret_stdin, config, Some(&hash_algo))?;
        decoder = decoder.with_xxhash_config(xxhash_config);
    }

    let hash_result = if let Some(file_path) = file {
        let mut file_handle = fs::File::open(file_path)?;
        decoder
            .decode(&mut file_handle)
            .map_err(|e| format!("{:?}", e))?
    } else {
        decoder
            .decode(&mut io::stdin())
            .map_err(|e| format!("{:?}", e))?
    };

    // Print hash if computed
    if let Some(hash_bytes) = hash_result {
        if let Some(encode_name) = encode {
            let encode_dictionary = create_dictionary(config, &encode_name)?;
            let hash_encoded = base_d::encode(&hash_bytes, &encode_dictionary);
            eprintln!("Hash: {}", hash_encoded);
        } else {
            eprintln!("Hash: {}", hex::encode(hash_bytes));
        }
    }

    Ok(())
}

/// Streaming encode mode
#[allow(clippy::too_many_arguments)]
pub fn streaming_encode(
    config: &DictionaryRegistry,
    encode_name: &str,
    file: Option<&PathBuf>,
    compress: Option<String>,
    level: Option<u32>,
    hash: Option<String>,
    xxhash_seed: Option<u64>,
    xxhash_secret_stdin: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use base_d::StreamingEncoder;

    let encode_dictionary = create_dictionary(config, encode_name)?;
    let mut encoder = StreamingEncoder::new(&encode_dictionary, io::stdout());

    // Add compression if specified
    if let Some(algo_name) = compress {
        let algo = base_d::CompressionAlgorithm::from_str(&algo_name)?;
        let compression_level = get_compression_level(config, level, algo);
        encoder = encoder.with_compression(algo, compression_level);
    }

    // Add hashing if specified
    if let Some(hash_name) = &hash {
        let hash_algo = base_d::HashAlgorithm::from_str(hash_name)?;
        encoder = encoder.with_hashing(hash_algo);

        // Add xxHash config
        let xxhash_config =
            load_xxhash_config(xxhash_seed, xxhash_secret_stdin, config, Some(&hash_algo))?;
        encoder = encoder.with_xxhash_config(xxhash_config);
    }

    let hash_result = if let Some(file_path) = file {
        let mut file_handle = fs::File::open(file_path)?;
        encoder
            .encode(&mut file_handle)
            .map_err(|e| format!("{}", e))?
    } else {
        encoder
            .encode(&mut io::stdin())
            .map_err(|e| format!("{}", e))?
    };

    // Print hash if computed
    if let Some(hash_bytes) = hash_result {
        eprintln!("Hash: {}", hex::encode(hash_bytes));
    }

    Ok(())
}

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

    #[test]
    fn test_generate_word_line_basic() {
        let word_dict = base_d::WordDictionary::builder()
            .words(vec!["abandon", "ability", "able", "about"])
            .delimiter(" ")
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let line = generate_word_line(&mut rng, &word_dict, 80);

        // Line should be non-empty
        assert!(!line.is_empty());
        // Line should fit within terminal width
        assert!(line.chars().count() <= 80);
        // Line should contain words from the dictionary
        for word in line.split(' ') {
            assert!(
                ["abandon", "ability", "able", "about"].contains(&word),
                "Unknown word in line: {}",
                word
            );
        }
    }

    #[test]
    fn test_generate_word_line_respects_width() {
        let word_dict = base_d::WordDictionary::builder()
            .words(vec![
                "verylongword",
                "anotherlongword",
                "yetanotherlongword",
            ])
            .delimiter(" ")
            .build()
            .unwrap();

        let mut rng = rand::rng();

        // With small terminal width, should still produce valid output
        let line = generate_word_line(&mut rng, &word_dict, 20);
        assert!(line.chars().count() <= 20);

        // With very small width, should truncate first word
        let line = generate_word_line(&mut rng, &word_dict, 5);
        assert!(line.chars().count() <= 5);
        assert!(
            !line.is_empty(),
            "Should produce truncated word, not empty string"
        );
    }

    #[test]
    fn test_generate_word_line_truncates_long_first_word() {
        let word_dict = base_d::WordDictionary::builder()
            .words(vec!["supercalifragilisticexpialidocious"]) // 34 chars
            .delimiter(" ")
            .build()
            .unwrap();

        let mut rng = rand::rng();

        // Terminal width smaller than word - should truncate
        let line = generate_word_line(&mut rng, &word_dict, 10);
        assert_eq!(line.chars().count(), 10);
        assert_eq!(line, "supercalif");
    }

    #[test]
    fn test_generate_word_line_empty_dictionary() {
        // This shouldn't happen in practice, but let's handle it gracefully
        // We can't actually create an empty WordDictionary (it returns an error)
        // So this test verifies the function would return empty for an empty word list
        // The check in the function handles this case
    }

    #[test]
    fn test_generate_word_line_with_custom_delimiter() {
        let word_dict = base_d::WordDictionary::builder()
            .words(vec!["alpha", "bravo", "charlie", "delta"])
            .delimiter("-")
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let line = generate_word_line(&mut rng, &word_dict, 80);

        // Should use the custom delimiter
        assert!(line.contains('-') || !line.contains(' '));
    }

    #[test]
    fn test_generate_word_line_bip39_style() {
        // Simulate a BIP39-style dictionary with longer words
        let bip39_sample = base_d::WordDictionary::builder()
            .words(vec![
                "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract",
                "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid",
            ])
            .delimiter(" ")
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let line = generate_word_line(&mut rng, &bip39_sample, 100);

        // Should produce multiple words
        let word_count = line.split(' ').count();
        assert!(word_count >= 1, "Should have at least one word");

        // Each word should be from the dictionary
        for word in line.split(' ') {
            assert!(
                bip39_sample.decode_word(word).is_some(),
                "Word not in dictionary: {}",
                word
            );
        }
    }
}