sql-cli 1.71.0

SQL query tool for CSV/JSON with both interactive TUI and non-interactive CLI modes - perfect for exploration and automation
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
//! Action handlers using visitor pattern
//!
//! This module implements a visitor pattern for handling different groups of actions,
//! allowing us to break down the massive `try_handle_action` function into manageable chunks.

use crate::buffer::AppMode;
use crate::ui::input::actions::{Action, ActionContext, ActionResult, NavigateAction, YankTarget};
use anyhow::Result;

/// Trait for handling groups of related actions
pub trait ActionHandler {
    /// Handle an action if this handler is responsible for it
    fn handle_action(
        &self,
        action: &Action,
        context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>>;

    /// Get the name of this handler (for debugging/logging)
    fn name(&self) -> &'static str;
}

/// Context interface for action handlers to interact with the TUI
/// This abstracts the TUI methods that action handlers need
pub trait ActionHandlerContext {
    // Navigation methods
    fn previous_row(&mut self);
    fn next_row(&mut self);
    fn move_column_left(&mut self);
    fn move_column_right(&mut self);
    fn page_up(&mut self);
    fn page_down(&mut self);
    fn goto_first_row(&mut self);
    fn goto_last_row(&mut self);
    fn goto_first_column(&mut self);
    fn goto_last_column(&mut self);
    fn goto_row(&mut self, row: usize);
    fn goto_column(&mut self, col: usize);

    // Mode and UI state
    fn set_mode(&mut self, mode: AppMode);
    fn get_mode(&self) -> AppMode;
    fn set_status_message(&mut self, message: String);

    // Column operations
    fn toggle_column_pin(&mut self);
    fn hide_current_column(&mut self);
    fn unhide_all_columns(&mut self);
    fn clear_all_pinned_columns(&mut self);

    // Export operations
    fn export_to_csv(&mut self);
    fn export_to_json(&mut self);

    // Yank operations
    fn yank_cell(&mut self);
    fn yank_row(&mut self);
    fn yank_column(&mut self);
    fn yank_all(&mut self);
    fn yank_query(&mut self);

    // Toggle operations
    fn toggle_selection_mode(&mut self);
    fn toggle_row_numbers(&mut self);
    fn toggle_compact_mode(&mut self);
    fn toggle_case_insensitive(&mut self);
    fn toggle_key_indicator(&mut self);

    // Clear operations
    fn clear_filter(&mut self);
    fn clear_line(&mut self);

    // Mode operations
    fn start_search(&mut self);
    fn start_column_search(&mut self);
    fn start_filter(&mut self);
    fn start_fuzzy_filter(&mut self);
    fn exit_current_mode(&mut self);
    fn toggle_debug_mode(&mut self);

    // Column arrangement operations
    fn move_current_column_left(&mut self);
    fn move_current_column_right(&mut self);

    // Search navigation
    fn next_search_match(&mut self);
    fn previous_search_match(&mut self);

    // Statistics and display
    fn show_column_statistics(&mut self);
    fn cycle_column_packing(&mut self);

    // Viewport navigation
    fn navigate_to_viewport_top(&mut self);
    fn navigate_to_viewport_middle(&mut self);
    fn navigate_to_viewport_bottom(&mut self);

    // Input and text editing
    fn move_input_cursor_left(&mut self);
    fn move_input_cursor_right(&mut self);
    fn move_input_cursor_home(&mut self);
    fn move_input_cursor_end(&mut self);
    fn backspace(&mut self);
    fn delete(&mut self);
    fn undo(&mut self);
    fn redo(&mut self);

    // Jump-to-row operations
    fn start_jump_to_row(&mut self);
    fn clear_jump_to_row_input(&mut self);

    // Debug and development
    fn show_debug_info(&mut self);
    fn show_pretty_query(&mut self);
    fn show_help(&mut self);

    // Text editing
    fn kill_line(&mut self);
    fn kill_line_backward(&mut self);
    fn delete_word_backward(&mut self);
    fn delete_word_forward(&mut self);
    fn expand_asterisk(&mut self);
    fn expand_asterisk_visible(&mut self);

    // History navigation
    fn previous_history_command(&mut self);
    fn next_history_command(&mut self);

    // Viewport lock operations
    fn toggle_cursor_lock(&mut self);
    fn toggle_viewport_lock(&mut self);
}

/// Handler for navigation actions (Up, Down, Left, Right, `PageUp`, etc.)
pub struct NavigationActionHandler;

impl ActionHandler for NavigationActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::Navigate(nav_action) => match nav_action {
                NavigateAction::Up(count) => {
                    for _ in 0..*count {
                        tui.previous_row();
                    }
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::Down(count) => {
                    for _ in 0..*count {
                        tui.next_row();
                    }
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::Left(count) => {
                    for _ in 0..*count {
                        tui.move_column_left();
                    }
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::Right(count) => {
                    for _ in 0..*count {
                        tui.move_column_right();
                    }
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::PageUp => {
                    tui.page_up();
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::PageDown => {
                    tui.page_down();
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::Home => {
                    tui.goto_first_row();
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::End => {
                    tui.goto_last_row();
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::FirstColumn => {
                    tui.goto_first_column();
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::LastColumn => {
                    tui.goto_last_column();
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::JumpToRow(row) => {
                    tui.goto_row(*row);
                    Some(Ok(ActionResult::Handled))
                }
                NavigateAction::JumpToColumn(col) => {
                    tui.goto_column(*col);
                    Some(Ok(ActionResult::Handled))
                }
            },
            Action::NextColumn => {
                tui.move_column_right();
                Some(Ok(ActionResult::Handled))
            }
            Action::PreviousColumn => {
                tui.move_column_left();
                Some(Ok(ActionResult::Handled))
            }
            _ => None, // Not handled by this handler
        }
    }

    fn name(&self) -> &'static str {
        "Navigation"
    }
}

/// Handler for column operations (pin, hide, sort, etc.)
pub struct ColumnActionHandler;

impl ActionHandler for ColumnActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ToggleColumnPin => {
                tui.toggle_column_pin();
                Some(Ok(ActionResult::Handled))
            }
            Action::HideColumn => {
                tui.hide_current_column();
                Some(Ok(ActionResult::Handled))
            }
            Action::UnhideAllColumns => {
                tui.unhide_all_columns();
                Some(Ok(ActionResult::Handled))
            }
            Action::ClearAllPins => {
                tui.clear_all_pinned_columns();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Column"
    }
}

/// Handler for export operations (CSV, JSON)
pub struct ExportActionHandler;

impl ActionHandler for ExportActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ExportToCsv => {
                tui.export_to_csv();
                Some(Ok(ActionResult::Handled))
            }
            Action::ExportToJson => {
                tui.export_to_json();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Export"
    }
}

/// Handler for yank operations (cell, row, column, etc.)
pub struct YankActionHandler;

impl ActionHandler for YankActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::Yank(target) => {
                match target {
                    YankTarget::Cell => tui.yank_cell(),
                    YankTarget::Row => tui.yank_row(),
                    YankTarget::Column => tui.yank_column(),
                    YankTarget::All => tui.yank_all(),
                    YankTarget::Query => tui.yank_query(),
                }
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Yank"
    }
}

/// Handler for UI mode and display operations
pub struct UIActionHandler;

impl ActionHandler for UIActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ShowHelp => {
                tui.set_mode(AppMode::Help);
                tui.set_status_message("Help mode - Press 'q' or Escape to return".to_string());
                Some(Ok(ActionResult::Handled))
            }
            // ShowDebugInfo needs to stay in the legacy switch for now
            // because it calls toggle_debug_mode() which generates debug data
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "UI"
    }
}

/// Handler for toggle operations (selection mode, row numbers, etc.)
pub struct ToggleActionHandler;

impl ActionHandler for ToggleActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ToggleSelectionMode => {
                tui.toggle_selection_mode();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleRowNumbers => {
                tui.toggle_row_numbers();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleCompactMode => {
                tui.toggle_compact_mode();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleCaseInsensitive => {
                tui.toggle_case_insensitive();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleKeyIndicator => {
                tui.toggle_key_indicator();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Toggle"
    }
}

/// Handler for clear/reset operations
pub struct ClearActionHandler;

impl ActionHandler for ClearActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ClearFilter => {
                tui.clear_filter();
                Some(Ok(ActionResult::Handled))
            }
            Action::ClearLine => {
                // Only handle in Command mode
                if context.mode == AppMode::Command {
                    tui.clear_line();
                    Some(Ok(ActionResult::Handled))
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Clear"
    }
}

/// Handler for exit/quit actions
pub struct ExitActionHandler;

impl ActionHandler for ExitActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        _tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::Quit | Action::ForceQuit => Some(Ok(ActionResult::Exit)),
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Exit"
    }
}

/// Handler for mode transition actions (search modes, debug, etc.)
pub struct ModeActionHandler;

impl ActionHandler for ModeActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::StartSearch => {
                tui.start_search();
                Some(Ok(ActionResult::Handled))
            }
            Action::StartColumnSearch => {
                tui.start_column_search();
                Some(Ok(ActionResult::Handled))
            }
            Action::StartFilter => {
                tui.start_filter();
                Some(Ok(ActionResult::Handled))
            }
            Action::StartFuzzyFilter => {
                tui.start_fuzzy_filter();
                Some(Ok(ActionResult::Handled))
            }
            Action::ExitCurrentMode => {
                tui.exit_current_mode();
                Some(Ok(ActionResult::Handled))
            }
            Action::ShowDebugInfo => {
                tui.toggle_debug_mode();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Mode"
    }
}

/// Handler for viewport navigation actions (H, M, L vim commands)
pub struct ViewportNavigationHandler;

impl ActionHandler for ViewportNavigationHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::NavigateToViewportTop => {
                tui.navigate_to_viewport_top();
                Some(Ok(ActionResult::Handled))
            }
            Action::NavigateToViewportMiddle => {
                tui.navigate_to_viewport_middle();
                Some(Ok(ActionResult::Handled))
            }
            Action::NavigateToViewportBottom => {
                tui.navigate_to_viewport_bottom();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "ViewportNavigation"
    }
}

/// Handler for column arrangement actions (move left/right)
pub struct ColumnArrangementActionHandler;

impl ActionHandler for ColumnArrangementActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::MoveColumnLeft => {
                tui.move_current_column_left();
                Some(Ok(ActionResult::Handled))
            }
            Action::MoveColumnRight => {
                tui.move_current_column_right();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "ColumnArrangement"
    }
}

/// Handler for search navigation actions
pub struct SearchNavigationActionHandler;

impl ActionHandler for SearchNavigationActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::NextSearchMatch => {
                tui.next_search_match();
                Some(Ok(ActionResult::Handled))
            }
            Action::PreviousSearchMatch => {
                // When Shift+N is pressed and there's no active search,
                // toggle row numbers instead of navigating search
                if context.has_search {
                    tui.previous_search_match();
                } else {
                    tui.toggle_row_numbers();
                }
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "SearchNavigation"
    }
}

/// Handler for statistics and display actions
pub struct StatisticsActionHandler;

impl ActionHandler for StatisticsActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ShowColumnStatistics => {
                tui.show_column_statistics();
                Some(Ok(ActionResult::Handled))
            }
            Action::CycleColumnPacking => {
                tui.cycle_column_packing();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "Statistics"
    }
}

/// Handler for cursor movement actions in Command mode
pub struct InputCursorActionHandler;

impl ActionHandler for InputCursorActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        // Only handle in Command mode
        if context.mode != AppMode::Command {
            return None;
        }

        match action {
            Action::MoveCursorLeft => {
                tui.move_input_cursor_left();
                Some(Ok(ActionResult::Handled))
            }
            Action::MoveCursorRight => {
                tui.move_input_cursor_right();
                Some(Ok(ActionResult::Handled))
            }
            Action::MoveCursorHome => {
                tui.move_input_cursor_home();
                Some(Ok(ActionResult::Handled))
            }
            Action::MoveCursorEnd => {
                tui.move_input_cursor_end();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "InputCursor"
    }
}

/// Handler for debug and viewport control operations
pub struct DebugViewportActionHandler;

impl ActionHandler for DebugViewportActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ShowDebugInfo => {
                tui.toggle_debug_mode();
                Some(Ok(ActionResult::Handled))
            }
            Action::StartJumpToRow => {
                tui.start_jump_to_row();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleCursorLock => {
                tui.toggle_cursor_lock();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleViewportLock => {
                tui.toggle_viewport_lock();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "DebugViewport"
    }
}

/// Handler for function key actions (F1-F12)
pub struct FunctionKeyActionHandler;

impl ActionHandler for FunctionKeyActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        _context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        match action {
            Action::ShowHelp => {
                tui.show_help();
                Some(Ok(ActionResult::Handled))
            }
            Action::ShowPrettyQuery => {
                tui.show_pretty_query();
                Some(Ok(ActionResult::Handled))
            }
            Action::ShowDebugInfo => {
                tui.toggle_debug_mode();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleRowNumbers => {
                tui.toggle_row_numbers();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleCompactMode => {
                tui.toggle_compact_mode();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleCaseInsensitive => {
                tui.toggle_case_insensitive();
                Some(Ok(ActionResult::Handled))
            }
            Action::ToggleKeyIndicator => {
                tui.toggle_key_indicator();
                Some(Ok(ActionResult::Handled))
            }
            Action::KillLine => {
                tui.kill_line();
                Some(Ok(ActionResult::Handled))
            }
            Action::KillLineBackward => {
                tui.kill_line_backward();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "FunctionKey"
    }
}

/// Handler for text editing actions in Command mode
pub struct TextEditActionHandler;

impl ActionHandler for TextEditActionHandler {
    fn handle_action(
        &self,
        action: &Action,
        context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Option<Result<ActionResult>> {
        // Only handle in Command mode
        if context.mode != AppMode::Command {
            return None;
        }

        match action {
            Action::Backspace => {
                tui.backspace();
                Some(Ok(ActionResult::Handled))
            }
            Action::Delete => {
                tui.delete();
                Some(Ok(ActionResult::Handled))
            }
            Action::Undo => {
                tui.undo();
                Some(Ok(ActionResult::Handled))
            }
            Action::Redo => {
                tui.redo();
                Some(Ok(ActionResult::Handled))
            }
            Action::DeleteWordBackward => {
                tui.delete_word_backward();
                Some(Ok(ActionResult::Handled))
            }
            Action::DeleteWordForward => {
                tui.delete_word_forward();
                Some(Ok(ActionResult::Handled))
            }
            Action::KillLine => {
                tui.kill_line();
                Some(Ok(ActionResult::Handled))
            }
            Action::KillLineBackward => {
                tui.kill_line_backward();
                Some(Ok(ActionResult::Handled))
            }
            Action::ExpandAsterisk => {
                tui.expand_asterisk();
                Some(Ok(ActionResult::Handled))
            }
            Action::ExpandAsteriskVisible => {
                tui.expand_asterisk_visible();
                Some(Ok(ActionResult::Handled))
            }
            Action::PreviousHistoryCommand => {
                tui.previous_history_command();
                Some(Ok(ActionResult::Handled))
            }
            Action::NextHistoryCommand => {
                tui.next_history_command();
                Some(Ok(ActionResult::Handled))
            }
            _ => None,
        }
    }

    fn name(&self) -> &'static str {
        "TextEdit"
    }
}

/// Main action dispatcher using visitor pattern
pub struct ActionDispatcher {
    handlers: Vec<Box<dyn ActionHandler>>,
}

impl ActionDispatcher {
    #[must_use]
    pub fn new() -> Self {
        let handlers: Vec<Box<dyn ActionHandler>> = vec![
            Box::new(NavigationActionHandler),
            Box::new(ColumnActionHandler),
            Box::new(ExportActionHandler),
            Box::new(YankActionHandler),
            Box::new(UIActionHandler),
            Box::new(ToggleActionHandler),
            Box::new(ClearActionHandler),
            Box::new(ExitActionHandler),
            Box::new(FunctionKeyActionHandler),
            Box::new(ModeActionHandler),
            Box::new(ColumnArrangementActionHandler),
            Box::new(SearchNavigationActionHandler),
            Box::new(StatisticsActionHandler),
            Box::new(InputCursorActionHandler),
            Box::new(TextEditActionHandler),
            Box::new(ViewportNavigationHandler),
            Box::new(DebugViewportActionHandler),
        ];

        Self { handlers }
    }

    /// Dispatch an action to the appropriate handler
    pub fn dispatch(
        &self,
        action: &Action,
        context: &ActionContext,
        tui: &mut dyn ActionHandlerContext,
    ) -> Result<ActionResult> {
        for handler in &self.handlers {
            if let Some(result) = handler.handle_action(action, context, tui) {
                return result;
            }
        }

        // No handler found for this action
        Ok(ActionResult::NotHandled)
    }
}

impl Default for ActionDispatcher {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::input::actions::{Action, NavigateAction};

    // Mock implementation for testing
    struct MockTui {
        pub last_action: String,
        pub mode: AppMode,
        pub status_message: String,
    }

    impl MockTui {
        fn new() -> Self {
            Self {
                last_action: String::new(),
                mode: AppMode::Results,
                status_message: String::new(),
            }
        }
    }

    impl ActionHandlerContext for MockTui {
        fn previous_row(&mut self) {
            self.last_action = "previous_row".to_string();
        }
        fn next_row(&mut self) {
            self.last_action = "next_row".to_string();
        }
        fn move_column_left(&mut self) {
            self.last_action = "move_column_left".to_string();
        }
        fn move_column_right(&mut self) {
            self.last_action = "move_column_right".to_string();
        }
        fn page_up(&mut self) {
            self.last_action = "page_up".to_string();
        }
        fn page_down(&mut self) {
            self.last_action = "page_down".to_string();
        }
        fn goto_first_row(&mut self) {
            self.last_action = "goto_first_row".to_string();
        }
        fn goto_last_row(&mut self) {
            self.last_action = "goto_last_row".to_string();
        }
        fn goto_first_column(&mut self) {
            self.last_action = "goto_first_column".to_string();
        }
        fn goto_last_column(&mut self) {
            self.last_action = "goto_last_column".to_string();
        }
        fn goto_row(&mut self, row: usize) {
            self.last_action = format!("goto_row_{row}");
        }
        fn goto_column(&mut self, col: usize) {
            self.last_action = format!("goto_column_{col}");
        }

        fn set_mode(&mut self, mode: AppMode) {
            self.mode = mode;
        }
        fn get_mode(&self) -> AppMode {
            self.mode.clone()
        }
        fn set_status_message(&mut self, message: String) {
            self.status_message = message;
        }

        fn toggle_column_pin(&mut self) {
            self.last_action = "toggle_column_pin".to_string();
        }
        fn hide_current_column(&mut self) {
            self.last_action = "hide_current_column".to_string();
        }
        fn unhide_all_columns(&mut self) {
            self.last_action = "unhide_all_columns".to_string();
        }
        fn clear_all_pinned_columns(&mut self) {
            self.last_action = "clear_all_pinned_columns".to_string();
        }

        fn export_to_csv(&mut self) {
            self.last_action = "export_to_csv".to_string();
        }
        fn export_to_json(&mut self) {
            self.last_action = "export_to_json".to_string();
        }

        fn yank_cell(&mut self) {
            self.last_action = "yank_cell".to_string();
        }
        fn yank_row(&mut self) {
            self.last_action = "yank_row".to_string();
        }
        fn yank_column(&mut self) {
            self.last_action = "yank_column".to_string();
        }
        fn yank_all(&mut self) {
            self.last_action = "yank_all".to_string();
        }
        fn yank_query(&mut self) {
            self.last_action = "yank_query".to_string();
        }

        // Toggle operations
        fn toggle_selection_mode(&mut self) {
            self.last_action = "toggle_selection_mode".to_string();
        }
        fn toggle_row_numbers(&mut self) {
            self.last_action = "toggle_row_numbers".to_string();
        }
        fn toggle_compact_mode(&mut self) {
            self.last_action = "toggle_compact_mode".to_string();
        }
        fn toggle_case_insensitive(&mut self) {
            self.last_action = "toggle_case_insensitive".to_string();
        }
        fn toggle_key_indicator(&mut self) {
            self.last_action = "toggle_key_indicator".to_string();
        }

        // Clear operations
        fn clear_filter(&mut self) {
            self.last_action = "clear_filter".to_string();
        }
        fn clear_line(&mut self) {
            self.last_action = "clear_line".to_string();
        }

        // Mode operations
        fn start_search(&mut self) {
            self.last_action = "start_search".to_string();
        }
        fn start_column_search(&mut self) {
            self.last_action = "start_column_search".to_string();
        }
        fn start_filter(&mut self) {
            self.last_action = "start_filter".to_string();
        }
        fn start_fuzzy_filter(&mut self) {
            self.last_action = "start_fuzzy_filter".to_string();
        }
        fn exit_current_mode(&mut self) {
            self.last_action = "exit_current_mode".to_string();
        }
        fn toggle_debug_mode(&mut self) {
            self.last_action = "toggle_debug_mode".to_string();
        }

        // Column arrangement operations
        fn move_current_column_left(&mut self) {
            self.last_action = "move_current_column_left".to_string();
        }
        fn move_current_column_right(&mut self) {
            self.last_action = "move_current_column_right".to_string();
        }

        // Search navigation
        fn next_search_match(&mut self) {
            self.last_action = "next_search_match".to_string();
        }
        fn previous_search_match(&mut self) {
            self.last_action = "previous_search_match".to_string();
        }

        // Statistics and display
        fn show_column_statistics(&mut self) {
            self.last_action = "show_column_statistics".to_string();
        }
        fn cycle_column_packing(&mut self) {
            self.last_action = "cycle_column_packing".to_string();
        }

        fn navigate_to_viewport_top(&mut self) {
            self.last_action = "navigate_to_viewport_top".to_string();
        }

        fn navigate_to_viewport_middle(&mut self) {
            self.last_action = "navigate_to_viewport_middle".to_string();
        }

        fn navigate_to_viewport_bottom(&mut self) {
            self.last_action = "navigate_to_viewport_bottom".to_string();
        }

        // Jump-to-row operations
        fn start_jump_to_row(&mut self) {
            self.last_action = "start_jump_to_row".to_string();
        }
        fn clear_jump_to_row_input(&mut self) {
            self.last_action = "clear_jump_to_row_input".to_string();
        }

        // Viewport lock operations
        fn toggle_cursor_lock(&mut self) {
            self.last_action = "toggle_cursor_lock".to_string();
        }
        fn toggle_viewport_lock(&mut self) {
            self.last_action = "toggle_viewport_lock".to_string();
        }

        // Input and text editing
        fn move_input_cursor_left(&mut self) {
            self.last_action = "move_input_cursor_left".to_string();
        }
        fn move_input_cursor_right(&mut self) {
            self.last_action = "move_input_cursor_right".to_string();
        }
        fn move_input_cursor_home(&mut self) {
            self.last_action = "move_input_cursor_home".to_string();
        }
        fn move_input_cursor_end(&mut self) {
            self.last_action = "move_input_cursor_end".to_string();
        }
        fn backspace(&mut self) {
            self.last_action = "backspace".to_string();
        }
        fn delete(&mut self) {
            self.last_action = "delete".to_string();
        }
        fn undo(&mut self) {
            self.last_action = "undo".to_string();
        }
        fn redo(&mut self) {
            self.last_action = "redo".to_string();
        }

        // Debug and development methods
        fn show_debug_info(&mut self) {
            self.last_action = "show_debug_info".to_string();
        }
        fn show_pretty_query(&mut self) {
            self.last_action = "show_pretty_query".to_string();
        }
        fn show_help(&mut self) {
            self.last_action = "show_help".to_string();
        }

        // Text editing operations
        fn kill_line(&mut self) {
            self.last_action = "kill_line".to_string();
        }
        fn kill_line_backward(&mut self) {
            self.last_action = "kill_line_backward".to_string();
        }
        fn delete_word_backward(&mut self) {
            self.last_action = "delete_word_backward".to_string();
        }
        fn delete_word_forward(&mut self) {
            self.last_action = "delete_word_forward".to_string();
        }
        fn expand_asterisk(&mut self) {
            self.last_action = "expand_asterisk".to_string();
        }
        fn expand_asterisk_visible(&mut self) {
            self.last_action = "expand_asterisk_visible".to_string();
        }

        // History navigation
        fn previous_history_command(&mut self) {
            self.last_action = "previous_history_command".to_string();
        }
        fn next_history_command(&mut self) {
            self.last_action = "next_history_command".to_string();
        }
    }

    #[test]
    fn test_debug_viewport_handler() {
        let mut tui = MockTui::new();
        let handler = DebugViewportActionHandler;
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Cell,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Test ShowDebugInfo
        let result = handler
            .handle_action(&Action::ShowDebugInfo, &context, &mut tui)
            .unwrap();
        assert!(matches!(result, Ok(ActionResult::Handled)));
        assert_eq!(tui.last_action, "toggle_debug_mode");

        // Test StartJumpToRow
        let result = handler
            .handle_action(&Action::StartJumpToRow, &context, &mut tui)
            .unwrap();
        assert!(matches!(result, Ok(ActionResult::Handled)));
        assert_eq!(tui.last_action, "start_jump_to_row");

        // Test ToggleCursorLock
        let result = handler
            .handle_action(&Action::ToggleCursorLock, &context, &mut tui)
            .unwrap();
        assert!(matches!(result, Ok(ActionResult::Handled)));
        assert_eq!(tui.last_action, "toggle_cursor_lock");

        // Test ToggleViewportLock
        let result = handler
            .handle_action(&Action::ToggleViewportLock, &context, &mut tui)
            .unwrap();
        assert!(matches!(result, Ok(ActionResult::Handled)));
        assert_eq!(tui.last_action, "toggle_viewport_lock");

        // Test unhandled action
        let result = handler.handle_action(&Action::Quit, &context, &mut tui);
        assert!(result.is_none());
    }

    #[test]
    fn test_navigation_handler() {
        let handler = NavigationActionHandler;
        let mut mock_tui = MockTui::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        let action = Action::Navigate(NavigateAction::Up(1));
        let result = handler.handle_action(&action, &context, &mut mock_tui);

        assert!(result.is_some());
        assert_eq!(mock_tui.last_action, "previous_row");

        match result.unwrap() {
            Ok(ActionResult::Handled) => {}
            _ => panic!("Expected Handled result"),
        }
    }

    #[test]
    fn test_action_dispatcher() {
        let dispatcher = ActionDispatcher::new();
        let mut mock_tui = MockTui::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        // Test navigation action
        let action = Action::Navigate(NavigateAction::Down(2));
        let result = dispatcher
            .dispatch(&action, &context, &mut mock_tui)
            .unwrap();

        assert_eq!(result, ActionResult::Handled);
        assert_eq!(mock_tui.last_action, "next_row"); // Called twice for count=2

        // Test export action
        let action = Action::ExportToCsv;
        let result = dispatcher
            .dispatch(&action, &context, &mut mock_tui)
            .unwrap();

        assert_eq!(result, ActionResult::Handled);
        assert_eq!(mock_tui.last_action, "export_to_csv");
    }

    #[test]
    fn test_toggle_handler() {
        let handler = ToggleActionHandler;
        let mut mock_tui = MockTui::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        // Test toggle selection mode
        let action = Action::ToggleSelectionMode;
        let result = handler
            .handle_action(&action, &context, &mut mock_tui)
            .unwrap()
            .unwrap();
        assert_eq!(result, ActionResult::Handled);
        assert_eq!(mock_tui.last_action, "toggle_selection_mode");

        // Test toggle row numbers
        let action = Action::ToggleRowNumbers;
        let result = handler
            .handle_action(&action, &context, &mut mock_tui)
            .unwrap()
            .unwrap();
        assert_eq!(result, ActionResult::Handled);
        assert_eq!(mock_tui.last_action, "toggle_row_numbers");
    }

    #[test]
    fn test_clear_handler() {
        let handler = ClearActionHandler;
        let mut mock_tui = MockTui::new();

        // Test clear filter
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: true,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        let action = Action::ClearFilter;
        let result = handler
            .handle_action(&action, &context, &mut mock_tui)
            .unwrap()
            .unwrap();
        assert_eq!(result, ActionResult::Handled);
        assert_eq!(mock_tui.last_action, "clear_filter");

        // Test clear line in Command mode
        let context = ActionContext {
            mode: AppMode::Command,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        let action = Action::ClearLine;
        let result = handler
            .handle_action(&action, &context, &mut mock_tui)
            .unwrap()
            .unwrap();
        assert_eq!(result, ActionResult::Handled);
        assert_eq!(mock_tui.last_action, "clear_line");

        // Test clear line not handled in Results mode
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        let action = Action::ClearLine;
        let result = handler.handle_action(&action, &context, &mut mock_tui);
        assert!(result.is_none());
    }

    #[test]
    fn test_exit_handler() {
        let handler = ExitActionHandler;
        let mut mock_tui = MockTui::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: crate::app_state_container::SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 10,
            column_count: 5,
            current_row: 0,
            current_column: 0,
        };

        // Test quit
        let action = Action::Quit;
        let result = handler
            .handle_action(&action, &context, &mut mock_tui)
            .unwrap()
            .unwrap();
        assert_eq!(result, ActionResult::Exit);

        // Test force quit
        let action = Action::ForceQuit;
        let result = handler
            .handle_action(&action, &context, &mut mock_tui)
            .unwrap()
            .unwrap();
        assert_eq!(result, ActionResult::Exit);
    }
}