pxh 0.9.9

pxh is a fast, cross-shell history mining tool with interactive fuzzy search, secret scanning, and bidirectional sync across machines. It indexes bash and zsh history in SQLite with rich metadata for powerful recall.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::time::{Duration, Instant};

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
    execute, queue,
    style::{Attribute, Color, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor},
    terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
};

#[cfg(not(target_os = "windows"))]
use crossterm::event::{
    KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};

use super::command::{FilterMode, HostFilter};
use super::config::{KeymapMode, PreviewConfig, RecallConfig};
use super::engine::{HistoryEntry, SearchEngine, format_relative_time};

const SCROLL_MARGIN: usize = 5;

/// Sanitize a string for safe terminal display by removing ANSI escape sequences
/// and control characters that could affect cursor position or terminal state.
fn sanitize_for_display(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        match c {
            // ESC - start of ANSI escape sequence
            '\x1b' => {
                // Skip the escape sequence
                if let Some(&next) = chars.peek()
                    && next == '['
                {
                    chars.next(); // consume '['
                    // Skip until we hit a letter (end of CSI sequence)
                    while let Some(&c) = chars.peek() {
                        chars.next();
                        if c.is_ascii_alphabetic() {
                            break;
                        }
                    }
                }
            }
            // Newline, carriage return - would break row containment
            '\n' | '\r' => result.push(' '),
            // Other control characters that could affect display
            '\x00'..='\x08' | '\x0b'..='\x0c' | '\x0e'..='\x1f' | '\x7f' => {}
            // Tab - convert to space
            '\t' => result.push(' '),
            // Everything else passes through
            _ => result.push(c),
        }
    }

    result
}

const PREVIEW_HEIGHT: usize = 5; // Height of preview pane in lines
const FLASH_DURATION_MS: u64 = 100; // Duration of visual flash in milliseconds

/// Deduplicate history entries by command string, keeping the most recent occurrence.
/// Entries are already sorted by timestamp (most recent first), so we keep the first
/// occurrence of each command.
fn deduplicate_entries(entries: Vec<HistoryEntry>) -> Vec<HistoryEntry> {
    let mut seen = HashSet::new();
    entries.into_iter().filter(|e| seen.insert(e.command.clone())).collect()
}

/// Highlight matching portions of a command for display (substring matching).
/// Returns spans with (text, is_highlight) pairs.
/// Only used in tests now - fuzzy matching uses highlight_command_with_indices.
#[cfg(test)]
fn highlight_command(cmd: &str, query: &str, max_len: usize) -> Vec<(String, bool)> {
    if query.is_empty() {
        let truncated = if cmd.chars().count() > max_len {
            let t: String = cmd.chars().take(max_len.saturating_sub(3)).collect();
            format!("{t}...")
        } else {
            cmd.to_string()
        };
        return vec![(truncated, false)];
    }

    let cmd_lower = cmd.to_lowercase();
    let query_lower = query.to_lowercase();
    let mut spans = Vec::new();
    let mut pos = 0;
    let cmd_chars: Vec<char> = cmd.chars().collect();
    let mut total_len = 0;

    while let Some(match_start) = cmd_lower[pos..].find(&query_lower) {
        let abs_start = pos + match_start;
        let abs_end = abs_start + query_lower.len();

        // Add non-matching text before this match
        if abs_start > pos {
            let text: String = cmd_chars
                [char_pos_from_byte(cmd, pos)..char_pos_from_byte(cmd, abs_start)]
                .iter()
                .collect();
            let text_len = text.chars().count();
            if total_len + text_len > max_len.saturating_sub(3) {
                let remaining = max_len.saturating_sub(3).saturating_sub(total_len);
                let truncated: String = text.chars().take(remaining).collect();
                spans.push((truncated, false));
                spans.push(("...".to_string(), false));
                return spans;
            }
            total_len += text_len;
            spans.push((text, false));
        }

        // Add matching text
        let match_text: String = cmd_chars
            [char_pos_from_byte(cmd, abs_start)..char_pos_from_byte(cmd, abs_end)]
            .iter()
            .collect();
        let match_len = match_text.chars().count();
        if total_len + match_len > max_len.saturating_sub(3) {
            let remaining = max_len.saturating_sub(3).saturating_sub(total_len);
            let truncated: String = match_text.chars().take(remaining).collect();
            spans.push((truncated, true));
            spans.push(("...".to_string(), false));
            return spans;
        }
        total_len += match_len;
        spans.push((match_text, true));

        pos = abs_end;
    }

    // Add remaining text after last match
    if pos < cmd.len() {
        let text: String = cmd_chars[char_pos_from_byte(cmd, pos)..].iter().collect();
        let text_len = text.chars().count();
        if total_len + text_len > max_len {
            let remaining = max_len.saturating_sub(3).saturating_sub(total_len);
            let truncated: String = text.chars().take(remaining).collect();
            spans.push((truncated, false));
            spans.push(("...".to_string(), false));
        } else {
            spans.push((text, false));
        }
    }

    spans
}

/// Convert byte position to char position in a string.
#[cfg(test)]
fn char_pos_from_byte(s: &str, byte_pos: usize) -> usize {
    s[..byte_pos].chars().count()
}

/// Highlight a command using pre-computed match indices from fuzzy matching.
/// Returns spans with (text, is_highlight) pairs.
fn highlight_command_with_indices(
    cmd: &str,
    match_indices: &[u32],
    max_len: usize,
) -> Vec<(String, bool)> {
    if cmd.is_empty() {
        return vec![];
    }

    // Build a set of matched character positions for O(1) lookup
    let match_set: HashSet<u32> = match_indices.iter().copied().collect();

    let chars: Vec<char> = cmd.chars().collect();
    let mut spans = Vec::new();
    let mut current_span = String::new();
    let mut current_is_match = false;

    for (i, &c) in chars.iter().enumerate() {
        // Truncate early to leave room for "..." suffix
        if i >= max_len.saturating_sub(3) {
            // Truncate with ellipsis
            if !current_span.is_empty() {
                spans.push((current_span, current_is_match));
            }
            spans.push(("...".to_string(), false));
            return spans;
        }

        let is_match = match_set.contains(&(i as u32));

        if is_match != current_is_match && !current_span.is_empty() {
            spans.push((std::mem::take(&mut current_span), current_is_match));
        }

        current_is_match = is_match;
        current_span.push(c);
    }

    if !current_span.is_empty() {
        spans.push((current_span, current_is_match));
    }

    spans
}

fn format_duration(secs: i64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m {}s", secs / 60, secs % 60)
    } else {
        format!("{}h {}m {}s", secs / 3600, (secs % 3600) / 60, secs % 60)
    }
}

pub struct RecallTui {
    engine: SearchEngine,
    filter_mode: FilterMode,
    host_filter: HostFilter,
    entries: Vec<HistoryEntry>,
    /// Filtered indices with match positions: (entry_index, match_char_indices)
    filtered_indices: Vec<(usize, Vec<u32>)>,
    query: String,
    selected_index: usize,
    scroll_offset: usize, // Index of entry at top of visible area
    tty: File,
    term_height: u16,
    term_width: u16,
    keymap_mode: KeymapMode,
    show_preview: bool,
    preview_config: PreviewConfig,
    shell_mode: bool, // When true, outputs command for shell execution; when false, prints details
    flash_until: Option<Instant>, // For visual feedback on unrecognized keys
    #[cfg(not(target_os = "windows"))]
    keyboard_enhanced: bool,
}

impl RecallTui {
    pub fn new(
        mut engine: SearchEngine,
        initial_mode: FilterMode,
        initial_query: Option<String>,
        config: &RecallConfig,
        shell_mode: bool,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let query = initial_query.as_deref().unwrap_or("").to_string();
        let host_filter = HostFilter::default();
        // Load all entries without query filtering - fuzzy matching happens client-side
        let entries = deduplicate_entries(engine.load_entries(initial_mode, host_filter, None)?);

        terminal::enable_raw_mode()?;
        let mut tty = File::options().read(true).write(true).open("/dev/tty")?;

        // Enable keyboard enhancement for instant Escape key response (non-Windows)
        #[cfg(not(target_os = "windows"))]
        let keyboard_enhanced = execute!(
            tty,
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        )
        .is_ok();

        execute!(
            tty,
            EnterAlternateScreen,
            Hide,
            Clear(ClearType::All),
            Clear(ClearType::Purge),
            MoveTo(0, 0)
        )?;
        tty.flush()?;

        let (term_width, term_height) = terminal::size()?;

        // Apply initial fuzzy filtering
        let filtered_indices = if query.is_empty() {
            (0..entries.len()).map(|i| (i, Vec::new())).collect()
        } else {
            engine
                .filter_entries(&entries, &query)
                .into_iter()
                .map(|(entry, indices)| {
                    // Map entry reference back to index via pointer equality
                    // (filter_entries returns references into our entries slice)
                    let idx = entries
                        .iter()
                        .position(|e| std::ptr::eq(e, entry))
                        .expect("filter_entries returned entry not in entries slice");
                    (idx, indices)
                })
                .collect()
        };

        let mut tui = RecallTui {
            engine,
            filter_mode: initial_mode,
            host_filter,
            entries,
            filtered_indices,
            query,
            selected_index: 0,
            scroll_offset: 0,
            tty,
            term_height,
            term_width,
            keymap_mode: config.initial_keymap_mode(),
            show_preview: config.show_preview,
            preview_config: config.preview.clone(),
            shell_mode,
            flash_until: None,
            #[cfg(not(target_os = "windows"))]
            keyboard_enhanced,
        };

        tui.adjust_scroll_for_selection();
        Ok(tui)
    }

    fn results_height(&self) -> usize {
        let base = self.term_height.saturating_sub(2) as usize;
        if self.show_preview { base.saturating_sub(PREVIEW_HEIGHT) } else { base }
    }

    fn adjust_scroll_for_selection(&mut self) {
        let results_height = self.results_height();
        if results_height == 0 || self.filtered_indices.is_empty() {
            self.scroll_offset = 0;
            return;
        }

        // In our layout, entry 0 (most recent) is at the bottom visually.
        // scroll_offset is the entry index shown at the TOP of the visible area.
        // Higher scroll_offset means we're showing older entries.
        //
        // Visible range: scroll_offset.saturating_sub(results_height - 1) to scroll_offset
        // But actually, let's think of it differently:
        //   - The bottom of the visible area shows entry index `bottom_visible`
        //   - The top shows entry index `bottom_visible + results_height - 1`
        //
        // Let's use `view_bottom` as the entry index shown at the bottom of results area.
        // Visible entries: view_bottom to view_bottom + results_height - 1

        // Calculate current view bounds based on scroll_offset
        // scroll_offset represents the entry at the bottom of the visible area
        let view_bottom = self.scroll_offset;
        let view_top = view_bottom + results_height.saturating_sub(1);

        // Check if selected is within the visible range with margins
        if self.selected_index < view_bottom + SCROLL_MARGIN {
            // Selection is too close to bottom, scroll down (show newer entries)
            self.scroll_offset = self.selected_index.saturating_sub(SCROLL_MARGIN);
        } else if self.selected_index > view_top.saturating_sub(SCROLL_MARGIN) {
            // Selection is too close to top, scroll up (show older entries)
            let new_view_top = self.selected_index + SCROLL_MARGIN;
            self.scroll_offset = new_view_top.saturating_sub(results_height.saturating_sub(1));
        }

        // Clamp scroll_offset to valid range
        let max_scroll = self.filtered_indices.len().saturating_sub(results_height);
        self.scroll_offset = self.scroll_offset.min(max_scroll);
    }

    /// Reload entries from database and re-apply fuzzy filtering.
    /// Called when mode (directory/global) or host filter changes.
    fn reload_entries(&mut self) {
        match self.engine.load_entries(self.filter_mode, self.host_filter, None) {
            Ok(entries) => {
                self.entries = deduplicate_entries(entries);
            }
            Err(e) => {
                eprintln!("pxh recall: failed to reload entries: {e}");
                self.flash();
                return;
            }
        }
        self.update_filtered_indices();
    }

    /// Apply fuzzy filtering to the current entries based on query
    fn update_filtered_indices(&mut self) {
        if self.query.is_empty() {
            self.filtered_indices = (0..self.entries.len()).map(|i| (i, Vec::new())).collect();
        } else {
            self.filtered_indices = self
                .engine
                .filter_entries(&self.entries, &self.query)
                .into_iter()
                .map(|(entry, indices)| {
                    // Map entry reference back to index via pointer equality
                    let idx = self
                        .entries
                        .iter()
                        .position(|e| std::ptr::eq(e, entry))
                        .expect("filter_entries returned entry not in entries slice");
                    (idx, indices)
                })
                .collect();
        }

        if self.selected_index >= self.filtered_indices.len() {
            self.selected_index = 0;
        }
        self.adjust_scroll_for_selection();
    }

    /// Trigger a brief visual flash for feedback on unrecognized keys
    fn flash(&mut self) {
        self.flash_until = Some(Instant::now() + Duration::from_millis(FLASH_DURATION_MS));
    }

    /// Check if flash effect is currently active
    fn is_flashing(&self) -> bool {
        self.flash_until.is_some_and(|until| Instant::now() < until)
    }

    fn toggle_host_filter(&mut self) {
        self.host_filter = match self.host_filter {
            HostFilter::ThisHost => HostFilter::AllHosts,
            HostFilter::AllHosts => HostFilter::ThisHost,
        };
        self.reload_entries();
    }

    fn toggle_filter_mode(&mut self) {
        self.filter_mode = match self.filter_mode {
            FilterMode::Directory => FilterMode::Global,
            FilterMode::Global => FilterMode::Directory,
        };
        self.reload_entries();
    }

    pub fn run(&mut self) -> Result<Option<String>, Box<dyn std::error::Error>> {
        loop {
            self.draw()?;

            // Poll with timeout for responsive cancellation and future async features
            if !event::poll(Duration::from_millis(100))? {
                continue;
            }

            if let Event::Key(key) = event::read()? {
                let action = self.handle_key(key)?;
                match action {
                    KeyAction::Continue => continue,
                    KeyAction::Select | KeyAction::Edit => {
                        self.cleanup()?;
                        if !self.shell_mode {
                            self.print_entry_details();
                            return Ok(None);
                        }
                        let prefix =
                            if matches!(action, KeyAction::Select) { "run" } else { "edit" };
                        let result =
                            self.get_selected_command().map(|cmd| format!("{prefix}:{cmd}"));
                        return Ok(result);
                    }
                    KeyAction::Cancel => {
                        self.cleanup()?;
                        return Ok(None);
                    }
                }
            }
        }
    }

    fn print_entry_details(&self) {
        let Some(entry) = self
            .filtered_indices
            .get(self.selected_index)
            .and_then(|(idx, _)| self.entries.get(*idx))
        else {
            return;
        };

        let mut stdout = std::io::stdout();

        // Command (bold)
        let _ = execute!(stdout, SetAttribute(Attribute::Bold));
        println!("{}", entry.command);
        let _ = execute!(stdout, SetAttribute(Attribute::Reset));

        // Timestamp
        if let Some(ts) = entry.timestamp {
            let datetime = chrono::DateTime::from_timestamp(ts, 0)
                .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
                .unwrap_or_else(|| "?".to_string());
            let relative = format_relative_time(Some(ts));
            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
            print!("  Time: ");
            let _ = execute!(stdout, ResetColor);
            println!("{datetime} ({relative} ago)");
        }

        // Directory
        if let Some(ref dir) = entry.working_directory {
            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
            print!("   Dir: ");
            let _ = execute!(stdout, ResetColor);
            println!("{}", String::from_utf8_lossy(dir));
        }

        // Exit status
        if let Some(status) = entry.exit_status {
            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
            print!("Status: ");
            let _ = execute!(stdout, ResetColor);
            if status == 0 {
                let _ = execute!(stdout, SetForegroundColor(Color::Green));
                println!("0 (success)");
            } else {
                let _ = execute!(stdout, SetForegroundColor(Color::Red));
                println!("{status} (error)");
            }
            let _ = execute!(stdout, ResetColor);
        }

        // Duration
        if let Some(secs) = entry.duration_secs {
            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
            print!("  Took: ");
            let _ = execute!(stdout, ResetColor);
            println!("{}", format_duration(secs));
        }

        // Hostname
        if let Some(ref host) = entry.hostname {
            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
            print!("  Host: ");
            let _ = execute!(stdout, ResetColor);
            println!("{}", String::from_utf8_lossy(host));
        }
    }

    /// Draw once and exit (for profiling)
    pub fn draw_once(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.draw()?;
        self.cleanup()?;
        Ok(())
    }

    fn cleanup(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        #[cfg(not(target_os = "windows"))]
        if self.keyboard_enhanced {
            let _ = execute!(self.tty, PopKeyboardEnhancementFlags);
        }
        execute!(self.tty, Show, LeaveAlternateScreen)?;
        terminal::disable_raw_mode()?;
        Ok(())
    }

    fn get_selected_command(&self) -> Option<String> {
        self.filtered_indices
            .get(self.selected_index)
            .and_then(|(idx, _)| self.entries.get(*idx))
            .map(|e| e.command.clone())
    }

    fn handle_key(&mut self, key: KeyEvent) -> Result<KeyAction, Box<dyn std::error::Error>> {
        match self.keymap_mode {
            KeymapMode::Emacs => self.handle_key_emacs(key),
            KeymapMode::VimInsert => self.handle_key_vim_insert(key),
            KeymapMode::VimNormal => self.handle_key_vim_normal(key),
        }
    }

    /// Handle common keys that work in all modes
    fn handle_common_key(&mut self, key: KeyEvent) -> Option<KeyAction> {
        match key.code {
            KeyCode::Enter => Some(KeyAction::Select),
            KeyCode::Tab => Some(KeyAction::Edit),
            KeyCode::Char('c' | 'd') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                Some(KeyAction::Cancel)
            }
            KeyCode::Char('r') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.move_selection_up();
                Some(KeyAction::Continue)
            }
            KeyCode::Up => {
                self.move_selection_up();
                Some(KeyAction::Continue)
            }
            KeyCode::Down => {
                self.move_selection_down();
                Some(KeyAction::Continue)
            }
            KeyCode::PageUp => {
                self.page_up();
                Some(KeyAction::Continue)
            }
            KeyCode::PageDown => {
                self.page_down();
                Some(KeyAction::Continue)
            }
            KeyCode::Char(c @ '1'..='9') if key.modifiers.contains(KeyModifiers::ALT) => {
                let num = c.to_digit(10).unwrap() as usize;
                // Alt-1 selects current, Alt-2 selects next older, etc.
                let target_index = self.selected_index + (num - 1);
                if target_index < self.filtered_indices.len() {
                    self.selected_index = target_index;
                    return Some(KeyAction::Select);
                }
                Some(KeyAction::Continue)
            }
            KeyCode::Char('h') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.toggle_host_filter();
                Some(KeyAction::Continue)
            }
            KeyCode::Char('g') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.toggle_filter_mode();
                Some(KeyAction::Continue)
            }
            KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                Some(KeyAction::Edit)
            }
            _ => None,
        }
    }

    fn handle_key_emacs(&mut self, key: KeyEvent) -> Result<KeyAction, Box<dyn std::error::Error>> {
        // Check common keys first
        if let Some(action) = self.handle_common_key(key) {
            return Ok(action);
        }

        match key.code {
            KeyCode::Esc => Ok(KeyAction::Cancel),
            KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.move_selection_up();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.move_selection_down();
                Ok(KeyAction::Continue)
            }
            KeyCode::Backspace => {
                self.delete_last_char();
                Ok(KeyAction::Continue)
            }
            KeyCode::Right => Ok(KeyAction::Edit),
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.clear_query();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char('w') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.delete_last_word();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char(_) if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.flash();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char(c) => {
                self.insert_char(c);
                Ok(KeyAction::Continue)
            }
            _ => Ok(KeyAction::Continue),
        }
    }

    fn handle_key_vim_insert(
        &mut self,
        key: KeyEvent,
    ) -> Result<KeyAction, Box<dyn std::error::Error>> {
        // Check common keys first
        if let Some(action) = self.handle_common_key(key) {
            return Ok(action);
        }

        match key.code {
            KeyCode::Esc => {
                self.keymap_mode = KeymapMode::VimNormal;
                Ok(KeyAction::Continue)
            }
            KeyCode::Backspace => {
                self.delete_last_char();
                Ok(KeyAction::Continue)
            }
            KeyCode::Right => Ok(KeyAction::Edit),
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.clear_query();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char('w') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.delete_last_word();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char(_) if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.flash();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char(c) => {
                self.insert_char(c);
                Ok(KeyAction::Continue)
            }
            _ => Ok(KeyAction::Continue),
        }
    }

    fn handle_key_vim_normal(
        &mut self,
        key: KeyEvent,
    ) -> Result<KeyAction, Box<dyn std::error::Error>> {
        // Check common keys first
        if let Some(action) = self.handle_common_key(key) {
            return Ok(action);
        }

        match key.code {
            KeyCode::Esc => Ok(KeyAction::Cancel),
            KeyCode::Char('j') => {
                self.move_selection_down();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char('k') => {
                self.move_selection_up();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char('l') | KeyCode::Right => Ok(KeyAction::Edit),
            KeyCode::Char('i' | 'a' | 'A' | 'I') => {
                self.keymap_mode = KeymapMode::VimInsert;
                Ok(KeyAction::Continue)
            }
            KeyCode::Char('x' | 'X') => {
                self.delete_last_char();
                Ok(KeyAction::Continue)
            }
            KeyCode::Char(_) if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.flash();
                Ok(KeyAction::Continue)
            }
            _ => Ok(KeyAction::Continue),
        }
    }

    // Helper methods for selection movement and query editing

    fn move_selection_up(&mut self) {
        if self.selected_index + 1 < self.filtered_indices.len() {
            self.selected_index += 1;
            self.adjust_scroll_for_selection();
        }
    }

    fn move_selection_down(&mut self) {
        if self.selected_index > 0 {
            self.selected_index -= 1;
            self.adjust_scroll_for_selection();
        }
    }

    fn page_up(&mut self) {
        let page = self.results_height().saturating_sub(2);
        let max_index = self.filtered_indices.len().saturating_sub(1);
        self.selected_index = (self.selected_index + page).min(max_index);
        self.adjust_scroll_for_selection();
    }

    fn page_down(&mut self) {
        let page = self.results_height().saturating_sub(2);
        self.selected_index = self.selected_index.saturating_sub(page);
        self.adjust_scroll_for_selection();
    }

    fn insert_char(&mut self, c: char) {
        self.query.push(c);
        self.update_filtered_indices();
    }

    fn delete_last_char(&mut self) {
        if self.query.pop().is_some() {
            self.update_filtered_indices();
        }
    }

    fn clear_query(&mut self) {
        if !self.query.is_empty() {
            self.query.clear();
            self.update_filtered_indices();
        }
    }

    fn delete_last_word(&mut self) {
        if !self.query.is_empty() {
            let trimmed_len = self.query.trim_end().len();
            let word_start =
                self.query[..trimmed_len].rfind(char::is_whitespace).map(|i| i + 1).unwrap_or(0);
            self.query.truncate(word_start);
            self.update_filtered_indices();
        }
    }

    fn draw_preview<W: Write>(
        &self,
        w: &mut W,
        start_y: u16,
        width: u16,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Get the selected entry
        let entry = self
            .filtered_indices
            .get(self.selected_index)
            .and_then(|(idx, _)| self.entries.get(*idx));

        // Draw separator line
        queue!(w, MoveTo(0, start_y), Clear(ClearType::CurrentLine))?;
        queue!(w, SetForegroundColor(Color::DarkGrey))?;
        write!(w, "{}", "".repeat(width as usize))?;
        queue!(w, ResetColor)?;

        // If no entry selected, clear the rest and return
        let Some(entry) = entry else {
            for row in 1..PREVIEW_HEIGHT {
                queue!(w, MoveTo(0, start_y + row as u16), Clear(ClearType::CurrentLine))?;
            }
            return Ok(());
        };

        // Line 1: Full command (can truncate)
        queue!(w, MoveTo(0, start_y + 1), Clear(ClearType::CurrentLine))?;
        let safe_cmd = sanitize_for_display(&entry.command);
        let cmd_display: String = if safe_cmd.chars().count() > width as usize - 2 {
            let truncated: String = safe_cmd.chars().take(width as usize - 5).collect();
            format!("{truncated}...")
        } else {
            safe_cmd
        };
        write!(w, "  {cmd_display}")?;

        // Line 2: Directory and timestamp
        queue!(w, MoveTo(0, start_y + 2), Clear(ClearType::CurrentLine))?;
        let mut info_parts: Vec<String> = Vec::new();

        if self.preview_config.show_directory
            && let Some(ref dir) = entry.working_directory
        {
            info_parts.push(format!("Dir: {}", String::from_utf8_lossy(dir)));
        }

        if self.preview_config.show_timestamp
            && let Some(ts) = entry.timestamp
        {
            let datetime = chrono::DateTime::from_timestamp(ts, 0)
                .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
                .unwrap_or_else(|| "?".to_string());
            info_parts.push(format!("Time: {datetime}"));
        }

        queue!(w, SetForegroundColor(Color::DarkGrey))?;
        write!(w, "  {}", info_parts.join("  "))?;
        queue!(w, ResetColor)?;

        // Line 3: Exit status, duration, hostname
        queue!(w, MoveTo(0, start_y + 3), Clear(ClearType::CurrentLine))?;
        let mut status_parts: Vec<String> = Vec::new();

        if self.preview_config.show_exit_status
            && let Some(status) = entry.exit_status
        {
            let status_str = if status == 0 {
                "Status: 0 (ok)".to_string()
            } else {
                format!("Status: {status} (error)")
            };
            status_parts.push(status_str);
        }

        if self.preview_config.show_duration
            && let Some(secs) = entry.duration_secs
        {
            status_parts.push(format!("Duration: {}", format_duration(secs)));
        }

        if self.preview_config.show_hostname
            && let Some(ref host) = entry.hostname
        {
            status_parts.push(format!("Host: {}", String::from_utf8_lossy(host)));
        }

        queue!(w, SetForegroundColor(Color::DarkGrey))?;
        write!(w, "  {}", status_parts.join("  "))?;
        queue!(w, ResetColor)?;

        // Line 4: Bottom separator (blank or separator)
        queue!(w, MoveTo(0, start_y + 4), Clear(ClearType::CurrentLine))?;

        Ok(())
    }

    fn draw(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Get fresh terminal size each frame
        let (term_width, term_height) = terminal::size()?;
        self.term_width = term_width;
        self.term_height = term_height;

        let results_height = self.results_height();
        let preview_start_y = results_height as u16;
        let input_y = term_height.saturating_sub(2);
        let help_y = term_height.saturating_sub(1);

        // Use buffered writer to batch all terminal writes into a single syscall
        let mut w = BufWriter::new(&self.tty);

        // Check if we're in flash mode for visual feedback
        let flashing = self.is_flashing();

        // Disable line wrap during render to prevent visual glitches
        write!(w, "\x1b[?7l")?;

        // Draw each line, clearing as we go (avoids full-screen clear flicker)
        // Results area: rows 0 to results_height-1
        // Layout: oldest at top (row 0), newest at bottom (row results_height-1)
        // scroll_offset is the entry index shown at the bottom of the visible area
        for row in 0..results_height {
            queue!(w, MoveTo(0, row as u16), Clear(ClearType::CurrentLine))?;

            // Calculate which entry to show at this row
            // Row 0 (top) shows oldest visible entry
            // Row results_height-1 (bottom) shows entry at scroll_offset
            let offset_from_bottom = results_height - 1 - row;
            let entry_index = self.scroll_offset + offset_from_bottom;

            if entry_index >= self.filtered_indices.len() {
                continue;
            }

            let (idx, ref match_indices) = self.filtered_indices[entry_index];
            let entry = &self.entries[idx];
            let time_str = format_relative_time(entry.timestamp);
            let is_selected = entry_index == self.selected_index;

            // Calculate quick-select number (1-9) relative to selection
            // Alt-1 = selected, Alt-2 = selected+1 (next older), etc.
            let quick_num =
                if entry_index >= self.selected_index && entry_index < self.selected_index + 9 {
                    Some(entry_index - self.selected_index + 1)
                } else {
                    None
                };

            if is_selected {
                queue!(w, SetBackgroundColor(Color::DarkGrey))?;
            }

            // Draw quick-select indicator or selection marker
            if let Some(n) = quick_num {
                queue!(w, SetForegroundColor(Color::Yellow))?;
                write!(w, "{n}")?;
                queue!(w, ResetColor)?;
                if is_selected {
                    queue!(w, SetBackgroundColor(Color::DarkGrey))?;
                    write!(w, ">")?;
                } else {
                    write!(w, " ")?;
                }
            } else if is_selected {
                write!(w, " >")?;
            } else {
                write!(w, "  ")?;
            }

            queue!(w, SetForegroundColor(Color::DarkGrey))?;
            write!(w, "{time_str}  ")?;
            queue!(w, ResetColor)?;

            if is_selected {
                queue!(w, SetBackgroundColor(Color::DarkGrey))?;
            }

            // Show host prefix for entries from other hosts (in AllHosts mode)
            let host_prefix = if self.host_filter == HostFilter::AllHosts {
                entry.hostname.as_ref().and_then(|h| {
                    if !self.engine.is_this_host(h) {
                        let short =
                            String::from_utf8_lossy(h).split('.').next().unwrap_or("?").to_string();
                        Some(format!("@{short}: "))
                    } else {
                        None
                    }
                })
            } else {
                None
            };

            // Draw host prefix if present
            let host_prefix_len = host_prefix.as_ref().map_or(0, |p| p.chars().count());
            if let Some(ref prefix) = host_prefix {
                queue!(w, SetForegroundColor(Color::Magenta))?;
                write!(w, "{prefix}")?;
                queue!(w, ResetColor)?;
                if is_selected {
                    queue!(w, SetBackgroundColor(Color::DarkGrey))?;
                }
            }

            // Sanitize and truncate command to fit (handle UTF-8 safely)
            let safe_cmd = sanitize_for_display(&entry.command);
            let prefix_len = 9 + host_prefix_len; // "n>" + " XXx  " + host prefix
            let max_cmd_len = term_width.saturating_sub(prefix_len as u16) as usize;

            // Render command with highlighted fuzzy matches
            let spans = highlight_command_with_indices(&safe_cmd, match_indices, max_cmd_len);
            for (text, is_match) in spans {
                if is_match {
                    queue!(w, SetAttribute(Attribute::Bold))?;
                    queue!(w, SetForegroundColor(Color::Cyan))?;
                }
                write!(w, "{text}")?;
                if is_match {
                    queue!(w, SetAttribute(Attribute::Reset))?;
                    queue!(w, ResetColor)?;
                    if is_selected {
                        queue!(w, SetBackgroundColor(Color::DarkGrey))?;
                    }
                }
            }

            queue!(w, ResetColor)?;
        }

        // Draw preview pane if enabled
        if self.show_preview {
            self.draw_preview(&mut w, preview_start_y, term_width)?;
        }

        // Draw input line
        queue!(w, MoveTo(0, input_y), Clear(ClearType::CurrentLine))?;
        write!(w, "> {}", self.query)?;

        // Draw mode indicators on same line (host filter + dir/global)
        let host_str = match self.host_filter {
            HostFilter::ThisHost => {
                let hostname = self.engine.primary_hostname();
                let short_host =
                    String::from_utf8_lossy(hostname).split('.').next().unwrap_or("?").to_string();
                format!("[{short_host}]")
            }
            HostFilter::AllHosts => "[All Hosts]".to_string(),
        };
        let dir_str = match self.filter_mode {
            FilterMode::Directory => {
                let dir = self.engine.working_directory();
                let name = dir
                    .file_name()
                    .map(|s| s.to_string_lossy().to_string())
                    .unwrap_or_else(|| "?".to_string());
                format!("[Dir: {name}]")
            }
            FilterMode::Global => "[Global]".to_string(),
        };
        let mode_str = format!("{host_str} {dir_str}");
        let mode_x = term_width.saturating_sub(mode_str.len() as u16 + 1);
        queue!(w, MoveTo(mode_x, input_y), SetForegroundColor(Color::Cyan))?;
        write!(w, "{mode_str}")?;
        queue!(w, ResetColor)?;

        // Draw help line (mode-aware, flashes on unrecognized keys)
        queue!(w, MoveTo(0, help_y), Clear(ClearType::CurrentLine))?;
        if flashing {
            // Flash effect: invert the help line colors
            queue!(w, SetBackgroundColor(Color::White), SetForegroundColor(Color::Black))?;
        } else {
            queue!(w, SetForegroundColor(Color::DarkGrey))?;
        }
        let help_text = match self.keymap_mode {
            KeymapMode::Emacs => {
                "↑↓/^R Nav  Enter Select  Tab/→/^E Edit  ^G Dir  ^H Host  ^C/^D Quit  Alt-1-9"
            }
            KeymapMode::VimInsert | KeymapMode::VimNormal => {
                "j/k Nav  Enter Select  Tab/→/^E Edit  ^G Dir  ^H Host  ^C/^D Quit  Esc Mode  Alt-1-9"
            }
        };
        write!(w, "{help_text}")?;
        queue!(w, ResetColor)?;

        // Position cursor at end of query in input line
        queue!(w, MoveTo(2 + self.query.len() as u16, input_y))?;

        // Re-enable line wrap
        write!(w, "\x1b[?7h")?;

        // Single flush writes all buffered content
        w.flush()?;
        Ok(())
    }
}

enum KeyAction {
    Continue,
    Select,
    Edit,
    Cancel,
}

impl Drop for RecallTui {
    fn drop(&mut self) {
        #[cfg(not(target_os = "windows"))]
        if self.keyboard_enhanced {
            let _ = execute!(self.tty, PopKeyboardEnhancementFlags);
        }
        let _ = execute!(self.tty, Show, LeaveAlternateScreen);
        let _ = terminal::disable_raw_mode();
    }
}

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

    #[test]
    fn test_sanitize_preserves_normal_text() {
        assert_eq!(sanitize_for_display("hello world"), "hello world");
        assert_eq!(sanitize_for_display("ls -la /tmp"), "ls -la /tmp");
    }

    #[test]
    fn test_sanitize_preserves_box_drawing() {
        // Box-drawing characters should pass through
        assert_eq!(sanitize_for_display("┌History───┐"), "┌History───┐");
        assert_eq!(sanitize_for_display("│ cell │"), "│ cell │");
        assert_eq!(sanitize_for_display("└───────┘"), "└───────┘");
    }

    #[test]
    fn test_sanitize_preserves_unicode() {
        assert_eq!(sanitize_for_display("héllo wörld"), "héllo wörld");
        assert_eq!(sanitize_for_display("日本語"), "日本語");
        assert_eq!(sanitize_for_display("emoji 🎉 test"), "emoji 🎉 test");
    }

    #[test]
    fn test_sanitize_strips_ansi_escape_sequences() {
        // Color codes
        assert_eq!(sanitize_for_display("\x1b[31mred\x1b[0m"), "red");
        assert_eq!(sanitize_for_display("\x1b[1;32mbold green\x1b[0m"), "bold green");

        // Cursor movement
        assert_eq!(sanitize_for_display("\x1b[H"), ""); // cursor home
        assert_eq!(sanitize_for_display("\x1b[2J"), ""); // clear screen
        assert_eq!(sanitize_for_display("\x1b[10;20H"), ""); // cursor position

        // Mixed content
        assert_eq!(sanitize_for_display("before\x1b[31mred\x1b[0mafter"), "beforeredafter");
    }

    #[test]
    fn test_sanitize_converts_newlines_to_spaces() {
        assert_eq!(sanitize_for_display("line1\nline2"), "line1 line2");
        assert_eq!(sanitize_for_display("line1\r\nline2"), "line1  line2");
        assert_eq!(sanitize_for_display("a\nb\nc"), "a b c");
    }

    #[test]
    fn test_sanitize_converts_tabs_to_spaces() {
        assert_eq!(sanitize_for_display("col1\tcol2"), "col1 col2");
        assert_eq!(sanitize_for_display("\t\tindented"), "  indented");
    }

    #[test]
    fn test_sanitize_strips_control_characters() {
        // Bell, backspace, etc.
        assert_eq!(sanitize_for_display("hello\x07world"), "helloworld"); // bell
        assert_eq!(sanitize_for_display("hello\x08world"), "helloworld"); // backspace
        assert_eq!(sanitize_for_display("a\x00b\x01c"), "abc"); // null and other low controls
        assert_eq!(sanitize_for_display("test\x7fdelete"), "testdelete"); // DEL
    }

    #[test]
    fn test_sanitize_handles_binary_garbage() {
        // Simulate binary data that might corrupt terminal
        let binary_garbage = "cmd\x1b[2J\x1b[H\x00\x01\x02\x03visible\x1b[31m";
        assert_eq!(sanitize_for_display(binary_garbage), "cmdvisible");
    }

    #[test]
    fn test_sanitize_handles_incomplete_escape_sequences() {
        // Incomplete escape at end of string
        assert_eq!(sanitize_for_display("text\x1b"), "text");
        assert_eq!(sanitize_for_display("text\x1b["), "text");
        assert_eq!(sanitize_for_display("text\x1b[123"), "text");
    }

    #[test]
    fn test_sanitize_empty_string() {
        assert_eq!(sanitize_for_display(""), "");
    }

    #[test]
    fn test_highlight_no_query() {
        // Empty query returns whole string unhighlighted
        let spans = highlight_command("ls -la", "", 100);
        assert_eq!(spans, vec![("ls -la".to_string(), false)]);
    }

    #[test]
    fn test_highlight_single_match() {
        let spans = highlight_command("grep foo bar", "foo", 100);
        assert_eq!(
            spans,
            vec![
                ("grep ".to_string(), false),
                ("foo".to_string(), true),
                (" bar".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_highlight_case_insensitive() {
        let spans = highlight_command("grep FOO bar", "foo", 100);
        assert_eq!(
            spans,
            vec![
                ("grep ".to_string(), false),
                ("FOO".to_string(), true),
                (" bar".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_highlight_multiple_matches() {
        let spans = highlight_command("foo bar foo", "foo", 100);
        assert_eq!(
            spans,
            vec![
                ("foo".to_string(), true),
                (" bar ".to_string(), false),
                ("foo".to_string(), true),
            ]
        );
    }

    #[test]
    fn test_highlight_at_start() {
        let spans = highlight_command("foo bar", "foo", 100);
        assert_eq!(spans, vec![("foo".to_string(), true), (" bar".to_string(), false),]);
    }

    #[test]
    fn test_highlight_at_end() {
        let spans = highlight_command("bar foo", "foo", 100);
        assert_eq!(spans, vec![("bar ".to_string(), false), ("foo".to_string(), true),]);
    }

    #[test]
    fn test_highlight_truncation() {
        // When command is too long, it should be truncated with "..."
        let spans = highlight_command("very long command here", "", 10);
        assert_eq!(spans, vec![("very lo...".to_string(), false)]);
    }

    #[test]
    fn test_highlight_no_match() {
        // Query not found - return whole string unhighlighted
        let spans = highlight_command("ls -la", "xyz", 100);
        assert_eq!(spans, vec![("ls -la".to_string(), false)]);
    }

    #[test]
    fn test_highlight_multibyte_query() {
        // Query with multi-byte UTF-8 characters
        let spans = highlight_command("find 日本語 here", "日本語", 100);
        assert_eq!(
            spans,
            vec![
                ("find ".to_string(), false),
                ("日本語".to_string(), true),
                (" here".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_highlight_multibyte_command() {
        // ASCII query in command with multi-byte chars
        let spans = highlight_command("echo 日本語 foo bar", "foo", 100);
        assert_eq!(
            spans,
            vec![
                ("echo 日本語 ".to_string(), false),
                ("foo".to_string(), true),
                (" bar".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_highlight_empty_command() {
        // Empty command returns empty spans (nothing to display)
        let spans = highlight_command("", "foo", 100);
        assert!(spans.is_empty());
    }

    #[test]
    fn test_highlight_empty_both() {
        // Empty command with empty query returns the empty string
        let spans = highlight_command("", "", 100);
        assert_eq!(spans, vec![("".to_string(), false)]);
    }

    #[test]
    fn test_deduplicate_empty_list() {
        use super::deduplicate_entries;
        let deduped = deduplicate_entries(vec![]);
        assert!(deduped.is_empty());
    }

    #[test]
    fn test_deduplicate_keeps_first_occurrence() {
        use super::deduplicate_entries;
        use crate::recall::engine::HistoryEntry;

        let entries = vec![
            HistoryEntry {
                command: "cmd1".to_string(),
                timestamp: Some(100),
                working_directory: None,
                exit_status: None,
                duration_secs: None,
                hostname: None,
            },
            HistoryEntry {
                command: "cmd2".to_string(),
                timestamp: Some(90),
                working_directory: None,
                exit_status: None,
                duration_secs: None,
                hostname: None,
            },
            HistoryEntry {
                command: "cmd1".to_string(), // duplicate
                timestamp: Some(80),
                working_directory: None,
                exit_status: None,
                duration_secs: None,
                hostname: None,
            },
        ];

        let deduped = deduplicate_entries(entries);
        assert_eq!(deduped.len(), 2);
        assert_eq!(deduped[0].command, "cmd1");
        assert_eq!(deduped[0].timestamp, Some(100)); // kept first (most recent)
        assert_eq!(deduped[1].command, "cmd2");
    }

    // Tests for highlight_command_with_indices (fuzzy match highlighting)
    #[test]
    fn test_fuzzy_highlight_no_indices() {
        use super::highlight_command_with_indices;
        // No match indices - whole string unhighlighted
        let spans = highlight_command_with_indices("git fetch origin", &[], 100);
        assert_eq!(spans, vec![("git fetch origin".to_string(), false)]);
    }

    #[test]
    fn test_fuzzy_highlight_scattered_matches() {
        use super::highlight_command_with_indices;
        // "gfo" fuzzy matching "git fetch origin" -> indices 0, 4, 10
        let spans = highlight_command_with_indices("git fetch origin", &[0, 4, 10], 100);
        assert_eq!(
            spans,
            vec![
                ("g".to_string(), true),
                ("it ".to_string(), false),
                ("f".to_string(), true),
                ("etch ".to_string(), false),
                ("o".to_string(), true),
                ("rigin".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_fuzzy_highlight_contiguous_matches() {
        use super::highlight_command_with_indices;
        // Contiguous matches should be grouped
        let spans = highlight_command_with_indices("grep foo bar", &[5, 6, 7], 100);
        assert_eq!(
            spans,
            vec![
                ("grep ".to_string(), false),
                ("foo".to_string(), true),
                (" bar".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_fuzzy_highlight_truncation() {
        use super::highlight_command_with_indices;
        // Long command truncated with ellipsis
        // max_len=10 means we truncate at position 7 (10-3), leaving room for "..."
        let spans = highlight_command_with_indices("very long command here", &[0, 5], 10);
        assert_eq!(
            spans,
            vec![
                ("v".to_string(), true),
                ("ery ".to_string(), false),
                ("l".to_string(), true),
                ("o".to_string(), false),
                ("...".to_string(), false),
            ]
        );
    }

    #[test]
    fn test_fuzzy_highlight_empty_command() {
        use super::highlight_command_with_indices;
        let spans = highlight_command_with_indices("", &[0, 1, 2], 100);
        assert!(spans.is_empty());
    }

    #[test]
    fn test_fuzzy_highlight_match_at_start() {
        use super::highlight_command_with_indices;
        let spans = highlight_command_with_indices("foo bar", &[0, 1, 2], 100);
        assert_eq!(spans, vec![("foo".to_string(), true), (" bar".to_string(), false),]);
    }

    #[test]
    fn test_fuzzy_highlight_match_at_end() {
        use super::highlight_command_with_indices;
        let spans = highlight_command_with_indices("foo bar", &[4, 5, 6], 100);
        assert_eq!(spans, vec![("foo ".to_string(), false), ("bar".to_string(), true),]);
    }
}