sql-cli 1.68.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
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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
use crate::api_client::QueryResponse; // V50: Still needed for conversion from API responses
use crate::csv_datasource::CsvApiClient; // Kept for API compatibility in from_csv/from_json
use crate::cursor_operations::CursorOperations;
use crate::data::data_view::DataView;
use crate::data::datatable::DataTable;
use crate::hybrid_parser::HybridParser;
use crate::input_manager::{create_from_input, create_single_line, InputManager};
use anyhow::Result;
use crossterm::event::KeyEvent;
use fuzzy_matcher::skim::SkimMatcherV2;
use ratatui::style::Color;
use ratatui::widgets::TableState;
use regex::Regex;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use tracing::debug;
use tui_input::Input;

// Re-define the types we need (these should eventually be moved to a common module)
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum AppMode {
    Command,
    Results,
    Search,
    Filter,
    FuzzyFilter,
    ColumnSearch,
    Help,
    History,
    Debug,
    PrettyQuery,
    JumpToRow,
    ColumnStats,
}

#[derive(Clone, PartialEq, Debug)]
pub enum EditMode {
    SingleLine,
    MultiLine,
}

#[derive(Clone, PartialEq, Copy, Debug)]
pub enum SortOrder {
    Ascending,
    Descending,
    None,
}

#[derive(Clone)]
pub struct SortState {
    pub column: Option<usize>,
    pub order: SortOrder,
}

#[derive(Clone, Debug, Default)]
pub struct FilterState {
    pub pattern: String,
    pub regex: Option<Regex>,
    pub active: bool,
}

#[derive(Default)]
pub struct FuzzyFilterState {
    pub pattern: String,
    pub active: bool,
    pub matcher: SkimMatcherV2,
    pub filtered_indices: Vec<usize>,
}

impl std::fmt::Debug for FuzzyFilterState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FuzzyFilterState")
            .field("pattern", &self.pattern)
            .field("active", &self.active)
            .field("matcher", &"SkimMatcherV2")
            .field("filtered_indices", &self.filtered_indices)
            .finish()
    }
}

impl Clone for FuzzyFilterState {
    fn clone(&self) -> Self {
        Self {
            pattern: self.pattern.clone(),
            active: self.active,
            matcher: SkimMatcherV2::default(), // Create new matcher
            filtered_indices: self.filtered_indices.clone(),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct SearchState {
    pub pattern: String,
    pub current_match: Option<(usize, usize)>,
    pub matches: Vec<(usize, usize)>,
    pub match_index: usize,
}

// ColumnSearchState: MIGRATED to AppStateContainer

#[derive(Clone, Debug, PartialEq)]
pub enum SelectionMode {
    Row,
    Cell,
    Column,
}

/// `ViewState` consolidates all view-related state for a buffer
/// This is the single source of truth for navigation, selection, and viewport state
#[derive(Clone, Debug)]
pub struct ViewState {
    // Position
    pub crosshair_row: usize,
    pub crosshair_col: usize,
    pub scroll_offset: (usize, usize),

    // Selection
    pub selection_mode: SelectionMode,
    pub selected_cells: Vec<(usize, usize)>,
    pub selection_anchor: Option<(usize, usize)>,

    // Viewport config
    pub viewport_lock: bool,
    pub cursor_lock: bool,

    // Navigation history
    pub navigation_history: Vec<(usize, usize)>,
    pub history_index: usize,

    // Viewport dimensions (cached from last render)
    pub viewport_rows: usize,
    pub viewport_columns: usize,
    pub total_rows: usize,
    pub total_columns: usize,
}

impl Default for ViewState {
    fn default() -> Self {
        Self {
            crosshair_row: 0,
            crosshair_col: 0,
            scroll_offset: (0, 0),
            selection_mode: SelectionMode::Row,
            selected_cells: Vec::new(),
            selection_anchor: None,
            viewport_lock: false,
            cursor_lock: false,
            navigation_history: Vec::new(),
            history_index: 0,
            viewport_rows: 0,
            viewport_columns: 0,
            total_rows: 0,
            total_columns: 0,
        }
    }
}

#[derive(Clone, Debug)]
pub enum ColumnType {
    String,
    Numeric,
    Mixed,
}

#[derive(Clone)]
pub struct ColumnStatistics {
    pub column_name: String,
    pub column_type: ColumnType,
    // For all columns
    pub total_count: usize,
    pub null_count: usize,
    pub unique_count: usize,
    // For categorical/string columns
    pub frequency_map: Option<BTreeMap<String, usize>>,
    // For numeric columns
    pub min: Option<f64>,
    pub max: Option<f64>,
    pub sum: Option<f64>,
    pub mean: Option<f64>,
    pub median: Option<f64>,
}

// ColumnSearchState Default impl: MIGRATED to AppStateContainer

// pub type ColumnStatistics = std::collections::BTreeMap<String, String>; // Replaced with struct

/// `BufferAPI` trait - defines the interface for interacting with buffer state
/// This abstraction allows the TUI to work with buffer state without knowing
/// the implementation details, enabling gradual migration and testing
pub trait BufferAPI: Send + Sync {
    // --- Identity ---
    fn get_id(&self) -> usize;
    // --- Query ---
    fn get_query(&self) -> String;
    fn set_query(&mut self, query: String);
    // V50: Removed get_results/set_results - use DataTable methods instead
    fn get_last_query(&self) -> String;
    fn set_last_query(&mut self, query: String);

    // --- V50: DataTable is primary storage ---
    fn get_datatable(&self) -> Option<&DataTable>;
    fn get_datatable_mut(&mut self) -> Option<&mut DataTable>;
    fn has_datatable(&self) -> bool;
    fn set_datatable(&mut self, datatable: Option<Arc<DataTable>>);
    fn get_original_source(&self) -> Option<&DataTable>;
    /// V50: Helper to convert `QueryResponse` to `DataTable` and store it
    fn set_results_as_datatable(&mut self, response: Option<QueryResponse>) -> Result<(), String>;

    // --- V51: DataView support (direct query results) ---
    fn get_dataview(&self) -> Option<&DataView>;
    fn get_dataview_mut(&mut self) -> Option<&mut DataView>;
    fn set_dataview(&mut self, dataview: Option<DataView>);
    fn has_dataview(&self) -> bool;

    // --- Mode and Status ---
    fn get_mode(&self) -> AppMode;
    fn set_mode(&mut self, mode: AppMode);
    fn get_edit_mode(&self) -> EditMode;
    fn set_edit_mode(&mut self, mode: EditMode);
    fn get_status_message(&self) -> String;
    fn set_status_message(&mut self, message: String);

    // --- Table Navigation ---
    fn get_selected_row(&self) -> Option<usize>;
    fn set_selected_row(&mut self, row: Option<usize>);
    fn get_current_column(&self) -> usize;
    fn set_current_column(&mut self, col: usize);
    fn get_scroll_offset(&self) -> (usize, usize);
    fn set_scroll_offset(&mut self, offset: (usize, usize));
    fn get_last_results_row(&self) -> Option<usize>;
    fn set_last_results_row(&mut self, row: Option<usize>);
    fn get_last_scroll_offset(&self) -> (usize, usize);
    fn set_last_scroll_offset(&mut self, offset: (usize, usize));

    // --- Filtering ---
    fn get_filter_pattern(&self) -> String;
    fn set_filter_pattern(&mut self, pattern: String);
    fn is_filter_active(&self) -> bool;
    fn set_filter_active(&mut self, active: bool);
    // REMOVED: get_filtered_data/set_filtered_data - DataView handles filtering

    // --- Fuzzy Filter ---
    fn get_fuzzy_filter_pattern(&self) -> String;
    fn set_fuzzy_filter_pattern(&mut self, pattern: String);
    fn is_fuzzy_filter_active(&self) -> bool;
    fn set_fuzzy_filter_active(&mut self, active: bool);
    fn get_fuzzy_filter_indices(&self) -> &Vec<usize>;
    fn set_fuzzy_filter_indices(&mut self, indices: Vec<usize>);
    fn clear_fuzzy_filter(&mut self);

    // --- Search ---
    fn get_search_pattern(&self) -> String;
    fn set_search_pattern(&mut self, pattern: String);
    fn get_search_matches(&self) -> Vec<(usize, usize)>;
    fn set_search_matches(&mut self, matches: Vec<(usize, usize)>);
    fn get_current_match(&self) -> Option<(usize, usize)>;
    fn set_current_match(&mut self, match_pos: Option<(usize, usize)>);
    fn get_search_match_index(&self) -> usize;
    fn set_search_match_index(&mut self, index: usize);
    fn clear_search_state(&mut self);

    // --- Column Search ---

    // --- Column Statistics ---
    fn get_column_stats(&self) -> Option<&ColumnStatistics>;
    fn set_column_stats(&mut self, stats: Option<ColumnStatistics>);

    // --- Sorting ---
    fn get_sort_column(&self) -> Option<usize>;
    fn set_sort_column(&mut self, column: Option<usize>);
    fn get_sort_order(&self) -> SortOrder;
    fn set_sort_order(&mut self, order: SortOrder);

    // --- Display Options ---
    fn is_compact_mode(&self) -> bool;
    fn set_compact_mode(&mut self, compact: bool);
    fn is_show_row_numbers(&self) -> bool;
    fn set_show_row_numbers(&mut self, show: bool);
    fn is_viewport_lock(&self) -> bool;
    fn set_viewport_lock(&mut self, locked: bool);
    fn get_viewport_lock_row(&self) -> Option<usize>;
    fn set_viewport_lock_row(&mut self, row: Option<usize>);
    // REMOVED: pinned_columns methods - DataView handles pinned columns
    // REMOVED: hidden_columns methods - DataView handles column visibility
    fn get_column_widths(&self) -> &Vec<u16>;
    fn set_column_widths(&mut self, widths: Vec<u16>);
    fn is_case_insensitive(&self) -> bool;
    fn set_case_insensitive(&mut self, case_insensitive: bool);

    // --- Buffer Metadata ---
    fn get_name(&self) -> String;
    fn set_name(&mut self, name: String);
    fn get_file_path(&self) -> Option<&PathBuf>;
    fn set_file_path(&mut self, path: Option<String>);
    fn is_modified(&self) -> bool;
    fn set_modified(&mut self, modified: bool);
    fn get_last_query_source(&self) -> Option<String>;
    fn set_last_query_source(&mut self, source: Option<String>);

    // --- CSV/Data Source ---
    // REMOVED: CSV/Cache methods - legacy data access patterns

    // --- Input State ---
    fn get_input_value(&self) -> String;
    fn set_input_value(&mut self, value: String);
    fn get_input_cursor(&self) -> usize;
    fn set_input_cursor(&mut self, pos: usize);

    // --- Advanced Operations ---
    fn apply_filter(&mut self) -> Result<()>;
    fn apply_sort(&mut self) -> Result<()>;
    fn search(&mut self) -> Result<()>;
    fn clear_filters(&mut self);
    fn get_row_count(&self) -> usize;
    fn get_column_count(&self) -> usize;
    fn get_column_names(&self) -> Vec<String>;

    // --- Edit State ---
    fn get_undo_stack(&self) -> &Vec<(String, usize)>;
    fn push_undo(&mut self, state: (String, usize));
    fn pop_undo(&mut self) -> Option<(String, usize)>;
    fn get_redo_stack(&self) -> &Vec<(String, usize)>;
    fn push_redo(&mut self, state: (String, usize));
    fn pop_redo(&mut self) -> Option<(String, usize)>;
    fn clear_redo(&mut self);
    fn get_kill_ring(&self) -> String;
    fn set_kill_ring(&mut self, text: String);
    fn is_kill_ring_empty(&self) -> bool;

    // High-level undo/redo operations
    fn perform_undo(&mut self) -> bool;
    fn perform_redo(&mut self) -> bool;
    fn save_state_for_undo(&mut self);

    // --- Viewport State ---
    fn get_last_visible_rows(&self) -> usize;
    fn set_last_visible_rows(&mut self, rows: usize);

    // --- Debug ---
    fn debug_dump(&self) -> String;

    // --- Input Management ---
    fn get_input_text(&self) -> String;
    fn set_input_text(&mut self, text: String);
    fn handle_input_key(&mut self, event: KeyEvent) -> bool;
    fn switch_input_mode(&mut self, multiline: bool);
    fn get_input_cursor_position(&self) -> usize;
    fn set_input_cursor_position(&mut self, position: usize);
    fn is_input_multiline(&self) -> bool;

    // --- History Navigation ---
    fn navigate_history_up(&mut self, history: &[String]) -> bool;
    fn navigate_history_down(&mut self, history: &[String]) -> bool;
    fn reset_history_navigation(&mut self);

    // --- Results Management ---
    fn clear_results(&mut self);
}

/// Represents a single buffer/tab with its own independent state
pub struct Buffer {
    /// Unique identifier for this buffer
    pub id: usize,

    /// File path if loaded from file
    pub file_path: Option<PathBuf>,

    /// Display name (filename or "untitled")
    pub name: String,

    /// Whether this buffer has unsaved changes
    pub modified: bool,

    // --- Data State ---
    pub datatable: Option<Arc<DataTable>>,
    /// Original unmodified `DataTable` (preserved for query operations)
    pub original_source: Option<Arc<DataTable>>,
    /// `DataView` for applying filters like hidden columns without modifying the `DataTable`
    pub dataview: Option<DataView>,

    // --- UI State ---
    pub mode: AppMode,
    pub edit_mode: EditMode,
    pub input: Input, // Legacy - kept for compatibility during migration
    pub input_manager: Box<dyn InputManager>, // New unified input management
    pub table_state: TableState,
    pub last_results_row: Option<usize>,
    pub last_scroll_offset: (usize, usize),

    // --- Query State ---
    pub last_query: String,
    pub status_message: String,

    // --- Filter/Search State ---
    pub sort_state: SortState,
    pub filter_state: FilterState,
    pub fuzzy_filter_state: FuzzyFilterState,
    pub search_state: SearchState,

    pub column_stats: Option<ColumnStatistics>,

    // --- View State (Consolidated) ---
    pub view_state: ViewState,

    // --- Display Options (not navigation-related) ---
    pub column_widths: Vec<u16>,
    pub compact_mode: bool,
    pub show_row_numbers: bool,
    pub case_insensitive: bool,

    // --- Misc State ---
    pub undo_stack: Vec<(String, usize)>,
    pub redo_stack: Vec<(String, usize)>,
    pub kill_ring: String,
    pub last_visible_rows: usize,
    pub last_query_source: Option<String>,

    // --- Syntax Highlighting ---
    pub highlighted_text_cache: Option<Vec<(String, Color)>>, // Cache of highlighted tokens
    pub last_highlighted_text: String, // Track what text was highlighted to detect changes

    // --- Input State Stack (for search/filter modes) ---
    pub saved_input_state: Option<(String, usize)>, // Save input when entering search/filter
}

// Implement BufferAPI for Buffer
impl BufferAPI for Buffer {
    // --- Identity ---
    fn get_id(&self) -> usize {
        self.id
    }

    // --- Query and Results ---
    fn get_query(&self) -> String {
        // Use InputManager if available, fallback to legacy input
        self.input_manager.get_text()
    }

    fn set_query(&mut self, query: String) {
        // Update both InputManager and legacy field for compatibility
        self.input_manager.set_text(query.clone());
        self.input = Input::new(query.clone()).with_cursor(query.len());
    }

    // V50: Removed get_results/set_results - use get_datatable/set_datatable instead

    fn get_last_query(&self) -> String {
        self.last_query.clone()
    }

    fn set_last_query(&mut self, query: String) {
        self.last_query = query;
    }

    // --- V50: DataTable is primary storage ---
    fn get_datatable(&self) -> Option<&DataTable> {
        self.datatable.as_ref().map(std::convert::AsRef::as_ref)
    }

    fn get_datatable_mut(&mut self) -> Option<&mut DataTable> {
        // Can't mutate through Arc - need to make a new copy if mutation is needed
        // For now, return None as we shouldn't be mutating the DataTable directly
        None
    }

    fn has_datatable(&self) -> bool {
        self.datatable.is_some()
    }

    fn get_original_source(&self) -> Option<&DataTable> {
        self.original_source
            .as_ref()
            .map(std::convert::AsRef::as_ref)
    }

    fn set_datatable(&mut self, datatable: Option<Arc<DataTable>>) {
        debug!(
            "V50: Setting DataTable with {} rows, {} columns",
            datatable.as_ref().map_or(0, |d| d.row_count()),
            datatable.as_ref().map_or(0, |d| d.column_count())
        );

        // Log current state
        if let Some(ref current) = self.datatable {
            debug!(
                "V50: Current DataTable has {} columns: {:?}",
                current.column_count(),
                current.column_names()
            );
        }

        if let Some(ref original) = self.original_source {
            debug!(
                "V50: Original source has {} columns: {:?}",
                original.column_count(),
                original.column_names()
            );
        }

        // Preserve the original source if this is the first data load
        // Only update original_source if we don't have one yet
        if datatable.is_some() && self.original_source.is_none() {
            self.original_source = datatable.clone();
            debug!(
                "V50: Preserving original source DataTable with {} columns",
                datatable.as_ref().map_or(0, |d| d.column_count())
            );
        }

        // When setting a DataTable, also create a DataView for it
        // This ensures we always have a DataView as the source of truth for column visibility
        if let Some(dt) = &datatable {
            // Use the existing Arc, don't clone the DataTable!
            let mut view = crate::data::data_view::DataView::new(dt.clone());

            // Apply any existing hidden columns from the previous DataView
            if let Some(old_view) = &self.dataview {
                // Get list of hidden column names from old view
                let old_all_cols = old_view.source().column_names();
                let old_visible_cols = old_view.column_names();

                for col_name in &old_all_cols {
                    if !old_visible_cols.contains(col_name) {
                        // This column was hidden in the old view
                        view.hide_column_by_name(col_name);
                    }
                }
            }

            // Optimize memory after setting up the view
            view.shrink_to_fit();

            // DataView now handles column visibility directly
            self.dataview = Some(view);
        } else {
            self.dataview = None;
        }

        // IMPORTANT: Never replace the datatable if we have an original source
        // and the new table has fewer columns (indicating it's a query result)
        if let Some(ref original) = self.original_source {
            if let Some(ref new_dt) = datatable {
                if new_dt.column_count() < original.column_count() {
                    debug!(
                        "V50: WARNING - Attempted to replace datatable with fewer columns ({} < {}). Keeping original.",
                        new_dt.column_count(),
                        original.column_count()
                    );
                    // Don't replace the datatable with a reduced one
                    return;
                }
            }
        }

        self.datatable = datatable;
    }

    fn set_results_as_datatable(&mut self, response: Option<QueryResponse>) -> Result<(), String> {
        if let Some(ref resp) = response {
            debug!("V50: Converting QueryResponse to DataTable");
            let table_name = resp.table.as_deref().unwrap_or("data");
            match DataTable::from_query_response(resp, table_name) {
                Ok(datatable) => {
                    debug!(
                        "V50: Stored DataTable with {} rows, {} columns",
                        datatable.row_count(),
                        datatable.column_count()
                    );
                    self.datatable = Some(Arc::new(datatable));
                    Ok(())
                }
                Err(e) => {
                    let err_msg = format!("V50: Failed to create DataTable: {e}");
                    debug!("{}", err_msg);
                    self.datatable = None;
                    Err(err_msg)
                }
            }
        } else {
            self.datatable = None;
            Ok(())
        }
    }

    // --- V51: DataView support (direct query results) ---
    fn get_dataview(&self) -> Option<&DataView> {
        self.dataview.as_ref()
    }
    fn get_dataview_mut(&mut self) -> Option<&mut DataView> {
        self.dataview.as_mut()
    }
    fn set_dataview(&mut self, dataview: Option<DataView>) {
        debug!(
            "V51: Setting DataView with {} rows",
            dataview
                .as_ref()
                .map_or(0, super::data::data_view::DataView::row_count)
        );
        self.dataview = dataview;
    }
    fn has_dataview(&self) -> bool {
        self.dataview.is_some()
    }

    // --- Mode and Status ---
    fn get_mode(&self) -> AppMode {
        self.mode.clone()
    }

    fn set_mode(&mut self, mode: AppMode) {
        self.mode = mode;
    }

    fn get_edit_mode(&self) -> EditMode {
        self.edit_mode.clone()
    }

    fn set_edit_mode(&mut self, mode: EditMode) {
        self.edit_mode = mode;
    }

    fn get_status_message(&self) -> String {
        self.status_message.clone()
    }

    fn set_status_message(&mut self, message: String) {
        self.status_message = message;
    }

    // --- Table Navigation ---
    fn get_selected_row(&self) -> Option<usize> {
        // For backward compatibility, check if table_state has a selection
        // This maintains the old API behavior where None means no selection
        self.table_state.selected()
    }

    fn set_selected_row(&mut self, row: Option<usize>) {
        if let Some(r) = row {
            self.view_state.crosshair_row = r;
            // Also update table_state for compatibility during migration
            self.table_state.select(Some(r));
        } else {
            // When setting to None, reset crosshair to 0 but clear table selection
            self.view_state.crosshair_row = 0;
            self.table_state.select(None);
        }
    }

    fn get_current_column(&self) -> usize {
        self.view_state.crosshair_col
    }

    fn set_current_column(&mut self, col: usize) {
        self.view_state.crosshair_col = col;
    }

    fn get_scroll_offset(&self) -> (usize, usize) {
        self.view_state.scroll_offset
    }

    fn set_scroll_offset(&mut self, offset: (usize, usize)) {
        self.view_state.scroll_offset = offset;
    }

    fn get_last_results_row(&self) -> Option<usize> {
        self.last_results_row
    }

    fn set_last_results_row(&mut self, row: Option<usize>) {
        self.last_results_row = row;
    }

    fn get_last_scroll_offset(&self) -> (usize, usize) {
        self.last_scroll_offset
    }

    fn set_last_scroll_offset(&mut self, offset: (usize, usize)) {
        self.last_scroll_offset = offset;
    }

    // --- Filtering ---
    fn get_filter_pattern(&self) -> String {
        self.filter_state.pattern.clone()
    }

    fn set_filter_pattern(&mut self, pattern: String) {
        self.filter_state.pattern = pattern;
    }

    fn is_filter_active(&self) -> bool {
        self.filter_state.active
    }

    fn set_filter_active(&mut self, active: bool) {
        self.filter_state.active = active;
    }

    // REMOVED: get_filtered_data/set_filtered_data implementations

    // --- Fuzzy Filter ---
    fn get_fuzzy_filter_pattern(&self) -> String {
        self.fuzzy_filter_state.pattern.clone()
    }

    fn set_fuzzy_filter_pattern(&mut self, pattern: String) {
        self.fuzzy_filter_state.pattern = pattern;
    }

    fn is_fuzzy_filter_active(&self) -> bool {
        self.fuzzy_filter_state.active
    }

    fn set_fuzzy_filter_active(&mut self, active: bool) {
        self.fuzzy_filter_state.active = active;
    }

    fn get_fuzzy_filter_indices(&self) -> &Vec<usize> {
        &self.fuzzy_filter_state.filtered_indices
    }

    fn set_fuzzy_filter_indices(&mut self, indices: Vec<usize>) {
        self.fuzzy_filter_state.filtered_indices = indices;
    }

    fn clear_fuzzy_filter(&mut self) {
        self.fuzzy_filter_state.pattern.clear();
        self.fuzzy_filter_state.active = false;
        self.fuzzy_filter_state.filtered_indices.clear();
    }

    // --- Search ---
    fn get_search_pattern(&self) -> String {
        self.search_state.pattern.clone()
    }

    fn set_search_pattern(&mut self, pattern: String) {
        self.search_state.pattern = pattern;
    }

    fn get_search_matches(&self) -> Vec<(usize, usize)> {
        self.search_state.matches.clone()
    }

    fn set_search_matches(&mut self, matches: Vec<(usize, usize)>) {
        self.search_state.matches = matches;
    }

    fn get_current_match(&self) -> Option<(usize, usize)> {
        self.search_state.current_match
    }

    fn set_current_match(&mut self, match_pos: Option<(usize, usize)>) {
        self.search_state.current_match = match_pos;
    }

    fn get_search_match_index(&self) -> usize {
        self.search_state.match_index
    }

    fn set_search_match_index(&mut self, index: usize) {
        self.search_state.match_index = index;
    }

    fn clear_search_state(&mut self) {
        self.search_state.pattern.clear();
        self.search_state.matches.clear();
        self.search_state.current_match = None;
        self.search_state.match_index = 0;
    }

    // --- Column Search ---

    fn get_column_stats(&self) -> Option<&ColumnStatistics> {
        self.column_stats.as_ref()
    }

    fn set_column_stats(&mut self, stats: Option<ColumnStatistics>) {
        self.column_stats = stats;
    }

    // --- Sorting ---
    fn get_sort_column(&self) -> Option<usize> {
        self.sort_state.column
    }

    fn set_sort_column(&mut self, column: Option<usize>) {
        self.sort_state.column = column;
    }

    fn get_sort_order(&self) -> SortOrder {
        self.sort_state.order
    }

    fn set_sort_order(&mut self, order: SortOrder) {
        self.sort_state.order = order;
    }

    // --- Display Options ---
    fn is_compact_mode(&self) -> bool {
        self.compact_mode
    }

    fn set_compact_mode(&mut self, compact: bool) {
        self.compact_mode = compact;
    }

    fn is_show_row_numbers(&self) -> bool {
        self.show_row_numbers
    }

    fn set_show_row_numbers(&mut self, show: bool) {
        self.show_row_numbers = show;
    }

    fn is_viewport_lock(&self) -> bool {
        self.view_state.viewport_lock
    }

    fn set_viewport_lock(&mut self, locked: bool) {
        self.view_state.viewport_lock = locked;
    }

    fn get_viewport_lock_row(&self) -> Option<usize> {
        // Return current crosshair row when viewport is locked
        if self.view_state.viewport_lock {
            Some(self.view_state.crosshair_row)
        } else {
            None
        }
    }

    fn set_viewport_lock_row(&mut self, row: Option<usize>) {
        // When setting viewport lock row, update the crosshair position
        if let Some(r) = row {
            self.view_state.crosshair_row = r;
            self.view_state.viewport_lock = true;
        }
    }

    fn get_column_widths(&self) -> &Vec<u16> {
        &self.column_widths
    }

    fn set_column_widths(&mut self, widths: Vec<u16>) {
        self.column_widths = widths;
    }

    fn is_case_insensitive(&self) -> bool {
        self.case_insensitive
    }

    fn set_case_insensitive(&mut self, case_insensitive: bool) {
        self.case_insensitive = case_insensitive;
    }

    // --- Buffer Metadata ---
    fn get_name(&self) -> String {
        self.name.clone()
    }

    fn set_name(&mut self, name: String) {
        self.name = name;
    }

    fn get_file_path(&self) -> Option<&PathBuf> {
        self.file_path.as_ref()
    }

    fn set_file_path(&mut self, path: Option<String>) {
        self.file_path = path.map(PathBuf::from);
    }

    fn is_modified(&self) -> bool {
        self.modified
    }

    fn set_modified(&mut self, modified: bool) {
        self.modified = modified;
    }

    fn get_last_query_source(&self) -> Option<String> {
        self.last_query_source.clone()
    }

    fn set_last_query_source(&mut self, source: Option<String>) {
        self.last_query_source = source;
    }

    // --- Input State ---
    fn get_input_value(&self) -> String {
        self.input.value().to_string()
    }

    fn set_input_value(&mut self, value: String) {
        let cursor = value.len();
        self.input = Input::new(value).with_cursor(cursor);
    }

    fn get_input_cursor(&self) -> usize {
        self.input.cursor()
    }

    fn set_input_cursor(&mut self, pos: usize) {
        let value = self.input.value().to_string();
        self.input = Input::new(value).with_cursor(pos);
    }

    // --- Advanced Operations ---
    fn apply_filter(&mut self) -> Result<()> {
        // TODO: Implement actual filtering logic
        Ok(())
    }

    fn apply_sort(&mut self) -> Result<()> {
        // TODO: Implement actual sorting logic
        Ok(())
    }

    fn search(&mut self) -> Result<()> {
        // TODO: Implement actual search logic
        Ok(())
    }

    fn clear_filters(&mut self) {
        self.filter_state.active = false;
        self.filter_state.pattern.clear();
        self.fuzzy_filter_state.active = false;
        self.fuzzy_filter_state.pattern.clear();
        // DataView handles the actual filtering
    }

    fn get_row_count(&self) -> usize {
        if let Some(dataview) = &self.dataview {
            dataview.row_count()
        } else if let Some(datatable) = &self.datatable {
            datatable.row_count()
        } else {
            0
        }
    }

    fn get_column_count(&self) -> usize {
        if let Some(datatable) = &self.datatable {
            return datatable.column_count();
        }
        0
    }

    fn get_column_names(&self) -> Vec<String> {
        if let Some(datatable) = &self.datatable {
            return datatable.column_names();
        }
        Vec::new()
    }

    // --- Edit State ---
    fn get_undo_stack(&self) -> &Vec<(String, usize)> {
        &self.undo_stack
    }

    fn push_undo(&mut self, state: (String, usize)) {
        self.undo_stack.push(state);
        if self.undo_stack.len() > 100 {
            self.undo_stack.remove(0);
        }
    }

    fn pop_undo(&mut self) -> Option<(String, usize)> {
        self.undo_stack.pop()
    }

    fn get_redo_stack(&self) -> &Vec<(String, usize)> {
        &self.redo_stack
    }

    fn push_redo(&mut self, state: (String, usize)) {
        self.redo_stack.push(state);
    }

    fn pop_redo(&mut self) -> Option<(String, usize)> {
        self.redo_stack.pop()
    }

    fn clear_redo(&mut self) {
        self.redo_stack.clear();
    }

    fn perform_undo(&mut self) -> bool {
        if let Some((prev_text, prev_cursor)) = self.pop_undo() {
            // Save current state to redo stack
            let current_state = (self.get_input_text(), self.get_input_cursor_position());
            self.push_redo(current_state);

            // Restore previous state
            self.set_input_text(prev_text);
            self.set_input_cursor_position(prev_cursor);
            true
        } else {
            false
        }
    }

    fn perform_redo(&mut self) -> bool {
        if let Some((next_text, next_cursor)) = self.pop_redo() {
            // Save current state to undo stack
            let current_state = (self.get_input_text(), self.get_input_cursor_position());
            self.push_undo(current_state);

            // Restore next state
            self.set_input_text(next_text);
            self.set_input_cursor_position(next_cursor);
            true
        } else {
            false
        }
    }

    fn save_state_for_undo(&mut self) {
        let current_state = (self.get_input_text(), self.get_input_cursor_position());
        self.push_undo(current_state);
        self.clear_redo();
    }

    fn get_kill_ring(&self) -> String {
        self.kill_ring.clone()
    }

    fn set_kill_ring(&mut self, text: String) {
        self.kill_ring = text;
    }

    fn is_kill_ring_empty(&self) -> bool {
        self.kill_ring.is_empty()
    }

    // --- Viewport State ---
    fn get_last_visible_rows(&self) -> usize {
        self.last_visible_rows
    }

    fn set_last_visible_rows(&mut self, rows: usize) {
        self.last_visible_rows = rows;
    }

    fn debug_dump(&self) -> String {
        let mut output = String::new();
        output.push_str("=== BUFFER DEBUG DUMP ===\n");
        output.push_str(&format!("Buffer ID: {}\n", self.id));
        output.push_str(&format!("Name: {}\n", self.name));
        output.push_str(&format!("File Path: {:?}\n", self.file_path));
        output.push_str(&format!("Modified: {}\n", self.modified));
        output.push_str("\n--- Modes ---\n");
        output.push_str(&format!("App Mode: {:?}\n", self.mode));
        output.push_str(&format!("Edit Mode: {:?}\n", self.edit_mode));
        output.push_str("\n--- Query State ---\n");
        output.push_str(&format!("Current Input: '{}'\n", self.input.value()));
        output.push_str(&format!("Input Cursor: {}\n", self.input.cursor()));
        output.push_str(&format!("Last Query: '{}'\n", self.last_query));
        output.push_str(&format!("Status Message: '{}'\n", self.status_message));
        output.push_str(&format!(
            "Last Query Source: {:?}\n",
            self.last_query_source
        ));
        output.push_str("\n--- Results ---\n");
        output.push_str(&format!("Has DataTable: {}\n", self.datatable.is_some()));
        output.push_str(&format!("Row Count: {}\n", self.get_row_count()));
        output.push_str(&format!("Column Count: {}\n", self.get_column_count()));
        output.push_str(&format!(
            "Selected Row: {:?}\n",
            self.table_state.selected()
        ));
        output.push_str(&format!(
            "Current Column: {}\n",
            self.view_state.crosshair_col
        ));
        output.push_str(&format!(
            "Scroll Offset: {:?}\n",
            self.view_state.scroll_offset
        ));
        output.push_str("\n--- Filtering ---\n");
        output.push_str(&format!("Filter Active: {}\n", self.filter_state.active));
        output.push_str(&format!(
            "Filter Pattern: '{}'\n",
            self.filter_state.pattern
        ));
        output.push_str("Filtering: Handled by DataView\n");
        output.push_str(&format!(
            "Fuzzy Filter Active: {}\n",
            self.fuzzy_filter_state.active
        ));
        output.push_str(&format!(
            "Fuzzy Pattern: '{}'\n",
            self.fuzzy_filter_state.pattern
        ));
        output.push_str("\n--- Search ---\n");
        output.push_str(&format!(
            "Search Pattern: '{}'\n",
            self.search_state.pattern
        ));
        output.push_str(&format!(
            "Search Matches: {} found\n",
            self.search_state.matches.len()
        ));
        output.push_str(&format!(
            "Current Match: {:?}\n",
            self.search_state.current_match
        ));
        output.push_str(&format!("Match Index: {}\n", self.search_state.match_index));
        output.push_str("\n--- Column Search ---\n");
        output.push_str(&format!(
            "Column Search Pattern: '{}'\n",
            "<migrated>" // Column search migrated to AppStateContainer
        ));
        output.push_str(&format!(
            "Matching Columns: {:?}\n",
            Vec::<(usize, String)>::new() // Column search migrated to AppStateContainer
        ));
        output.push_str("\n--- Sorting ---\n");
        output.push_str(&format!("Sort Column: {:?}\n", self.sort_state.column));
        output.push_str(&format!("Sort Order: {:?}\n", self.sort_state.order));
        output.push_str("\n--- Display Options ---\n");
        output.push_str(&format!("Compact Mode: {}\n", self.compact_mode));
        output.push_str(&format!("Show Row Numbers: {}\n", self.show_row_numbers));
        output.push_str(&format!("Case Insensitive: {}\n", self.case_insensitive));
        // Pinned columns now handled by DataView
        if let Some(ref dataview) = self.dataview {
            output.push_str(&format!(
                "Pinned Columns: {:?}\n",
                dataview.get_pinned_column_names()
            ));
        } else {
            output.push_str("Pinned Columns: []\n");
        }
        output.push_str(&format!("Column Widths: {:?}\n", self.column_widths));
        output.push_str(&format!("ViewState: {:?}\n", self.view_state));
        output.push_str("\n--- Data Source ---\n");
        output.push_str("Legacy CSV/Cache fields removed - using DataTable/DataView\n");
        output.push_str("\n--- Undo/Redo ---\n");
        output.push_str(&format!("Undo Stack Size: {}\n", self.undo_stack.len()));
        output.push_str(&format!("Redo Stack Size: {}\n", self.redo_stack.len()));
        output.push_str(&format!(
            "Kill Ring: '{}'\n",
            if self.kill_ring.len() > 50 {
                format!(
                    "{}... ({} chars)",
                    &self.kill_ring[..50],
                    self.kill_ring.len()
                )
            } else {
                self.kill_ring.clone()
            }
        ));
        output.push_str("\n--- Stats ---\n");
        output.push_str(&format!(
            "Has Column Stats: {}\n",
            self.column_stats.is_some()
        ));
        output.push_str(&format!("Last Visible Rows: {}\n", self.last_visible_rows));
        output.push_str(&format!("Last Results Row: {:?}\n", self.last_results_row));
        output.push_str(&format!(
            "Last Scroll Offset: {:?}\n",
            self.last_scroll_offset
        ));
        output.push_str("\n=== END BUFFER DEBUG ===\n");
        output
    }

    // --- Input Management ---
    fn get_input_text(&self) -> String {
        self.input_manager.get_text()
    }

    fn set_input_text(&mut self, text: String) {
        self.input_manager.set_text(text.clone());
        // Sync with legacy fields for compatibility
        self.input = Input::new(text.clone()).with_cursor(text.len());
    }

    fn handle_input_key(&mut self, event: KeyEvent) -> bool {
        let result = self.input_manager.handle_key_event(event);
        // Sync with legacy fields after key handling
        self.sync_from_input_manager();
        result
    }

    fn switch_input_mode(&mut self, _multiline: bool) {
        let current_text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();

        // Always use single-line mode
        self.edit_mode = EditMode::SingleLine;
        self.input_manager = create_single_line(current_text.clone());
        // Update legacy input
        self.input =
            Input::new(current_text.clone()).with_cursor(cursor_pos.min(current_text.len()));

        // Try to restore cursor position
        self.input_manager.set_cursor_position(cursor_pos);
    }

    fn get_input_cursor_position(&self) -> usize {
        self.input_manager.get_cursor_position()
    }

    fn set_input_cursor_position(&mut self, position: usize) {
        self.input_manager.set_cursor_position(position);
        // Sync with legacy fields
        if self.edit_mode == EditMode::SingleLine {
            let text = self.input.value().to_string();
            self.input = Input::new(text).with_cursor(position);
        }
    }

    fn is_input_multiline(&self) -> bool {
        self.input_manager.is_multiline()
    }

    // --- History Navigation ---
    fn navigate_history_up(&mut self, history: &[String]) -> bool {
        // Set history if not already set
        self.input_manager.set_history(history.to_vec());
        let navigated = self.input_manager.history_previous();
        if navigated {
            // Sync to legacy fields
            self.sync_from_input_manager();
        }
        navigated
    }

    fn navigate_history_down(&mut self, history: &[String]) -> bool {
        // Set history if not already set
        self.input_manager.set_history(history.to_vec());
        let navigated = self.input_manager.history_next();
        if navigated {
            // Sync to legacy fields
            self.sync_from_input_manager();
        }
        navigated
    }

    fn reset_history_navigation(&mut self) {
        self.input_manager.reset_history_position();
    }

    // --- Results Management ---
    fn clear_results(&mut self) {
        self.datatable = None;
        // DataView handles filtering
        self.table_state.select(None);
        self.last_results_row = None;
        self.view_state.scroll_offset = (0, 0);
        self.last_scroll_offset = (0, 0);
        self.column_widths.clear();
        self.status_message = "Results cleared".to_string();
        // Reset search/filter states
        self.filter_state.active = false;
        self.filter_state.pattern.clear();
        self.search_state.pattern.clear();
        self.search_state.matches.clear();
        self.search_state.current_match = None;
    }
}

impl Buffer {
    /// Create a new empty buffer
    #[must_use]
    pub fn new(id: usize) -> Self {
        Self {
            id,
            file_path: None,
            name: format!("[Buffer {id}]"),
            modified: false,

            // Legacy CSV/Cache fields removed
            datatable: None,
            original_source: None,
            dataview: None,

            mode: AppMode::Command,
            edit_mode: EditMode::SingleLine,
            input: Input::default(),
            input_manager: create_single_line(String::new()),
            table_state: TableState::default(),
            last_results_row: None,
            last_scroll_offset: (0, 0),

            last_query: String::new(),
            status_message: String::new(),

            sort_state: SortState {
                column: None,
                order: SortOrder::None,
            },
            filter_state: FilterState::default(),
            fuzzy_filter_state: FuzzyFilterState::default(),
            search_state: SearchState::default(),
            // column_search_state: MIGRATED to AppStateContainer
            column_stats: None,

            view_state: ViewState::default(),
            column_widths: Vec::new(),
            compact_mode: false,
            show_row_numbers: false,
            case_insensitive: false,

            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            kill_ring: String::new(),
            last_visible_rows: 30,
            last_query_source: None,

            highlighted_text_cache: None,
            last_highlighted_text: String::new(),
            saved_input_state: None,
        }
    }

    /// Create a buffer from a CSV file
    #[must_use]
    pub fn from_csv(
        id: usize,
        path: PathBuf,
        _csv_client: CsvApiClient, // Kept for API compatibility but unused
        _table_name: String,       // Kept for API compatibility but unused
    ) -> Self {
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown.csv")
            .to_string();

        let mut buffer = Self::new(id);
        buffer.file_path = Some(path);
        buffer.name = name;
        // Legacy CSV fields removed - DataTable/DataView handles data

        buffer
    }

    /// Create a buffer from a JSON file
    #[must_use]
    pub fn from_json(
        id: usize,
        path: PathBuf,
        _csv_client: CsvApiClient, // Kept for API compatibility but unused
        _table_name: String,       // Kept for API compatibility but unused
    ) -> Self {
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown.json")
            .to_string();

        let mut buffer = Self::new(id);
        buffer.file_path = Some(path);
        buffer.name = name;
        // Legacy CSV fields removed - DataTable/DataView handles data

        buffer
    }

    /// Get display name for tab bar
    pub fn display_name(&self) -> String {
        if self.modified {
            format!("{}*", self.name)
        } else {
            self.name.clone()
        }
    }

    /// Get short name for tab bar (truncated if needed)
    pub fn short_name(&self, max_len: usize) -> String {
        let display = self.display_name();
        if display.len() <= max_len {
            display
        } else {
            format!("{}...", &display[..max_len.saturating_sub(3)])
        }
    }

    /// Check if buffer has a specific file open
    pub fn has_file(&self, path: &PathBuf) -> bool {
        self.file_path.as_ref() == Some(path)
    }

    /// Sync from `InputManager` to legacy fields (for compatibility during migration)
    fn sync_from_input_manager(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();

        // Always sync to single-line input
        let text_len = text.len();
        self.input = Input::new(text).with_cursor(cursor_pos.min(text_len));
    }

    /// Sync from legacy fields to `InputManager` (for compatibility during migration)
    fn sync_to_input_manager(&mut self) {
        // Always sync from single-line input
        let _text = self.input.value().to_string();
        self.input_manager = create_from_input(self.input.clone());
    }

    // --- Cursor Movement Operations ---
    // These use the CursorOperations helper to provide intelligent
    // SQL-aware cursor movement and text manipulation

    /// Move cursor to previous word boundary
    pub fn move_cursor_word_backward(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let new_pos = CursorOperations::find_word_boundary_backward(&text, cursor_pos);
        self.input_manager.set_cursor_position(new_pos);
        self.sync_from_input_manager();
        self.status_message = format!("Moved to position {new_pos} (word boundary)");
    }

    /// Move cursor to next word boundary
    pub fn move_cursor_word_forward(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let new_pos = CursorOperations::find_word_boundary_forward(&text, cursor_pos);
        self.input_manager.set_cursor_position(new_pos);
        self.sync_from_input_manager();
    }

    /// Delete word backward from cursor
    pub fn delete_word_backward(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let (new_text, new_cursor) = CursorOperations::delete_word_backward(&text, cursor_pos);

        // Store deleted text in kill ring
        if cursor_pos > new_cursor {
            self.kill_ring = text[new_cursor..cursor_pos].to_string();
        }

        self.input_manager.set_text(new_text);
        self.input_manager.set_cursor_position(new_cursor);
        self.sync_from_input_manager();
    }

    /// Delete word forward from cursor
    pub fn delete_word_forward(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let (new_text, new_cursor) = CursorOperations::delete_word_forward(&text, cursor_pos);

        // Store deleted text in kill ring
        let word_end = CursorOperations::find_word_boundary_forward(&text, cursor_pos);
        if word_end > cursor_pos {
            self.kill_ring = text[cursor_pos..word_end].to_string();
        }

        self.input_manager.set_text(new_text);
        self.input_manager.set_cursor_position(new_cursor);
        self.sync_from_input_manager();
    }

    /// Kill line from cursor to end
    pub fn kill_line(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let (new_text, killed) = CursorOperations::kill_line(&text, cursor_pos);

        self.kill_ring = killed;
        self.input_manager.set_text(new_text);
        self.sync_from_input_manager();
    }

    /// Kill line from start to cursor
    pub fn kill_line_backward(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let (new_text, killed, new_cursor) =
            CursorOperations::kill_line_backward(&text, cursor_pos);

        self.kill_ring = killed;
        self.input_manager.set_text(new_text);
        self.input_manager.set_cursor_position(new_cursor);
        self.sync_from_input_manager();
    }

    /// Jump to previous SQL token
    pub fn jump_to_prev_token(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let new_pos = CursorOperations::jump_to_prev_token(&text, cursor_pos);
        self.input_manager.set_cursor_position(new_pos);
        self.sync_from_input_manager();
    }

    /// Jump to next SQL token
    pub fn jump_to_next_token(&mut self) {
        let text = self.input_manager.get_text();
        let cursor_pos = self.input_manager.get_cursor_position();
        let new_pos = CursorOperations::jump_to_next_token(&text, cursor_pos);
        self.input_manager.set_cursor_position(new_pos);
        self.sync_from_input_manager();
    }

    /// Yank (paste) from kill ring
    pub fn yank(&mut self) {
        if !self.kill_ring.is_empty() {
            self.save_state_for_undo();

            let text = self.input_manager.get_text();
            let cursor_pos = self.input_manager.get_cursor_position();

            // Insert kill ring content at cursor position
            let before = text.chars().take(cursor_pos).collect::<String>();
            let after = text.chars().skip(cursor_pos).collect::<String>();
            let new_text = format!("{}{}{}", before, &self.kill_ring, after);
            let new_cursor = cursor_pos + self.kill_ring.len();

            self.input_manager.set_text(new_text);
            self.input_manager.set_cursor_position(new_cursor);
            self.sync_from_input_manager();
        }
    }

    /// Expand SELECT * to column names using schema information
    pub fn expand_asterisk(&mut self, parser: &HybridParser) -> bool {
        let query = self.input_manager.get_text();
        let query_upper = query.to_uppercase();

        // Find SELECT * pattern
        if let Some(select_pos) = query_upper.find("SELECT") {
            if let Some(star_pos) = query_upper[select_pos..].find('*') {
                let star_abs_pos = select_pos + star_pos;

                // Find FROM clause after the *
                if let Some(from_rel_pos) = query_upper[star_abs_pos..].find("FROM") {
                    let from_abs_pos = star_abs_pos + from_rel_pos;

                    // Extract table name after FROM
                    let after_from = &query[from_abs_pos + 4..].trim_start();
                    let table_name = after_from
                        .split_whitespace()
                        .next()
                        .unwrap_or("")
                        .trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_');

                    if !table_name.is_empty() {
                        // Get columns from the schema
                        let columns = parser.get_table_columns(table_name);

                        if columns.is_empty() {
                            self.status_message =
                                format!("No columns found for table '{table_name}'");
                        } else {
                            // Build the replacement with all columns
                            let columns_str = columns.join(", ");

                            // Replace * with the column list
                            let before_star = &query[..star_abs_pos];
                            let after_star = &query[star_abs_pos + 1..];
                            let new_query = format!("{before_star}{columns_str}{after_star}");

                            // Update the input
                            self.input_manager.set_text(new_query.clone());
                            self.input_manager.set_cursor_position(new_query.len());
                            self.sync_from_input_manager();

                            self.status_message =
                                format!("Expanded * to {} columns", columns.len());
                            return true;
                        }
                    }
                }
            }
        }

        self.status_message = "No SELECT * pattern found to expand".to_string();
        false
    }

    /// Expand SELECT * to only visible column names
    pub fn expand_asterisk_visible(&mut self) -> bool {
        let query = self.input_manager.get_text();
        let query_upper = query.to_uppercase();

        // Find SELECT * pattern
        if let Some(select_pos) = query_upper.find("SELECT") {
            if let Some(star_pos) = query_upper[select_pos..].find('*') {
                let star_abs_pos = select_pos + star_pos;

                // Get visible columns from the DataView
                if let Some(dataview) = &self.dataview {
                    let visible_columns = dataview.get_display_column_names();

                    if !visible_columns.is_empty() {
                        // Build the replacement with visible columns only
                        let columns_str = visible_columns.join(", ");

                        // Replace * with the column list
                        let before_star = &query[..star_abs_pos];
                        let after_star = &query[star_abs_pos + 1..];
                        let new_query = format!("{before_star}{columns_str}{after_star}");

                        // Update the input
                        self.input_manager.set_text(new_query.clone());
                        self.input_manager.set_cursor_position(new_query.len());
                        self.sync_from_input_manager();

                        self.status_message =
                            format!("Expanded * to {} visible columns", visible_columns.len());
                        return true;
                    }
                    self.status_message = "No visible columns available".to_string();
                } else {
                    self.status_message = "No data loaded to expand from".to_string();
                }
            }
        }

        self.status_message = "No SELECT * pattern found to expand".to_string();
        false
    }
}

// Manual Clone implementation for Buffer due to Box<dyn InputManager>
impl Clone for Buffer {
    fn clone(&self) -> Self {
        // Always clone as single-line mode
        let input_manager = create_from_input(self.input.clone());

        Self {
            id: self.id,
            file_path: self.file_path.clone(),
            name: self.name.clone(),
            modified: self.modified,
            // Legacy CSV/Cache fields removed
            datatable: self.datatable.clone(),
            original_source: self.original_source.clone(),
            dataview: self.dataview.clone(),
            mode: self.mode.clone(),
            edit_mode: self.edit_mode.clone(),
            input: self.input.clone(),
            input_manager,
            table_state: self.table_state.clone(),
            last_results_row: self.last_results_row,
            last_scroll_offset: self.last_scroll_offset,
            last_query: self.last_query.clone(),
            status_message: self.status_message.clone(),
            sort_state: self.sort_state.clone(),
            filter_state: self.filter_state.clone(),
            fuzzy_filter_state: self.fuzzy_filter_state.clone(),
            search_state: self.search_state.clone(),
            // column_search_state: MIGRATED to AppStateContainer
            column_stats: self.column_stats.clone(),
            view_state: self.view_state.clone(),
            column_widths: self.column_widths.clone(),
            compact_mode: self.compact_mode,
            show_row_numbers: self.show_row_numbers,
            case_insensitive: self.case_insensitive,
            undo_stack: self.undo_stack.clone(),
            redo_stack: self.redo_stack.clone(),
            kill_ring: self.kill_ring.clone(),
            last_visible_rows: self.last_visible_rows,
            last_query_source: self.last_query_source.clone(),
            highlighted_text_cache: self.highlighted_text_cache.clone(),
            last_highlighted_text: self.last_highlighted_text.clone(),
            saved_input_state: self.saved_input_state.clone(),
        }
    }
}

/// Manages multiple buffers and switching between them
pub struct BufferManager {
    buffers: Vec<Buffer>,
    current_buffer_index: usize,
    next_buffer_id: usize,
}

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

impl BufferManager {
    #[must_use]
    pub fn new() -> Self {
        Self {
            buffers: Vec::new(),
            current_buffer_index: 0,
            next_buffer_id: 1,
        }
    }

    /// Add a new buffer and make it current
    pub fn add_buffer(&mut self, mut buffer: Buffer) -> usize {
        buffer.id = self.next_buffer_id;
        self.next_buffer_id += 1;

        let index = self.buffers.len();
        self.buffers.push(buffer);
        self.current_buffer_index = index;
        index
    }

    /// Get current buffer
    #[must_use]
    pub fn current(&self) -> Option<&Buffer> {
        self.buffers.get(self.current_buffer_index)
    }

    /// Get current buffer mutably
    pub fn current_mut(&mut self) -> Option<&mut Buffer> {
        self.buffers.get_mut(self.current_buffer_index)
    }

    /// Switch to next buffer
    pub fn next_buffer(&mut self) {
        if !self.buffers.is_empty() {
            self.current_buffer_index = (self.current_buffer_index + 1) % self.buffers.len();
        }
    }

    /// Switch to previous buffer
    pub fn prev_buffer(&mut self) {
        if !self.buffers.is_empty() {
            if self.current_buffer_index == 0 {
                self.current_buffer_index = self.buffers.len() - 1;
            } else {
                self.current_buffer_index -= 1;
            }
        }
    }

    /// Switch to buffer by index
    pub fn switch_to(&mut self, index: usize) {
        if index < self.buffers.len() {
            self.current_buffer_index = index;
        }
    }

    /// Close current buffer
    pub fn close_current(&mut self) -> bool {
        if self.buffers.len() <= 1 {
            return false; // Don't close last buffer
        }

        self.buffers.remove(self.current_buffer_index);

        // Adjust current index if needed
        if self.current_buffer_index >= self.buffers.len() {
            self.current_buffer_index = self.buffers.len() - 1;
        }

        true
    }

    /// Find buffer by file path
    #[must_use]
    pub fn find_by_path(&self, path: &PathBuf) -> Option<usize> {
        self.buffers.iter().position(|b| b.has_file(path))
    }

    /// Get all buffers for display
    #[must_use]
    pub fn all_buffers(&self) -> &[Buffer] {
        &self.buffers
    }

    /// Get current buffer index
    #[must_use]
    pub fn current_index(&self) -> usize {
        self.current_buffer_index
    }

    /// Check if we have multiple buffers
    #[must_use]
    pub fn has_multiple(&self) -> bool {
        self.buffers.len() > 1
    }

    /// Clear all buffers (used when loading a new file)
    pub fn clear_all(&mut self) {
        self.buffers.clear();
        self.current_buffer_index = 0;
    }
}