cqlite-cli 0.11.0

Command-line interface for CQLite — read Apache Cassandra 5.0 SSTables without a cluster
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
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
#![allow(dead_code)]
// Allow deprecated BulletproofReader usage (Issue #190 - experimental reader)
// This will be removed once BulletproofReader is fully replaced with SSTableReader
#![allow(deprecated)]

use crate::cli::OutputFormat;
#[cfg(feature = "state_machine")]
use crate::cli::{ExportFormat, ImportFormat};
#[cfg(feature = "state_machine")]
use indicatif::{ProgressBar, ProgressStyle};
// use crate::formatter::CqlshTableFormatter;
// use crate::data_parser::{RealDataParser, ParsedRow};

// Temporary stub types for disabled modules
#[derive(Debug, Clone)]
pub struct ParsedRow {
    pub data: std::collections::HashMap<String, String>,
}

impl ParsedRow {
    pub fn get(&self, key: &str) -> Option<&String> {
        self.data.get(key)
    }

    pub fn to_json(&self) -> serde_json::Value {
        serde_json::Value::Object(
            self.data
                .iter()
                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                .collect(),
        )
    }
}

#[derive(Debug, Clone)]
pub struct RealDataParser {
    pub schema: cqlite_core::schema::TableSchema,
}

impl RealDataParser {
    pub fn new(schema: cqlite_core::schema::TableSchema) -> Self {
        Self { schema }
    }

    pub fn parse_entry(
        &self,
        _key: &cqlite_core::RowKey,
        _value: &cqlite_core::Value,
    ) -> Result<ParsedRow> {
        Ok(ParsedRow {
            data: std::collections::HashMap::new(),
        })
    }

    pub fn get_column_names(&self) -> Vec<String> {
        self.schema.columns.iter().map(|c| c.name.clone()).collect()
    }
}

/// Format duration for export statistics display
fn format_export_duration(duration: std::time::Duration) -> String {
    let secs = duration.as_secs();
    if secs == 0 {
        let millis = duration.as_millis();
        if millis > 0 {
            format!("{}ms", millis)
        } else {
            "<1ms".to_string()
        }
    } else if secs < 60 {
        format!("{}s", secs)
    } else if secs < 3600 {
        format!("{}m {}s", secs / 60, secs % 60)
    } else {
        format!("{}h {}m {}s", secs / 3600, (secs % 3600) / 60, secs % 60)
    }
}

// Stub for QueryExecutor
#[derive(Debug)]
pub struct QueryExecutor;

impl QueryExecutor {
    pub fn new(_config: QueryExecutorConfig) -> Self {
        Self
    }

    pub async fn execute_select(&self, _query: &str) -> Result<QueryResult> {
        Ok(QueryResult {
            rows: Vec::new(),
            execution_time_ms: 0.0,
        })
    }
}

#[derive(Debug, Default)]
pub struct QueryExecutorConfig;

// Wrapper struct for query results
#[derive(Debug, Clone)]
pub struct QueryResult {
    pub rows: Vec<ParsedRow>,
    pub execution_time_ms: f64,
}

impl QueryResult {
    pub fn display_table(&self) {
        if self.rows.is_empty() {
            println!("No rows returned");
            return;
        }

        // Create a simple table display
        let mut table = prettytable::Table::new();

        // Add headers if we can determine them from first row
        if let Some(first_row) = self.rows.first() {
            let headers: Vec<_> = first_row.data.keys().cloned().collect();
            table.set_titles(prettytable::Row::new(
                headers.iter().map(|h| prettytable::Cell::new(h)).collect(),
            ));

            // Add data rows
            for row in &self.rows {
                let cells: Vec<_> = headers
                    .iter()
                    .map(|h| prettytable::Cell::new(row.data.get(h).unwrap_or(&String::new())))
                    .collect();
                table.add_row(prettytable::Row::new(cells));
            }
        }

        table.printstd();
    }

    pub fn display_json(&self) -> Result<()> {
        let json_rows: Vec<_> = self.rows.iter().map(|r| r.to_json()).collect();
        println!("{}", serde_json::to_string_pretty(&json_rows)?);
        Ok(())
    }

    pub fn display_csv(&self) -> Result<()> {
        if self.rows.is_empty() {
            return Ok(());
        }

        let headers: Vec<_> = self.rows[0].data.keys().cloned().collect();

        // Print headers
        println!("{}", headers.join(","));

        // Print data
        for row in &self.rows {
            let values: Vec<_> = headers
                .iter()
                .map(|h| row.data.get(h).unwrap_or(&String::new()).clone())
                .collect();
            println!("{}", values.join(","));
        }

        Ok(())
    }
}
// use crate::pagination::{PaginationConfig, PaginatedReader, StreamingProcessor, PaginationProgress};
// use crate::query_executor::{QueryExecutor, QueryExecutorConfig};
// use crate::table_scanner::{TableScanner, ScanStrategy, ScanConfig};
use anyhow::{Context, Result};
#[cfg(feature = "state_machine")]
use cqlite_core::Database;
use cqlite_core::{
    schema::{parse_cql_schema, ClusteringColumn, ClusteringOrder, Column, KeyColumn, TableSchema},
    storage::sstable::{bulletproof_reader::BulletproofReader, reader::SSTableReader},
};
use std::collections::HashMap;
#[cfg(feature = "state_machine")]
use std::fs::File;
#[cfg(feature = "state_machine")]
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

pub mod admin;
pub mod bench;
pub mod schema;
pub mod write;

pub mod docker;
pub mod info;
pub mod read_sstable;

#[cfg(feature = "state_machine")]
pub async fn execute_query(
    database: &Database,
    query: &str,
    explain: bool,
    timing: bool,
    format: OutputFormat,
    config: &crate::config::OutputConfig,
) -> Result<()> {
    use crate::output::{write_to_target, OutputTarget};
    use std::time::Instant;

    let start_time = Instant::now();

    // Handle explain queries (always to stdout, not affected by --output)
    if explain {
        let explain_result = database
            .explain(query)
            .await
            .with_context(|| "Failed to explain query")?;

        println!("Query Explanation");
        println!("================");
        println!("Query Type: {}", explain_result.query_type);
        println!("Plan Type: {}", explain_result.plan_type);
        println!("Estimated Cost: {:.2}", explain_result.estimated_cost);
        println!("Estimated Rows: {}", explain_result.estimated_rows);

        if !explain_result.selected_indexes.is_empty() {
            println!("\nSelected Indexes:");
            for index in &explain_result.selected_indexes {
                println!("  - {index}");
            }
        }

        if !explain_result.execution_steps.is_empty() {
            println!("\nExecution Steps:");
            for (i, step) in explain_result.execution_steps.iter().enumerate() {
                println!("  {}. {}", i + 1, step);
            }
        }

        if !explain_result.parallelization_info.is_empty() {
            println!("\nParallelization:");
            for info in &explain_result.parallelization_info {
                println!("  - {info}");
            }
        }

        if timing {
            let elapsed = start_time.elapsed();
            println!("\nTiming: {:.2}ms", elapsed.as_millis());
        }

        return Ok(());
    }

    // Execute the query
    let result = database
        .execute(query)
        .await
        .with_context(|| "Failed to execute query")?;

    // Generate output bytes based on format (Issue #279)
    let output_bytes: Vec<u8> = match format {
        OutputFormat::Table => {
            use crate::output::table::TableWriter;
            let table_output = TableWriter::write(&result, config)
                .map_err(|e| anyhow::anyhow!("Failed to format table output: {}", e))?;
            table_output.into_bytes()
        }
        OutputFormat::Json => {
            use crate::output::json::JSONWriter;
            let json_output = JSONWriter::write(&result, config)
                .map_err(|e| anyhow::anyhow!("Failed to format JSON output: {}", e))?;
            json_output.into_bytes()
        }
        OutputFormat::Csv => {
            use crate::output::CSVWriter;
            let csv_output = CSVWriter::write(&result, config)
                .map_err(|e| anyhow::anyhow!("Failed to format CSV output: {}", e))?;
            csv_output.into_bytes()
        }
        OutputFormat::Parquet => {
            use crate::output::ParquetWriter;
            ParquetWriter::write(&result, config)
                .map_err(|e| anyhow::anyhow!("Failed to format Parquet output: {}", e))?
        }
    };

    // Write to target (stdout or file)
    write_to_target(&output_bytes, &config.target, config.overwrite)
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    // Add newline for text formats written to stdout (not for binary/file output)
    if matches!(config.target, OutputTarget::Stdout) && !matches!(format, OutputFormat::Parquet) {
        // Text writers don't include trailing newline, so add one for stdout
        // (CSV already ends with newline from csv crate)
        if !matches!(format, OutputFormat::Csv) {
            println!();
        }
    }

    // Show success message for file output (to stderr so it doesn't mix with output)
    if let OutputTarget::File(path) = &config.target {
        eprintln!("Output written to: {}", path.display());
    }

    // Show timing information if requested (to stderr when writing to file)
    if timing {
        let elapsed = start_time.elapsed();
        eprintln!("\nQuery executed in {:.2}ms", elapsed.as_millis());

        let performance = result.performance();
        if performance.total_time_us > 0 {
            eprintln!(
                "Parse time: {:.2}ms",
                performance.parse_time_us as f64 / 1000.0
            );
            eprintln!(
                "Planning time: {:.2}ms",
                performance.planning_time_us as f64 / 1000.0
            );
            eprintln!(
                "Execution time: {:.2}ms",
                performance.execution_time_us as f64 / 1000.0
            );
            eprintln!("Memory usage: {} bytes", performance.memory_usage_bytes);
            eprintln!("I/O operations: {}", performance.io_operations);
            if performance.cache_hits + performance.cache_misses > 0 {
                eprintln!(
                    "Cache hit ratio: {:.1}%",
                    performance.cache_hit_ratio() * 100.0
                );
            }
        }
    }

    // Show warnings if any (to stderr)
    let warnings = result.warnings();
    if !warnings.is_empty() {
        eprintln!("\nWarnings:");
        for warning in warnings {
            eprintln!("  ⚠️  {warning}");
        }
    }

    Ok(())
}

#[cfg(not(feature = "state_machine"))]
pub async fn execute_query(
    _database: &cqlite_core::Database,
    _query: &str,
    _explain: bool,
    _timing: bool,
    _format: OutputFormat,
    _config: &crate::config::OutputConfig,
) -> Result<()> {
    Err(anyhow::anyhow!(
        "Query execution is not available in M1.\n\
         Build with --features state_machine to enable this feature.\n\
         See CLAUDE.md for M1 API examples."
    ))
}

/// Print results in CSV format
#[cfg(feature = "state_machine")]
fn print_csv_format(
    result: &cqlite_core::query::result::QueryResult,
    config: &crate::config::OutputConfig,
) -> Result<()> {
    use crate::output::CSVWriter;

    // CSVWriter handles limit internally via config
    let csv_output = CSVWriter::write(result, config)
        .map_err(|e| anyhow::anyhow!("Failed to format CSV output: {}", e))?;

    print!("{}", csv_output);
    Ok(())
}

#[cfg(feature = "state_machine")]
pub async fn import_data(
    database: &Database,
    file: &Path,
    format: ImportFormat,
    table: Option<&str>,
) -> Result<()> {
    println!("Importing data from: {}", file.display());
    println!("Format: {format}, Target table: {table:?}");

    // Validate input file exists
    if !file.exists() {
        return Err(anyhow::anyhow!("Import file not found: {}", file.display()));
    }

    // Determine target table
    let target_table = match table {
        Some(t) => t.to_string(),
        None => {
            // Try to infer table name from filename
            file.file_stem()
                .and_then(|stem| stem.to_str())
                .map(|s| s.to_string())
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "Could not determine target table name. Please specify --table option."
                    )
                })?
        }
    };

    // Try to validate target table exists, but don't fail if we can't verify
    let table_check_query =
        format!("SELECT table_name FROM system.tables WHERE table_name = '{target_table}'");
    match database.execute(&table_check_query).await {
        Ok(result) if result.rows.is_empty() => {
            println!(
                "⚠️  Warning: Table '{}' not found in system catalog. Assuming it exists or will be created during import.",
                target_table
            );
        }
        Ok(_) => {
            println!("✓ Target table '{target_table}' found");
        }
        Err(_) => {
            println!(
                "⚠️  Warning: Could not verify table existence (system tables may not be implemented). Proceeding with import..."
            );
        }
    }

    // Get table schema for validation
    let table_columns = get_table_columns(database, &target_table).await
        .unwrap_or_else(|_| {
            println!("⚠️  Warning: Could not retrieve table schema. Import may fail if column types don't match.");
            Vec::new()
        });

    let mut _imported_rows = 0;
    let error_count = 0;

    match format {
        ImportFormat::Csv => {
            _imported_rows = import_csv_data(database, file, &target_table, &table_columns).await?;
        }
        ImportFormat::Json => {
            _imported_rows =
                import_json_data(database, file, &target_table, &table_columns).await?;
        }
        ImportFormat::Parquet => {
            return Err(anyhow::anyhow!(
                "Parquet import not yet implemented. Please convert to CSV or JSON format first."
            ));
        }
    }

    println!("\n📊 Import Summary:");
    println!("  Rows imported: {_imported_rows}");
    if error_count > 0 {
        println!("  Errors: {error_count}");
    }
    println!("  ✅ Import completed successfully!");

    Ok(())
}

#[cfg(not(feature = "state_machine"))]
pub async fn import_data(
    _database: &cqlite_core::Database,
    _file: &Path,
    _format: crate::cli::ImportFormat,
    _table: Option<&str>,
) -> Result<()> {
    Err(anyhow::anyhow!(
        "Data import is not available in M1.\n\
         Build with --features state_machine to enable this feature.\n\
         See CLAUDE.md for M1 API examples."
    ))
}

/// Import CSV data into the specified table
#[cfg(feature = "state_machine")]
async fn import_csv_data(
    database: &Database,
    file: &Path,
    table: &str,
    table_columns: &[String],
) -> Result<u64> {
    use csv::ReaderBuilder;
    use indicatif::{ProgressBar, ProgressStyle};

    let file_handle =
        File::open(file).with_context(|| format!("Failed to open CSV file: {}", file.display()))?;

    let mut csv_reader = ReaderBuilder::new()
        .has_headers(true)
        .from_reader(file_handle);

    // Get headers from CSV
    let headers = csv_reader
        .headers()
        .with_context(|| "Failed to read CSV headers")?;
    let csv_columns: Vec<String> = headers.iter().map(|h| h.to_string()).collect();

    println!("📋 CSV columns: {}", csv_columns.join(", "));
    if !table_columns.is_empty() {
        println!("📋 Table columns: {}", table_columns.join(", "));
    }

    // Count total rows for progress
    let total_rows = csv_reader.records().count() as u64;

    // Reopen file for actual processing
    let file_handle = File::open(file)?;
    let mut csv_reader = ReaderBuilder::new()
        .has_headers(true)
        .from_reader(file_handle);

    let pb = ProgressBar::new(total_rows);
    pb.set_style(
        ProgressStyle::default_bar()
            .template(
                "Importing CSV [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} rows ({eta})",
            )
            .unwrap()
            .progress_chars("=>-"),
    );

    let mut imported_count = 0;
    let mut batch_statements = Vec::new();
    let batch_size = 100; // Process in batches for better performance

    for (row_num, record_result) in csv_reader.records().enumerate() {
        pb.set_position(row_num as u64 + 1);

        let record = record_result
            .with_context(|| format!("Failed to parse CSV record at line {}", row_num + 2))?;

        // Create INSERT statement
        let values: Vec<String> = record
            .iter()
            .map(|field| {
                if field.is_empty() {
                    "NULL".to_string()
                } else {
                    format!("'{}'", field.replace("'", "''")) // Escape single quotes
                }
            })
            .collect();

        let insert_stmt = format!(
            "INSERT INTO {} ({}) VALUES ({})",
            table,
            csv_columns.join(", "),
            values.join(", ")
        );

        batch_statements.push(insert_stmt);

        // Execute batch when it reaches the batch size
        if batch_statements.len() >= batch_size {
            execute_batch_statements(database, &mut batch_statements, &mut imported_count).await?;
        }
    }

    // Execute remaining statements
    if !batch_statements.is_empty() {
        execute_batch_statements(database, &mut batch_statements, &mut imported_count).await?;
    }

    pb.finish_with_message(format!("Imported {imported_count} rows from CSV"));
    Ok(imported_count)
}

/// Import JSON data into the specified table
#[cfg(feature = "state_machine")]
async fn import_json_data(
    database: &Database,
    file: &Path,
    table: &str,
    _table_columns: &[String],
) -> Result<u64> {
    use indicatif::{ProgressBar, ProgressStyle};
    use std::fs;

    let file_content = fs::read_to_string(file)
        .with_context(|| format!("Failed to read JSON file: {}", file.display()))?;

    // Try to parse as array of objects or single object
    let json_data: serde_json::Value =
        serde_json::from_str(&file_content).with_context(|| "Failed to parse JSON file")?;

    let objects = match json_data {
        serde_json::Value::Array(arr) => arr,
        serde_json::Value::Object(_) => vec![json_data],
        _ => {
            return Err(anyhow::anyhow!(
                "JSON file must contain an object or array of objects"
            ));
        }
    };

    println!("📋 Found {} JSON objects to import", objects.len());

    let pb = ProgressBar::new(objects.len() as u64);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("Importing JSON [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} objects ({eta})")
            .unwrap()
            .progress_chars("=>-"),
    );

    let mut imported_count = 0;
    let mut batch_statements = Vec::new();
    let batch_size = 50;

    for (index, obj) in objects.iter().enumerate() {
        pb.set_position(index as u64 + 1);

        if let serde_json::Value::Object(map) = obj {
            let columns: Vec<String> = map.keys().cloned().collect();
            let values: Vec<String> = map
                .values()
                .map(|v| match v {
                    serde_json::Value::Null => "NULL".to_string(),
                    serde_json::Value::String(s) => format!("'{}'", s.replace("'", "''")),
                    serde_json::Value::Number(n) => n.to_string(),
                    serde_json::Value::Bool(b) => b.to_string(),
                    _ => format!("'{}'", v.to_string().replace("'", "''")),
                })
                .collect();

            let insert_stmt = format!(
                "INSERT INTO {} ({}) VALUES ({})",
                table,
                columns.join(", "),
                values.join(", ")
            );

            batch_statements.push(insert_stmt);

            if batch_statements.len() >= batch_size {
                execute_batch_statements(database, &mut batch_statements, &mut imported_count)
                    .await?;
            }
        } else {
            println!("⚠️  Skipping non-object JSON element at index {index}");
        }
    }

    // Execute remaining statements
    if !batch_statements.is_empty() {
        execute_batch_statements(database, &mut batch_statements, &mut imported_count).await?;
    }

    pb.finish_with_message(format!("Imported {imported_count} objects from JSON"));
    Ok(imported_count)
}

/// Execute a batch of INSERT statements
#[cfg(feature = "state_machine")]
async fn execute_batch_statements(
    database: &Database,
    statements: &mut Vec<String>,
    imported_count: &mut u64,
) -> Result<()> {
    for statement in statements.drain(..) {
        match database.execute(&statement).await {
            Ok(_) => {
                *imported_count += 1;
            }
            Err(e) => {
                println!("⚠️  Error executing statement: {e}");
                println!(
                    "   Statement: {}",
                    statement.chars().take(100).collect::<String>() + "..."
                );
                // Continue with next statement rather than failing completely
            }
        }
    }
    Ok(())
}

/// Get table columns for schema validation
#[cfg(feature = "state_machine")]
async fn get_table_columns(database: &Database, table: &str) -> Result<Vec<String>> {
    let query = format!("SELECT column_name FROM system.columns WHERE table_name = '{table}'");
    match database.execute(&query).await {
        Ok(result) => {
            let columns = result
                .rows
                .iter()
                .filter_map(|row| row.get("column_name"))
                .map(|col| col.to_string())
                .collect();
            Ok(columns)
        }
        Err(e) => Err(anyhow::anyhow!("Failed to get table columns: {}", e)),
    }
}

/// Export data using true streaming execution (Issue #280)
///
/// This function uses `execute_streaming()` to process rows incrementally,
/// avoiding the need to materialize all query results in memory at once.
#[cfg(feature = "state_machine")]
pub async fn export_data(
    database: &Database,
    source: &str,
    file: &Path,
    format: ExportFormat,
    query_filter: Option<&str>,
    limit: Option<usize>,
    quiet: bool,
) -> Result<()> {
    use cqlite_core::query::result::StreamingConfig;
    use std::io::IsTerminal;
    use std::time::Instant;

    use crate::output::{
        create_streaming_parquet_writer, StreamingCSVWriter, StreamingJSONWriter, StreamingWriter,
    };
    use crate::status_metrics::format_bytes;

    // Determine if progress should be shown (not quiet, and output is a TTY)
    let show_progress = !quiet && std::io::stdout().is_terminal();

    if show_progress {
        println!("Exporting data from: {source}");
        println!("Output file: {}, Format: {}", file.display(), format);
    }

    // Create output directory if it doesn't exist
    if let Some(parent) = file.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create output directory: {}", parent.display()))?;
    }

    // Determine if source is a table name or a query
    let query = if source.to_uppercase().trim().starts_with("SELECT") {
        // If source is already a SELECT query, append LIMIT if specified
        // but only if the query doesn't already have a LIMIT clause
        match limit {
            Some(n) => {
                let upper = source.to_uppercase();
                if upper.contains(" LIMIT ") {
                    // Query already has LIMIT - use as-is to avoid invalid SQL
                    source.to_string()
                } else {
                    format!("{} LIMIT {}", source.trim_end_matches(';'), n)
                }
            }
            None => source.to_string(),
        }
    } else {
        // Source is a table name - build SELECT with optional WHERE and LIMIT
        let mut q = format!("SELECT * FROM {}", source);
        if let Some(filter) = query_filter {
            q.push_str(&format!(" WHERE {}", filter));
        }
        if let Some(n) = limit {
            q.push_str(&format!(" LIMIT {}", n));
        }
        q
    };

    if show_progress {
        println!(
            "Executing query: {}",
            query.chars().take(100).collect::<String>() + "..."
        );
    }

    // Configure streaming based on format
    let config = match format {
        ExportFormat::Parquet => StreamingConfig::for_parquet(),
        _ => StreamingConfig::for_text_formats(),
    };

    // Execute the query with streaming (Issue #280 - true end-to-end streaming)
    let mut result_iter = database
        .execute_streaming(&query, config.clone())
        .await
        .with_context(|| format!("Failed to execute streaming export query: {query}"))?;

    // Get column names from metadata
    let column_names: Vec<String> = result_iter
        .metadata
        .columns
        .iter()
        .map(|c| c.name.clone())
        .collect();

    if column_names.is_empty() {
        return Err(anyhow::anyhow!(
            "Could not determine column names for export"
        ));
    }

    if show_progress {
        println!("Columns: {}", column_names.join(", "));
        println!("Streaming export in progress...");
    }

    // Track timing for statistics
    let start_time = Instant::now();

    // Create spinner progress bar (unknown total for streaming)
    let pb = if show_progress {
        let pb = ProgressBar::new_spinner();
        pb.set_style(
            ProgressStyle::default_spinner()
                .template("{spinner:.green} {msg} ({pos} rows)")
                .unwrap(),
        );
        pb.set_message("Exporting");
        pb
    } else {
        ProgressBar::hidden()
    };

    // Chunk size for collecting rows before writing
    let chunk_size = config.chunk_size;
    let mut rows_exported: u64 = 0;
    // Track remaining rows for limit enforcement (streaming doesn't automatically enforce LIMIT)
    let mut rows_remaining: Option<usize> = limit;

    // Export based on format with true streaming
    match format {
        ExportFormat::Csv => {
            let output_file = File::create(file)
                .with_context(|| format!("Failed to create CSV file: {}", file.display()))?;
            let buf_writer = BufWriter::new(output_file);
            let mut writer = StreamingCSVWriter::new(buf_writer);

            writer
                .write_header(&result_iter.metadata)
                .map_err(|e| anyhow::anyhow!("Failed to write CSV header: {}", e))?;

            // Stream rows in chunks
            loop {
                // Check if we've hit the limit
                if rows_remaining == Some(0) {
                    break;
                }

                let chunk = result_iter
                    .collect_chunk(chunk_size)
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunk: {}", e))?;

                if chunk.is_empty() {
                    break;
                }

                // Truncate chunk if it exceeds remaining limit
                let chunk_to_write = if let Some(remaining) = rows_remaining {
                    if chunk.len() > remaining {
                        chunk.into_iter().take(remaining).collect::<Vec<_>>()
                    } else {
                        chunk
                    }
                } else {
                    chunk
                };

                let written = chunk_to_write.len();
                writer
                    .write_chunk(&chunk_to_write)
                    .map_err(|e| anyhow::anyhow!("Failed to write CSV chunk: {}", e))?;

                rows_exported += written as u64;
                pb.set_position(rows_exported);

                // Update remaining count
                if let Some(ref mut remaining) = rows_remaining {
                    *remaining = remaining.saturating_sub(written);
                }
            }

            writer
                .finalize()
                .map_err(|e| anyhow::anyhow!("Failed to finalize CSV: {}", e))?;
        }
        ExportFormat::Json => {
            let output_file = File::create(file)
                .with_context(|| format!("Failed to create JSON file: {}", file.display()))?;
            let buf_writer = BufWriter::new(output_file);
            let mut writer = StreamingJSONWriter::new(buf_writer);

            writer
                .write_header(&result_iter.metadata)
                .map_err(|e| anyhow::anyhow!("Failed to write JSON header: {}", e))?;

            // Stream rows in chunks
            loop {
                // Check if we've hit the limit
                if rows_remaining == Some(0) {
                    break;
                }

                let chunk = result_iter
                    .collect_chunk(chunk_size)
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunk: {}", e))?;

                if chunk.is_empty() {
                    break;
                }

                // Truncate chunk if it exceeds remaining limit
                let chunk_to_write = if let Some(remaining) = rows_remaining {
                    if chunk.len() > remaining {
                        chunk.into_iter().take(remaining).collect::<Vec<_>>()
                    } else {
                        chunk
                    }
                } else {
                    chunk
                };

                let written = chunk_to_write.len();
                writer
                    .write_chunk(&chunk_to_write)
                    .map_err(|e| anyhow::anyhow!("Failed to write JSON chunk: {}", e))?;

                rows_exported += written as u64;
                pb.set_position(rows_exported);

                // Update remaining count
                if let Some(ref mut remaining) = rows_remaining {
                    *remaining = remaining.saturating_sub(written);
                }
            }

            writer
                .finalize()
                .map_err(|e| anyhow::anyhow!("Failed to finalize JSON: {}", e))?;
        }
        ExportFormat::Cql => {
            // CQL format needs special handling - collect all for table name extraction
            // For now, fall back to non-streaming for CQL
            let output_file = File::create(file)
                .with_context(|| format!("Failed to create CQL file: {}", file.display()))?;
            let mut buf_writer = BufWriter::new(output_file);

            // Extract table name from source
            let table_name = if source.to_uppercase().contains("FROM") {
                source
                    .split_whitespace()
                    .skip_while(|&word| word.to_uppercase() != "FROM")
                    .nth(1)
                    .unwrap_or("exported_table")
            } else {
                source
            };

            // Write header comment
            writeln!(buf_writer, "-- CQL Export from CQLite (streaming)")?;
            writeln!(buf_writer, "-- Source: {source}")?;
            writeln!(
                buf_writer,
                "-- Generated: {}",
                chrono::Utc::now().to_rfc3339()
            )?;
            writeln!(buf_writer)?;

            // Stream rows
            loop {
                // Check if we've hit the limit
                if rows_remaining == Some(0) {
                    break;
                }

                let chunk = result_iter
                    .collect_chunk(chunk_size)
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunk: {}", e))?;

                if chunk.is_empty() {
                    break;
                }

                // Truncate chunk if it exceeds remaining limit
                let chunk_to_write: Vec<_> = if let Some(remaining) = rows_remaining {
                    if chunk.len() > remaining {
                        chunk.into_iter().take(remaining).collect()
                    } else {
                        chunk
                    }
                } else {
                    chunk
                };

                for row in &chunk_to_write {
                    let values: Vec<String> = column_names
                        .iter()
                        .map(|col| {
                            row.values
                                .get(col)
                                .map(|v| match v {
                                    cqlite_core::Value::Text(s) => {
                                        format!("'{}'", s.replace("'", "''"))
                                    }
                                    cqlite_core::Value::Null => "NULL".to_string(),
                                    _ => v.to_string(),
                                })
                                .unwrap_or_else(|| "NULL".to_string())
                        })
                        .collect();

                    writeln!(
                        buf_writer,
                        "INSERT INTO {} ({}) VALUES ({});",
                        table_name,
                        column_names.join(", "),
                        values.join(", ")
                    )?;
                }

                let written = chunk_to_write.len();
                rows_exported += written as u64;
                pb.set_position(rows_exported);

                // Update remaining count
                if let Some(ref mut remaining) = rows_remaining {
                    *remaining = remaining.saturating_sub(written);
                }
            }

            buf_writer.flush()?;
        }
        ExportFormat::Parquet => {
            let output_file = File::create(file)
                .with_context(|| format!("Failed to create Parquet file: {}", file.display()))?;

            let mut writer =
                create_streaming_parquet_writer(output_file, &result_iter.metadata, chunk_size)
                    .map_err(|e| anyhow::anyhow!("Failed to initialize Parquet writer: {}", e))?;

            writer
                .write_header(&result_iter.metadata)
                .map_err(|e| anyhow::anyhow!("Failed to write Parquet header: {}", e))?;

            // Stream rows in chunks
            loop {
                // Check if we've hit the limit
                if rows_remaining == Some(0) {
                    break;
                }

                let chunk = result_iter
                    .collect_chunk(chunk_size)
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunk: {}", e))?;

                if chunk.is_empty() {
                    break;
                }

                // Truncate chunk if it exceeds remaining limit
                let chunk_to_write = if let Some(remaining) = rows_remaining {
                    if chunk.len() > remaining {
                        chunk.into_iter().take(remaining).collect::<Vec<_>>()
                    } else {
                        chunk
                    }
                } else {
                    chunk
                };

                let written = chunk_to_write.len();
                writer
                    .write_chunk(&chunk_to_write)
                    .map_err(|e| anyhow::anyhow!("Failed to write Parquet chunk: {}", e))?;

                rows_exported += written as u64;
                pb.set_position(rows_exported);

                // Update remaining count
                if let Some(ref mut remaining) = rows_remaining {
                    *remaining = remaining.saturating_sub(written);
                }
            }

            writer
                .finalize()
                .map_err(|e| anyhow::anyhow!("Failed to finalize Parquet: {}", e))?;
        }
    }

    pb.finish_and_clear();

    // Display statistics (unless quiet)
    if !quiet {
        let duration = start_time.elapsed();
        let file_size = std::fs::metadata(file)?.len();

        println!("\nExport complete:");
        println!("  Rows: {}", rows_exported);
        println!("  Size: {}", format_bytes(file_size));
        println!("  Time: {}", format_export_duration(duration));
        let secs_f64 = duration.as_secs_f64();
        if secs_f64 > 0.0 {
            let rate = rows_exported as f64 / secs_f64;
            if rate.is_finite() {
                println!("  Rate: {:.0} rows/sec", rate);
            }
        }
    }

    Ok(())
}

#[cfg(not(feature = "state_machine"))]
pub async fn export_data(
    _database: &cqlite_core::Database,
    _source: &str,
    _file: &Path,
    _format: crate::cli::ExportFormat,
    _query_filter: Option<&str>,
    _limit: Option<usize>,
    _quiet: bool,
) -> Result<()> {
    Err(anyhow::anyhow!(
        "Data export is not available in M1.\n\
         Build with --features state_machine to enable this feature.\n\
         See CLAUDE.md for M1 API examples."
    ))
}

/// Export query result to CSV format using streaming writer (Issue #280)
///
/// Uses `StreamingCSVWriter` for memory-efficient chunked export.
/// Rows are written directly to file in chunks.
#[cfg(feature = "state_machine")]
async fn export_to_csv(
    result: &cqlite_core::query::result::QueryResult,
    file: &Path,
    _column_names: &[String],
    pb: &ProgressBar,
) -> Result<()> {
    use crate::output::{StreamingCSVWriter, StreamingWriter};

    // Chunk size for CSV streaming
    const CHUNK_SIZE: usize = 5_000;

    let output_file = File::create(file)
        .with_context(|| format!("Failed to create CSV file: {}", file.display()))?;

    // Create streaming CSV writer with buffering for I/O efficiency
    let buf_writer = BufWriter::new(output_file);
    let mut writer = StreamingCSVWriter::new(buf_writer);

    // Write header (column names from metadata)
    writer
        .write_header(&result.metadata)
        .map_err(|e| anyhow::anyhow!("Failed to write CSV header: {}", e))?;

    // Process rows in chunks for memory efficiency
    for chunk in result.rows.chunks(CHUNK_SIZE) {
        writer
            .write_chunk(chunk)
            .map_err(|e| anyhow::anyhow!("Failed to write CSV chunk: {}", e))?;
        pb.inc(chunk.len() as u64);
    }

    // Finalize (flush)
    writer
        .finalize()
        .map_err(|e| anyhow::anyhow!("Failed to finalize CSV file: {}", e))?;

    Ok(())
}

/// Export query result to JSON format using streaming writer (Issue #280)
///
/// Uses `StreamingJSONWriter` for memory-efficient chunked export.
/// Rows are processed in chunks to avoid building entire JSON array in memory.
#[cfg(feature = "state_machine")]
async fn export_to_json(
    result: &cqlite_core::query::result::QueryResult,
    file: &Path,
    _column_names: &[String],
    pb: &ProgressBar,
) -> Result<()> {
    use crate::output::{StreamingJSONWriter, StreamingWriter};

    // Chunk size for JSON streaming (smaller than Parquet since JSON is text-heavy)
    const CHUNK_SIZE: usize = 5_000;

    let output_file = File::create(file)
        .with_context(|| format!("Failed to create JSON file: {}", file.display()))?;
    let buf_writer = BufWriter::new(output_file);

    // Create streaming JSON writer with pretty-printing
    let mut writer = StreamingJSONWriter::new(buf_writer);

    // Write header (opening bracket and store column order)
    writer
        .write_header(&result.metadata)
        .map_err(|e| anyhow::anyhow!("Failed to write JSON header: {}", e))?;

    // Process rows in chunks for memory efficiency
    for chunk in result.rows.chunks(CHUNK_SIZE) {
        writer
            .write_chunk(chunk)
            .map_err(|e| anyhow::anyhow!("Failed to write JSON chunk: {}", e))?;
        pb.inc(chunk.len() as u64);
    }

    // Finalize (write closing bracket)
    writer
        .finalize()
        .map_err(|e| anyhow::anyhow!("Failed to finalize JSON file: {}", e))?;

    Ok(())
}

/// Export query result to CQL INSERT statements
#[cfg(feature = "state_machine")]
async fn export_to_cql(
    result: &cqlite_core::query::result::QueryResult,
    file: &Path,
    source: &str,
    column_names: &[String],
    pb: &ProgressBar,
) -> Result<()> {
    let output_file = File::create(file)
        .with_context(|| format!("Failed to create CQL file: {}", file.display()))?;
    let mut writer = BufWriter::new(output_file);

    // Extract table name from source
    let table_name = if source.to_uppercase().contains("FROM") {
        // Try to extract table name from SELECT query
        source
            .split_whitespace()
            .skip_while(|&word| word.to_uppercase() != "FROM")
            .nth(1)
            .unwrap_or("exported_table")
    } else {
        source
    };

    // Write header comment
    writeln!(writer, "-- CQL Export from CQLite")?;
    writeln!(writer, "-- Source: {source}")?;
    writeln!(writer, "-- Generated: {}", chrono::Utc::now().to_rfc3339())?;
    writeln!(writer, "-- Rows: {}", result.rows.len())?;
    writeln!(writer)?;

    // Write INSERT statements
    for (index, row) in result.rows.iter().enumerate() {
        pb.set_position(index as u64 + 1);

        let values: Vec<String> = column_names
            .iter()
            .map(|col| {
                row.get(col)
                    .map(|v| match v {
                        cqlite_core::Value::Text(s) => format!("'{}'", s.replace("'", "''")),
                        cqlite_core::Value::Null => "NULL".to_string(),
                        _ => v.to_string(),
                    })
                    .unwrap_or_else(|| "NULL".to_string())
            })
            .collect();

        writeln!(
            writer,
            "INSERT INTO {} ({}) VALUES ({});",
            table_name,
            column_names.join(", "),
            values.join(", ")
        )?;
    }

    writer
        .flush()
        .with_context(|| "Failed to flush CQL writer")?;

    Ok(())
}

/// Export query result to Parquet format using streaming writer (Issue #280)
///
/// Uses `StreamingParquetWriter` for memory-efficient chunked export.
/// Rows are processed in chunks (default 10,000) matching Parquet row group size.
#[cfg(feature = "state_machine")]
async fn export_to_parquet(
    result: &cqlite_core::query::result::QueryResult,
    file: &Path,
    _column_names: &[String],
    pb: &ProgressBar,
) -> Result<()> {
    use crate::output::{create_streaming_parquet_writer, StreamingWriter};

    // Default chunk size matches Parquet row group size
    const CHUNK_SIZE: usize = 10_000;

    pb.set_message("Initializing Parquet writer...");

    // Create file for streaming output
    let output_file = File::create(file)
        .with_context(|| format!("Failed to create Parquet file: {}", file.display()))?;

    // Create streaming writer with row group size = chunk size
    let mut writer = create_streaming_parquet_writer(output_file, &result.metadata, CHUNK_SIZE)
        .map_err(|e| anyhow::anyhow!("Failed to initialize Parquet writer: {}", e))?;

    // Write header (initializes Arrow schema)
    writer
        .write_header(&result.metadata)
        .map_err(|e| anyhow::anyhow!("Failed to write Parquet header: {}", e))?;

    pb.set_message("Streaming rows to Parquet...");

    // Process rows in chunks for memory efficiency
    for chunk in result.rows.chunks(CHUNK_SIZE) {
        writer
            .write_chunk(chunk)
            .map_err(|e| anyhow::anyhow!("Failed to write Parquet chunk: {}", e))?;
        pb.inc(chunk.len() as u64);
    }

    // Finalize (flush remaining rows, write footer)
    pb.set_message("Finalizing Parquet file...");
    writer
        .finalize()
        .map_err(|e| anyhow::anyhow!("Failed to finalize Parquet file: {}", e))?;

    Ok(())
}

/// Read and display SSTable directory or file data with schema
pub async fn read_sstable(
    sstable_path: &Path,
    schema_path: &Path,
    limit: Option<usize>,
    skip: Option<usize>,
    _generation: Option<u32>,
    format: OutputFormat,
    auto_detect: bool,
    cassandra_version: Option<String>,
) -> Result<()> {
    // Load schema from file (supports both .cql and .json)
    let schema = load_schema_file(schema_path, auto_detect, cassandra_version.as_deref())?;

    println!("🔍 Reading SSTable with REAL data parsing (no mocking!)");
    println!("📂 SSTable: {}", sstable_path.display());
    println!("📋 Schema: {}", schema_path.display());

    // Smart path resolution: if directory, find the Data.db file
    let actual_sstable_path = resolve_sstable_path(sstable_path)?;
    println!("📄 Data file: {}", actual_sstable_path.display());

    // Use Bulletproof SSTable Reader for universal format support
    println!("🚀 Using Bulletproof SSTable Reader (supports all Cassandra versions)");

    // Try bulletproof reader first
    let mut bulletproof_reader =
        BulletproofReader::open(&actual_sstable_path).with_context(|| {
            format!(
                "Failed to open SSTable with bulletproof reader: {}",
                actual_sstable_path.display()
            )
        })?;

    // Show format detection results
    let info = bulletproof_reader.info();
    println!(
        "📋 Detected format: {:?} (generation {}, size {})",
        info.format,
        info.generation_numeric().unwrap_or(0),
        info.size
    );

    if let Some(compression_info) = bulletproof_reader.compression_info() {
        println!(
            "📦 Compression: {} ({} byte chunks)",
            compression_info.algorithm, compression_info.chunk_length
        );
    }

    // Try to parse the SSTable data
    match bulletproof_reader.parse_sstable_data() {
        Ok(bulletproof_entries) => {
            println!(
                "✅ Successfully parsed {} entries with bulletproof reader",
                bulletproof_entries.len()
            );

            // Convert bulletproof entries to the format expected by the rest of the code
            let mut processed = 0;
            let mut displayed = 0;
            let skip_count = skip.unwrap_or(0);
            let limit_count = limit.unwrap_or(bulletproof_entries.len());

            let mut parsed_rows = Vec::new();
            let parser = RealDataParser::new(schema.clone());

            for entry in bulletproof_entries {
                if processed < skip_count {
                    processed += 1;
                    continue;
                }

                if displayed >= limit_count {
                    break;
                }

                // Create mock key and value from bulletproof entry for compatibility
                let key = entry.key.clone();
                let value =
                    cqlite_core::Value::Text(format!("{:?}|{}", entry.key, entry.format_info));

                match parser.parse_entry(&key, &value) {
                    Ok(parsed_row) => {
                        parsed_rows.push(parsed_row);
                        displayed += 1;
                    }
                    Err(e) => {
                        eprintln!("⚠️  Failed to parse row {}: {}", processed + 1, e);
                        // Show bulletproof data anyway
                        println!(
                            "📄 Raw bulletproof data: key='{:?}', info='{}'",
                            entry.key, entry.format_info
                        );
                    }
                }
                processed += 1;
            }

            // Display results
            match format {
                OutputFormat::Table => {
                    display_table_format(&parser.get_column_names(), &parsed_rows)
                }
                OutputFormat::Json => display_json_format(&parsed_rows)?,
                OutputFormat::Csv => display_csv_format(&parser.get_column_names(), &parsed_rows)?,
                OutputFormat::Parquet => {
                    return Err(anyhow::anyhow!("Parquet format is not supported for this command. Use --out json or --out csv instead."));
                }
            }

            println!(
                "\n✅ Bulletproof reader processed {processed} entries, displayed {displayed} rows"
            );
            return Ok(());
        }
        Err(e) => {
            println!("⚠️  Bulletproof parser still in development: {e}");
            println!("🔄 Falling back to raw data display...");

            // Show raw decompressed data as fallback
            match bulletproof_reader.read_raw_data(0, 1024) {
                Ok(data) => {
                    println!("\n📊 Raw SSTable data (first 1024 bytes):");
                    for (i, chunk) in data.chunks(16).enumerate() {
                        print!("  {:04x}: ", i * 16);
                        for byte in chunk {
                            print!("{byte:02x} ");
                        }
                        print!("  ");
                        for byte in chunk {
                            let c = if byte.is_ascii_graphic() || *byte == b' ' {
                                *byte as char
                            } else {
                                '.'
                            };
                            print!("{c}");
                        }
                        println!();
                    }

                    println!(
                        "\n🎯 This shows the bulletproof reader successfully decompressed the data!"
                    );
                    println!(
                        "💡 The parsing layer is still being implemented for your specific format."
                    );
                    return Ok(());
                }
                Err(e) => {
                    println!("❌ Bulletproof reader failed to read raw data: {e}");
                }
            }
        }
    }

    // If bulletproof reader fails completely, fall back to old reader
    println!("🔄 Falling back to legacy SSTable reader...");
    let config = cqlite_core::Config::default();
    let platform = Arc::new(cqlite_core::platform::Platform::new(&config).await?);
    let reader = SSTableReader::open(&actual_sstable_path, &config, platform)
        .await
        .with_context(|| format!("Failed to open SSTable: {}", actual_sstable_path.display()))?;

    // Create real data parser
    let parser = RealDataParser::new(schema.clone());

    // Get entries from SSTable
    let entries = reader.get_all_entries().await?;
    let mut processed = 0;
    let mut displayed = 0;
    let skip_count = skip.unwrap_or(0);
    let limit_count = limit.unwrap_or(entries.len());

    println!("📊 Found {} entries in SSTable", entries.len());

    let mut parsed_rows = Vec::new();

    for (_table_id, key, value) in entries {
        if processed < skip_count {
            processed += 1;
            continue;
        }

        if displayed >= limit_count {
            break;
        }

        // Parse the entry using real data parser
        match parser.parse_entry(&key, &value) {
            Ok(parsed_row) => {
                parsed_rows.push(parsed_row);
                displayed += 1;
            }
            Err(e) => {
                eprintln!("⚠️  Failed to parse row {}: {}", processed + 1, e);
            }
        }
        processed += 1;
    }

    // Display results based on format
    match format {
        OutputFormat::Table => display_table_format(&parser.get_column_names(), &parsed_rows),
        OutputFormat::Json => display_json_format(&parsed_rows)?,
        OutputFormat::Csv => display_csv_format(&parser.get_column_names(), &parsed_rows)?,
        OutputFormat::Parquet => {
            return Err(anyhow::anyhow!("Parquet format is not supported for this command. Use --out json or --out csv instead."));
        }
    }

    println!("\n✅ Processed {processed} entries, displayed {displayed} rows");
    println!("🎯 Data source: LIVE SSTable file (no mocking!)");

    Ok(())
}

/// Execute a CQL SELECT query against SSTable data (live data, no mocking!)
pub async fn execute_select_query(
    sstable_path: &Path,
    schema_path: &Path,
    query: &str,
    format: OutputFormat,
    auto_detect: bool,
    cassandra_version: Option<String>,
) -> Result<()> {
    // Load schema from file (supports both .cql and .json)
    let _schema = load_schema_file(schema_path, auto_detect, cassandra_version.as_deref())?;

    println!("🚀 Executing CQL query against LIVE SSTable data!");
    println!("📂 SSTable: {}", sstable_path.display());
    println!("📋 Schema: {}", schema_path.display());
    println!("🔍 Query: {query}");

    // Smart path resolution: if directory, find the Data.db file
    let actual_sstable_path = resolve_sstable_path(sstable_path)?;
    println!("📄 Data file: {}", actual_sstable_path.display());

    // Create query executor
    let executor = QueryExecutor::new(QueryExecutorConfig);

    // Execute the query
    let result = executor.execute_select(query).await?;

    // Display results
    match format {
        OutputFormat::Table => result.display_table(),
        OutputFormat::Json => result.display_json()?,
        OutputFormat::Csv => result.display_csv()?,
        OutputFormat::Parquet => {
            return Err(anyhow::anyhow!("Parquet format is not supported for this command. Use --out json or --out csv instead."));
        }
    }

    Ok(())
}

/// Resolve SSTable path: if directory, find the Data.db file
fn resolve_sstable_path(sstable_path: &Path) -> Result<PathBuf> {
    if sstable_path.is_file() {
        // If it's already a file, use it directly
        return Ok(sstable_path.to_path_buf());
    }

    if sstable_path.is_dir() {
        // If it's a directory, look for SSTable data files
        println!("📁 Directory detected, looking for SSTable files...");

        // Look for common SSTable data file patterns
        let patterns = ["*-Data.db", "*-big-Data.db", "nb-*-big-Data.db"];

        for pattern in &patterns {
            if let Ok(entries) = std::fs::read_dir(sstable_path) {
                for entry in entries.flatten() {
                    let file_name = entry.file_name();
                    let file_name_str = file_name.to_string_lossy();

                    // Match the pattern
                    if pattern.contains("*") {
                        let pattern_parts: Vec<&str> = pattern.split('*').collect();
                        if pattern_parts.len() == 2 {
                            let starts_with = pattern_parts[0];
                            let ends_with = pattern_parts[1];

                            if file_name_str.starts_with(starts_with)
                                && file_name_str.ends_with(ends_with)
                            {
                                let data_file = entry.path();
                                println!("✓ Found SSTable data file: {}", data_file.display());
                                return Ok(data_file);
                            }
                        } else if pattern_parts.len() == 3 {
                            let starts_with = pattern_parts[0];
                            let middle = pattern_parts[1];
                            let ends_with = pattern_parts[2];

                            if file_name_str.starts_with(starts_with)
                                && file_name_str.contains(middle)
                                && file_name_str.ends_with(ends_with)
                            {
                                let data_file = entry.path();
                                println!("✓ Found SSTable data file: {}", data_file.display());
                                return Ok(data_file);
                            }
                        }
                    }
                }
            }
        }

        return Err(anyhow::anyhow!(
            "No SSTable data files found in directory: {}\nLooked for: {}",
            sstable_path.display(),
            patterns.join(", ")
        ));
    }

    Err(anyhow::anyhow!(
        "Path is neither a file nor a directory: {}",
        sstable_path.display()
    ))
}

/// Load schema from JSON or CQL file
fn load_schema_file(
    schema_path: &Path,
    _auto_detect: bool,
    _cassandra_version: Option<&str>,
) -> Result<TableSchema> {
    let schema_content = std::fs::read_to_string(schema_path)
        .with_context(|| format!("Failed to read schema file: {}", schema_path.display()))?;

    println!("📋 Loading schema from: {}", schema_path.display());

    // Determine file type by extension
    let extension = schema_path
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("");

    match extension.to_lowercase().as_str() {
        "json" => {
            println!("📝 Parsing JSON schema format");
            // Parse JSON schema
            let json_schema: serde_json::Value = serde_json::from_str(&schema_content)
                .with_context(|| "Failed to parse JSON schema")?;

            // Convert JSON to TableSchema
            parse_json_schema(&json_schema)
        }
        "cql" | "sql" | "" => {
            println!("📝 Parsing CQL schema format");
            // Parse CQL schema
            parse_cql_schema(&schema_content).with_context(|| "Failed to parse CQL schema")
        }
        _ => Err(anyhow::anyhow!(
            "Unsupported schema file extension: .{}\nSupported formats: .json, .cql",
            extension
        )),
    }
}

/// Parse JSON schema format
fn parse_json_schema(json: &serde_json::Value) -> Result<TableSchema> {
    let keyspace = json["keyspace"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Missing keyspace in schema"))?;
    let table = json["table"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Missing table in schema"))?;

    let columns = json["columns"]
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("Missing columns in schema"))?;

    let mut schema_columns = Vec::new();
    let mut partition_keys = Vec::new();
    let mut clustering_columns = Vec::new();

    for (col_name, col_info) in columns {
        let col_obj = col_info
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("Invalid column definition for {}", col_name))?;

        let col_type = col_obj["type"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing type for column {}", col_name))?;
        let col_kind = col_obj["kind"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing kind for column {}", col_name))?;

        let column = Column {
            name: col_name.clone(),
            data_type: col_type.to_string(),
            nullable: true,   // Default to nullable
            default: None,    // No default value
            is_static: false, // SSTable metadata doesn't track static columns
        };

        match col_kind {
            "PartitionKey" => {
                partition_keys.push(KeyColumn {
                    name: col_name.clone(),
                    position: partition_keys.len(),
                    data_type: col_type.to_string(),
                });
            }
            "ClusteringColumn" => {
                clustering_columns.push(ClusteringColumn {
                    name: col_name.clone(),
                    position: clustering_columns.len(),
                    data_type: col_type.to_string(),
                    order: ClusteringOrder::Asc,
                });
            }
            "Regular" => {
                // Regular column - just add to columns list
            }
            _ => return Err(anyhow::anyhow!("Unknown column kind: {}", col_kind)),
        }

        schema_columns.push(column);
    }

    Ok(TableSchema {
        keyspace: keyspace.to_string(),
        table: table.to_string(),
        columns: schema_columns,
        partition_keys,
        clustering_keys: clustering_columns,
        comments: HashMap::new(),
    })
}

/// Display results in table format
fn display_table_format(column_names: &[String], rows: &[ParsedRow]) {
    use prettytable::{Cell, Row, Table};

    if rows.is_empty() {
        println!("📭 No results found");
        return;
    }

    let mut table = Table::new();

    // Add header
    let mut header = Row::empty();
    for column in column_names {
        header.add_cell(Cell::new(column));
    }
    table.add_row(header);

    // Add data rows
    for parsed_row in rows {
        let mut row = Row::empty();
        for column in column_names {
            let cell_value = parsed_row
                .get(column)
                .map(|v| v.to_string())
                .unwrap_or_else(|| "NULL".to_string());
            row.add_cell(Cell::new(&cell_value));
        }
        table.add_row(row);
    }

    println!("\n📊 Live SSTable Data Results:");
    println!("{}", "=".repeat(50));
    table.printstd();
}

/// Display results in JSON format
fn display_json_format(rows: &[ParsedRow]) -> Result<()> {
    let json_rows: Vec<serde_json::Value> = rows.iter().map(|row| row.to_json()).collect();

    println!("{}", serde_json::to_string_pretty(&json_rows)?);
    Ok(())
}

/// Display results in CSV format
fn display_csv_format(column_names: &[String], rows: &[ParsedRow]) -> Result<()> {
    let mut wtr = csv::Writer::from_writer(std::io::stdout());

    // Write header
    wtr.write_record(column_names)?;

    // Write data rows
    for parsed_row in rows {
        let mut record = Vec::new();
        for column in column_names {
            let cell_value = parsed_row
                .get(column)
                .map(|v| v.to_string())
                .unwrap_or_else(|| "NULL".to_string());
            record.push(cell_value);
        }
        wtr.write_record(&record)?;
    }

    wtr.flush()?;
    Ok(())
}

/// Export SSTable data to file
#[cfg(feature = "state_machine")]
pub async fn export_sstable(
    sstable_path: &Path,
    schema_path: &Path,
    output_path: &Path,
    format: ExportFormat,
) -> Result<()> {
    // Load schema with auto-detection
    let schema = load_schema_file(schema_path, false, None)?;

    let config = cqlite_core::Config::default();
    let platform = Arc::new(cqlite_core::platform::Platform::new(&config).await?);
    let reader = SSTableReader::open(sstable_path, &config, platform)
        .await
        .with_context(|| format!("Failed to open SSTable: {}", sstable_path.display()))?;

    let mut output_file = File::create(output_path)
        .with_context(|| format!("Failed to create output file: {}", output_path.display()))?;

    println!("Exporting SSTable: {}", sstable_path.display());
    println!("Output: {} ({})", output_path.display(), format);

    let pb = ProgressBar::new_spinner();
    pb.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} [{elapsed_precise}] {pos} rows exported")
            .unwrap(),
    );

    match format {
        ExportFormat::Json => export_as_json(&reader, &schema, &mut output_file, &pb).await,
        ExportFormat::Csv => export_as_csv(&reader, &schema, &mut output_file, &pb).await,
        ExportFormat::Parquet => {
            // Parquet writer manages its own file handle, so we drop the one we created
            drop(output_file);
            export_as_parquet(&reader, &schema, output_path, &pb).await
        }
        ExportFormat::Cql => export_as_cql(&reader, &schema, &mut output_file, &pb).await,
    }
}

/// Export SSTable data as JSON
#[cfg(feature = "state_machine")]
async fn export_as_json(
    reader: &SSTableReader,
    schema: &TableSchema,
    output_file: &mut File,
    pb: &ProgressBar,
) -> Result<()> {
    use std::io::Write;

    let parser = RealDataParser::new(schema.clone());
    let entries = reader.get_all_entries().await?;

    let mut json_objects = Vec::new();

    for (index, (_table_id, key, value)) in entries.iter().enumerate() {
        pb.set_position(index as u64);

        match parser.parse_entry(key, value) {
            Ok(parsed_row) => {
                json_objects.push(parsed_row.to_json());
            }
            Err(e) => {
                eprintln!("⚠️  Failed to parse row {}: {}", index + 1, e);
            }
        }
    }

    let json_output = serde_json::to_string_pretty(&json_objects)?;
    output_file.write_all(json_output.as_bytes())?;

    pb.finish_with_message(format!("Exported {} rows to JSON", json_objects.len()));
    Ok(())
}

/// Export SSTable data as CSV
#[cfg(feature = "state_machine")]
async fn export_as_csv(
    reader: &SSTableReader,
    schema: &TableSchema,
    output_file: &mut File,
    pb: &ProgressBar,
) -> Result<()> {
    let parser = RealDataParser::new(schema.clone());
    let entries = reader.get_all_entries().await?;

    let mut wtr = csv::Writer::from_writer(output_file);
    let column_names = parser.get_column_names();

    // Write header
    wtr.write_record(&column_names)?;

    let mut exported_count = 0;

    for (index, (_table_id, key, value)) in entries.iter().enumerate() {
        pb.set_position(index as u64);

        match parser.parse_entry(key, value) {
            Ok(parsed_row) => {
                let mut record = Vec::new();
                for column in &column_names {
                    let cell_value = parsed_row
                        .get(column)
                        .map(|v| v.to_string())
                        .unwrap_or_else(|| "NULL".to_string());
                    record.push(cell_value);
                }
                wtr.write_record(&record)?;
                exported_count += 1;
            }
            Err(e) => {
                eprintln!("⚠️  Failed to parse row {}: {}", index + 1, e);
            }
        }
    }

    wtr.flush()?;
    pb.finish_with_message(format!("Exported {exported_count} rows to CSV"));
    Ok(())
}

/// Export SSTable data as CQL INSERT statements
#[cfg(feature = "state_machine")]
async fn export_as_cql(
    reader: &SSTableReader,
    schema: &TableSchema,
    output_file: &mut File,
    pb: &ProgressBar,
) -> Result<()> {
    use std::io::Write;

    let parser = RealDataParser::new(schema.clone());
    let entries = reader.get_all_entries().await?;
    let column_names = parser.get_column_names();

    // Write header
    writeln!(output_file, "-- CQL Export from CQLite")?;
    writeln!(
        output_file,
        "-- Table: {}.{}",
        schema.keyspace, schema.table
    )?;
    writeln!(
        output_file,
        "-- Generated: {}",
        chrono::Utc::now().to_rfc3339()
    )?;
    writeln!(output_file)?;

    let mut exported_count = 0;

    for (index, (_table_id, key, value)) in entries.iter().enumerate() {
        pb.set_position(index as u64);

        match parser.parse_entry(key, value) {
            Ok(parsed_row) => {
                let values: Vec<String> = column_names
                    .iter()
                    .map(|col| {
                        parsed_row
                            .get(col)
                            .map(|_v| "NULL".to_string())
                            .unwrap_or_else(|| "NULL".to_string())
                    })
                    .collect();

                writeln!(
                    output_file,
                    "INSERT INTO {}.{} ({}) VALUES ({});",
                    schema.keyspace,
                    schema.table,
                    column_names.join(", "),
                    values.join(", ")
                )?;
                exported_count += 1;
            }
            Err(e) => {
                eprintln!("⚠️  Failed to parse row {}: {}", index + 1, e);
            }
        }
    }

    pb.finish_with_message(format!("Exported {exported_count} rows to CQL"));
    Ok(())
}

/// Export SSTable data as Parquet using StreamingParquetWriter
///
/// This function converts SSTable entries to QueryRow format and uses
/// the StreamingParquetWriter for memory-efficient export.
#[cfg(feature = "state_machine")]
async fn export_as_parquet(
    reader: &SSTableReader,
    schema: &TableSchema,
    output_path: &Path,
    pb: &ProgressBar,
) -> Result<()> {
    use crate::output::parquet::create_streaming_parquet_writer;
    use crate::output::StreamingWriter;

    let entries = reader.get_all_entries().await?;

    if entries.is_empty() {
        pb.finish_with_message("No data to export");
        // Create empty Parquet file
        let output_file = File::create(output_path)
            .with_context(|| format!("Failed to create output file: {}", output_path.display()))?;
        let metadata = build_query_metadata_from_schema(schema);
        let mut writer = create_streaming_parquet_writer(output_file, &metadata, 10_000)
            .map_err(|e| anyhow::anyhow!("Failed to create Parquet writer: {}", e))?;
        writer
            .finalize()
            .map_err(|e| anyhow::anyhow!("Failed to finalize Parquet: {}", e))?;
        return Ok(());
    }

    // Build QueryMetadata from schema
    let metadata = build_query_metadata_from_schema(schema);

    // Create streaming Parquet writer
    let output_file = File::create(output_path)
        .with_context(|| format!("Failed to create output file: {}", output_path.display()))?;
    let mut writer = create_streaming_parquet_writer(output_file, &metadata, 10_000)
        .map_err(|e| anyhow::anyhow!("Failed to create Parquet writer: {}", e))?;

    let mut chunk = Vec::with_capacity(1000);
    let mut exported_count = 0;

    for (index, (_table_id, row_key, value)) in entries.iter().enumerate() {
        pb.set_position(index as u64);

        // Convert SSTable entry to QueryRow
        let query_row = convert_entry_to_query_row(row_key, value, schema);
        chunk.push(query_row);

        if chunk.len() >= 1000 {
            writer
                .write_chunk(&chunk)
                .map_err(|e| anyhow::anyhow!("Failed to write Parquet chunk: {}", e))?;
            exported_count += chunk.len();
            chunk.clear();
        }
    }

    // Write remaining rows
    if !chunk.is_empty() {
        writer
            .write_chunk(&chunk)
            .map_err(|e| anyhow::anyhow!("Failed to write Parquet chunk: {}", e))?;
        exported_count += chunk.len();
    }

    writer
        .finalize()
        .map_err(|e| anyhow::anyhow!("Failed to finalize Parquet: {}", e))?;

    pb.finish_with_message(format!("Exported {} rows to Parquet", exported_count));
    Ok(())
}

/// Build QueryMetadata from TableSchema for Parquet export
#[cfg(feature = "state_machine")]
fn build_query_metadata_from_schema(schema: &TableSchema) -> cqlite_core::query::QueryMetadata {
    use cqlite_core::query::{ColumnInfo, QueryMetadata};

    let mut columns = Vec::new();
    let mut position = 0;

    // Add partition keys
    // Mark as nullable because direct SSTable export may not extract all key values
    // from the raw binary RowKey format
    for pk in &schema.partition_keys {
        columns.push(ColumnInfo {
            name: pk.name.clone(),
            data_type: parse_cql_type_string(&pk.data_type),
            nullable: true,
            position,
            table_name: Some(format!("{}.{}", schema.keyspace, schema.table)),
            cql_type: None,
        });
        position += 1;
    }

    // Add clustering keys
    // Mark as nullable because direct SSTable export may not extract all key values
    for ck in &schema.clustering_keys {
        columns.push(ColumnInfo {
            name: ck.name.clone(),
            data_type: parse_cql_type_string(&ck.data_type),
            nullable: true,
            position,
            table_name: Some(format!("{}.{}", schema.keyspace, schema.table)),
            cql_type: None,
        });
        position += 1;
    }

    // Add regular columns
    for col in &schema.columns {
        columns.push(ColumnInfo {
            name: col.name.clone(),
            data_type: parse_cql_type_string(&col.data_type),
            nullable: true,
            position,
            table_name: Some(format!("{}.{}", schema.keyspace, schema.table)),
            cql_type: None,
        });
        position += 1;
    }

    QueryMetadata {
        columns,
        ..Default::default()
    }
}

/// Parse CQL type string to DataType
#[cfg(feature = "state_machine")]
fn parse_cql_type_string(type_str: &str) -> cqlite_core::types::DataType {
    use cqlite_core::types::DataType;

    match type_str.to_lowercase().as_str() {
        "text" | "varchar" | "ascii" => DataType::Text,
        "int" | "integer" => DataType::Integer,
        "bigint" => DataType::BigInt,
        "smallint" => DataType::SmallInt,
        "tinyint" => DataType::TinyInt,
        "float" => DataType::Float32,
        "double" => DataType::Float,
        "boolean" => DataType::Boolean,
        "timestamp" => DataType::Timestamp,
        "date" => DataType::Timestamp, // Map date to Timestamp
        "time" => DataType::BigInt,    // Map time to BigInt (nanoseconds)
        "uuid" | "timeuuid" => DataType::Uuid,
        "blob" => DataType::Blob,
        "counter" => DataType::BigInt, // Map counter to BigInt
        "varint" => DataType::Blob,    // Map varint to Blob
        "decimal" => DataType::Text,   // Map decimal to Text (for now)
        s if s.starts_with("list") => DataType::List,
        s if s.starts_with("set") => DataType::Set,
        s if s.starts_with("map") => DataType::Map,
        s if s.starts_with("frozen") => DataType::Frozen,
        s if s.starts_with("tuple") => DataType::Tuple,
        _ => DataType::Text, // Default fallback
    }
}

/// Convert SSTable entry to QueryRow for Parquet export
#[cfg(feature = "state_machine")]
fn convert_entry_to_query_row(
    row_key: &cqlite_core::RowKey,
    value: &cqlite_core::Value,
    schema: &TableSchema,
) -> cqlite_core::query::QueryRow {
    use cqlite_core::query::{QueryRow, RowMetadata};
    use cqlite_core::Value;
    use std::collections::HashMap;

    let mut values: HashMap<String, Value> = HashMap::new();

    // Extract values from the Value (which is typically a Map for parsed rows)
    match value {
        Value::Map(pairs) => {
            // Each pair is (key_value, column_value)
            for (k, v) in pairs {
                if let Value::Text(col_name) = k {
                    values.insert(col_name.clone(), v.clone());
                }
            }
        }
        Value::Blob(data) => {
            // For raw blob data, assign to first regular column if available
            if let Some(first_col) = schema.columns.first() {
                values.insert(first_col.name.clone(), Value::Blob(data.clone()));
            }
        }
        Value::Text(s) => {
            if let Some(first_col) = schema.columns.first() {
                values.insert(first_col.name.clone(), Value::Text(s.clone()));
            }
        }
        other => {
            // For other value types, assign to first column
            if let Some(first_col) = schema.columns.first() {
                values.insert(first_col.name.clone(), other.clone());
            }
        }
    }

    // Ensure all schema columns have entries (use Null for missing)
    for pk in &schema.partition_keys {
        values.entry(pk.name.clone()).or_insert(Value::Null);
    }
    for ck in &schema.clustering_keys {
        values.entry(ck.name.clone()).or_insert(Value::Null);
    }
    for col in &schema.columns {
        values.entry(col.name.clone()).or_insert(Value::Null);
    }

    QueryRow {
        values,
        key: row_key.clone(),
        metadata: RowMetadata::default(),
    }
}

/// Enhanced SSTable reader with interactive features, progress tracking, and export
pub async fn read_sstable_enhanced(
    sstable_path: &Path,
    schema_path: &Path,
    limit: Option<usize>,
    skip: Option<usize>,
    generation: Option<u32>,
    format: OutputFormat,
    auto_detect: bool,
    cassandra_version: Option<String>,
    interactive: bool,
    progress: bool,
    export: Option<PathBuf>,
) -> Result<()> {
    println!("🚀 Enhanced SSTable Reader");
    println!("📂 SSTable: {}", sstable_path.display());
    println!("📋 Schema: {}", schema_path.display());

    if interactive {
        println!("🔍 Interactive mode enabled - use Ctrl+C to exit");
    }

    if progress {
        println!("📊 Progress tracking enabled");
    }

    if let Some(ref export_path) = export {
        println!("📤 Export enabled to: {}", export_path.display());
    }

    // Use the existing read_sstable function as base
    let result = read_sstable(
        sstable_path,
        schema_path,
        limit,
        skip,
        generation,
        format,
        auto_detect,
        cassandra_version,
    )
    .await;

    // TODO: Add interactive features when needed
    // TODO: Add enhanced progress tracking
    // TODO: Add export functionality

    if interactive {
        println!("\n🔍 Interactive mode features coming soon!");
        println!("   - Filter data interactively");
        println!("   - Navigate through pages");
        println!("   - Query-like interface");
    }

    if let Some(export_path) = export {
        println!("\n📤 Export functionality coming soon!");
        println!("   Target: {}", export_path.display());
        println!("   Formats: JSON, CSV, Parquet");
    }

    result
}

/// Validate SSTable format, integrity, and data consistency
pub async fn validate_sstable(
    sstable_path: &Path,
    schema_path: Option<&Path>,
    deep: bool,
    fix: bool,
    report_path: Option<&Path>,
) -> Result<()> {
    println!("🔍 SSTable Validation");
    println!("📂 SSTable: {}", sstable_path.display());

    if let Some(schema) = schema_path {
        println!("📋 Schema: {}", schema.display());
    }

    if deep {
        println!("🔬 Deep validation enabled (thorough but slower)");
    }

    if fix {
        println!("🔧 Auto-fix enabled for recoverable issues");
    }

    if let Some(report) = report_path {
        println!("📋 Report will be saved to: {}", report.display());
    }

    // Smart path resolution
    let actual_sstable_path = resolve_sstable_path(sstable_path)?;
    println!("📄 Data file: {}", actual_sstable_path.display());

    let mut issues_found = 0;
    let issues_fixed = 0;
    let mut validation_errors = Vec::new();

    // Basic file existence and readability
    println!("\n🔍 Basic file validation:");
    if !actual_sstable_path.exists() {
        let error = "❌ SSTable file does not exist";
        println!("{error}");
        validation_errors.push(error.to_string());
        issues_found += 1;
    } else {
        println!("✅ SSTable file exists");

        // Check file permissions
        match std::fs::metadata(&actual_sstable_path) {
            Ok(metadata) => {
                println!("✅ File readable (size: {} bytes)", metadata.len());

                if metadata.len() == 0 {
                    let error = "⚠️  Warning: SSTable file is empty";
                    println!("{error}");
                    validation_errors.push(error.to_string());
                    issues_found += 1;
                }
            }
            Err(e) => {
                let error = format!("❌ Cannot read file metadata: {e}");
                println!("{error}");
                validation_errors.push(error);
                issues_found += 1;
            }
        }
    }

    // Try loading with bulletproof reader
    println!("\n🔍 Format validation:");
    match BulletproofReader::open(&actual_sstable_path) {
        Ok(mut reader) => {
            println!("✅ SSTable format is readable");

            let info = reader.info();
            println!("   Format: {:?}", info.format);
            println!("   Generation: {}", info.generation_numeric().unwrap_or(0));
            println!("   Size: {} bytes", info.size);

            if let Some(compression) = reader.compression_info() {
                println!(
                    "   Compression: {} (chunk size: {})",
                    compression.algorithm, compression.chunk_length
                );
            }

            // Deep validation
            if deep {
                println!("\n🔬 Deep validation:");
                match reader.parse_sstable_data() {
                    Ok(entries) => {
                        println!("✅ Successfully parsed {} entries", entries.len());

                        // Validate data consistency if schema provided
                        if let Some(schema_path) = schema_path {
                            match load_schema_file(schema_path, true, None) {
                                Ok(schema) => {
                                    println!("✅ Schema loaded successfully");
                                    let parser = RealDataParser::new(schema);

                                    let mut parsing_errors = 0;
                                    for entry in entries.iter() {
                                        let key = entry.key.clone();
                                        let value =
                                            cqlite_core::Value::Text(format!("{:?}", entry.key));

                                        if parser.parse_entry(&key, &value).is_err() {
                                            parsing_errors += 1;
                                        }
                                    }

                                    if parsing_errors > 0 {
                                        let error = format!(
                                            "⚠️  {parsing_errors} entries failed schema validation"
                                        );
                                        println!("{error}");
                                        validation_errors.push(error);
                                        issues_found += parsing_errors;
                                    } else {
                                        println!("✅ All entries match schema");
                                    }
                                }
                                Err(e) => {
                                    let error =
                                        format!("⚠️  Could not load schema for validation: {e}");
                                    println!("{error}");
                                    validation_errors.push(error);
                                }
                            }
                        }
                    }
                    Err(e) => {
                        let error = format!("❌ Failed to parse SSTable data: {e}");
                        println!("{error}");
                        validation_errors.push(error);
                        issues_found += 1;
                    }
                }
            }
        }
        Err(e) => {
            let error = format!("❌ Cannot open SSTable with bulletproof reader: {e}");
            println!("{error}");
            validation_errors.push(error);
            issues_found += 1;
        }
    }

    // Generate report
    if let Some(report_path) = report_path {
        let mut report_content = format!(
            "# SSTable Validation Report\n\n\
            **File:** {}\n\
            **Validation Time:** {}\n\
            **Deep Validation:** {}\n\
            **Auto-fix Enabled:** {}\n\n\
            ## Summary\n\
            - Issues Found: {}\n\
            - Issues Fixed: {}\n\n\
            ## Details\n",
            sstable_path.display(),
            chrono::Utc::now().to_rfc3339(),
            deep,
            fix,
            issues_found,
            issues_fixed
        );

        for error in &validation_errors {
            report_content.push_str(&format!("- {error}\n"));
        }

        std::fs::write(report_path, report_content)
            .with_context(|| format!("Failed to write report to {}", report_path.display()))?;

        println!("\n📋 Validation report saved to: {}", report_path.display());
    }

    // Summary
    println!("\n📊 Validation Summary:");
    println!("   Issues found: {issues_found}");
    println!("   Issues fixed: {issues_fixed}");

    if issues_found == 0 {
        println!("✅ SSTable validation passed!");
    } else if fix && issues_fixed == issues_found {
        println!("🔧 All issues fixed!");
    } else {
        println!("⚠️  {} issues remain", issues_found - issues_fixed);
    }

    Ok(())
}

/// Analyze SSTable structure, statistics, and performance characteristics
pub async fn analyze_sstable(
    sstable_path: &Path,
    schema_path: Option<&Path>,
    detailed: bool,
    infer_schema: bool,
    report_path: Option<&Path>,
) -> Result<()> {
    println!("📊 SSTable Analysis");
    println!("📂 SSTable: {}", sstable_path.display());

    if let Some(schema) = schema_path {
        println!("📋 Schema: {}", schema.display());
    }

    if detailed {
        println!("🔍 Detailed analysis enabled");
    }

    if infer_schema {
        println!("🧠 Schema inference enabled");
    }

    if let Some(report) = report_path {
        println!("📋 Report will be saved to: {}", report.display());
    }

    // Smart path resolution
    let actual_sstable_path = resolve_sstable_path(sstable_path)?;
    println!("📄 Data file: {}", actual_sstable_path.display());

    let mut analysis_results = Vec::new();

    // File-level analysis
    println!("\n📁 File Analysis:");
    match std::fs::metadata(&actual_sstable_path) {
        Ok(metadata) => {
            let file_size = metadata.len();
            println!(
                "   File size: {} bytes ({:.2} MB)",
                file_size,
                file_size as f64 / 1_048_576.0
            );
            analysis_results.push(format!("File size: {file_size} bytes"));

            if let Ok(created) = metadata.created() {
                println!("   Created: {created:?}");
            }
            if let Ok(modified) = metadata.modified() {
                println!("   Modified: {modified:?}");
            }
        }
        Err(e) => {
            println!("❌ Cannot read file metadata: {e}");
            return Err(anyhow::anyhow!("File metadata not accessible"));
        }
    }

    // Format analysis
    println!("\n🔍 Format Analysis:");
    match BulletproofReader::open(&actual_sstable_path) {
        Ok(mut reader) => {
            let info = reader.info();
            println!("   Format: {:?}", info.format);
            println!("   Generation: {}", info.generation_numeric().unwrap_or(0));
            println!("   Size: {} bytes", info.size);

            analysis_results.push(format!("Format: {:?}", info.format));
            analysis_results.push(format!(
                "Generation: {}",
                info.generation_numeric().unwrap_or(0)
            ));

            if let Some(compression) = reader.compression_info() {
                println!("   Compression: {}", compression.algorithm);
                println!("   Chunk length: {} bytes", compression.chunk_length);
                analysis_results.push(format!("Compression: {}", compression.algorithm));
            } else {
                println!("   Compression: None");
                analysis_results.push("Compression: None".to_string());
            }

            // Data analysis
            println!("\n📊 Data Analysis:");
            match reader.parse_sstable_data() {
                Ok(entries) => {
                    let entry_count = entries.len();
                    println!("   Total entries: {entry_count}");
                    analysis_results.push(format!("Total entries: {entry_count}"));

                    if entry_count > 0 {
                        // Calculate average key size
                        let total_key_size: usize =
                            entries.iter().map(|e| format!("{:?}", e.key).len()).sum();
                        let avg_key_size = total_key_size / entry_count;
                        println!("   Average key size: {avg_key_size} bytes");
                        analysis_results.push(format!("Average key size: {avg_key_size} bytes"));

                        // Show sample entries
                        println!("\n📋 Sample Entries (first 5):");
                        for (i, entry) in entries.iter().take(5).enumerate() {
                            println!(
                                "   {}. Key: {:?}, Info: {}",
                                i + 1,
                                entry.key,
                                entry.format_info
                            );
                        }
                    }

                    // Detailed analysis
                    if detailed {
                        println!("\n🔍 Detailed Statistics:");

                        // Key distribution analysis
                        let mut key_lengths = entries
                            .iter()
                            .map(|e| format!("{:?}", e.key).len())
                            .collect::<Vec<_>>();
                        key_lengths.sort_unstable();

                        if !key_lengths.is_empty() {
                            let min_key_len = key_lengths[0];
                            let max_key_len = key_lengths[key_lengths.len() - 1];
                            let median_key_len = key_lengths[key_lengths.len() / 2];

                            println!(
                                "   Key length min/max/median: {min_key_len}/{max_key_len}/{median_key_len}"
                            );
                            analysis_results.push(format!(
                                "Key lengths - min: {min_key_len}, max: {max_key_len}, median: {median_key_len}"
                            ));
                        }

                        // TODO: Add more detailed statistics
                        println!("   📊 Advanced statistics coming soon!");
                    }

                    // Schema inference
                    if infer_schema {
                        println!("\n🧠 Schema Inference:");
                        // TODO: Implement schema inference logic
                        println!("   🚧 Schema inference coming soon!");
                        analysis_results
                            .push("Schema inference: Feature in development".to_string());
                    }
                }
                Err(e) => {
                    println!("❌ Failed to parse SSTable data: {e}");
                    analysis_results.push(format!("Parse error: {e}"));
                }
            }
        }
        Err(e) => {
            println!("❌ Cannot open SSTable: {e}");
            return Err(anyhow::anyhow!("Cannot analyze SSTable: {}", e));
        }
    }

    // Generate report
    if let Some(report_path) = report_path {
        let mut report_content = format!(
            "# SSTable Analysis Report\n\n\
            **File:** {}\n\
            **Analysis Time:** {}\n\
            **Detailed Analysis:** {}\n\
            **Schema Inference:** {}\n\n\
            ## Results\n",
            sstable_path.display(),
            chrono::Utc::now().to_rfc3339(),
            detailed,
            infer_schema
        );

        for result in &analysis_results {
            report_content.push_str(&format!("- {result}\n"));
        }

        std::fs::write(report_path, report_content)
            .with_context(|| format!("Failed to write report to {}", report_path.display()))?;

        println!("\n📋 Analysis report saved to: {}", report_path.display());
    }

    println!("\n✅ Analysis completed!");

    Ok(())
}

/// Benchmark SSTable read performance with various operations
pub async fn benchmark_sstable(
    sstable_path: &Path,
    schema_path: Option<&Path>,
    iterations: u32,
    operations: &str,
    report_path: Option<&Path>,
    memory_profile: bool,
) -> Result<()> {
    println!("🏁 SSTable Performance Benchmark");
    println!("📂 SSTable: {}", sstable_path.display());

    if let Some(schema) = schema_path {
        println!("📋 Schema: {}", schema.display());
    }

    println!("🔄 Iterations: {iterations}");
    println!("🎯 Operations: {operations}");

    if memory_profile {
        println!("📊 Memory profiling enabled");
    }

    if let Some(report) = report_path {
        println!("📋 Report will be saved to: {}", report.display());
    }

    // Smart path resolution
    let actual_sstable_path = resolve_sstable_path(sstable_path)?;
    println!("📄 Data file: {}", actual_sstable_path.display());

    let mut benchmark_results = Vec::new();

    // Parse operations list
    let ops: Vec<&str> = if operations == "all" {
        vec!["read", "scan", "query"]
    } else {
        operations.split(',').map(|s| s.trim()).collect()
    };

    println!("\n🚀 Starting benchmarks...");

    for op in &ops {
        println!("\n📊 Benchmarking operation: {op}");

        let mut times = Vec::new();
        let mut memory_usage = Vec::new();

        for i in 1..=iterations {
            print!("   Iteration {i}/{iterations}: ");

            let start_time = std::time::Instant::now();
            let initial_memory = if memory_profile {
                // TODO: Implement memory measurement
                0u64
            } else {
                0u64
            };

            // Perform the operation
            let result = match *op {
                "read" => benchmark_read_operation(&actual_sstable_path).await,
                "scan" => benchmark_scan_operation(&actual_sstable_path).await,
                "query" => benchmark_query_operation(&actual_sstable_path, schema_path).await,
                _ => {
                    println!("❌ Unknown operation: {op}");
                    continue;
                }
            };

            let elapsed = start_time.elapsed();
            let final_memory = if memory_profile {
                // TODO: Implement memory measurement
                0u64
            } else {
                0u64
            };

            match result {
                Ok(entries_processed) => {
                    println!(
                        "{}ms ({} entries)",
                        elapsed.as_millis(),
                        entries_processed
                    );
                    times.push(elapsed.as_millis() as f64);
                    if memory_profile {
                        memory_usage.push(final_memory.saturating_sub(initial_memory));
                    }
                }
                Err(e) => {
                    println!("❌ Failed: {e}");
                }
            }
        }

        // Calculate statistics
        if !times.is_empty() {
            times.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let min_time = times[0];
            let max_time = times[times.len() - 1];
            let avg_time = times.iter().sum::<f64>() / times.len() as f64;
            let median_time = times[times.len() / 2];

            println!("\n   📊 {op} Statistics:");
            println!("      Min time: {min_time:.2}ms");
            println!("      Max time: {max_time:.2}ms");
            println!("      Avg time: {avg_time:.2}ms");
            println!("      Median time: {median_time:.2}ms");

            benchmark_results.push(format!(
                "{op}: min={min_time:.2}ms, max={max_time:.2}ms, avg={avg_time:.2}ms, median={median_time:.2}ms"
            ));

            if memory_profile && !memory_usage.is_empty() {
                let avg_memory = memory_usage.iter().sum::<u64>() / memory_usage.len() as u64;
                println!("      Avg memory: {avg_memory} bytes");
                benchmark_results.push(format!("{op}: avg_memory={avg_memory}bytes"));
            }
        }
    }

    // Generate report
    if let Some(report_path) = report_path {
        let mut report_content = format!(
            "# SSTable Benchmark Report\n\n\
            **File:** {}\n\
            **Benchmark Time:** {}\n\
            **Iterations:** {}\n\
            **Operations:** {}\n\
            **Memory Profiling:** {}\n\n\
            ## Results\n",
            sstable_path.display(),
            chrono::Utc::now().to_rfc3339(),
            iterations,
            operations,
            memory_profile
        );

        for result in &benchmark_results {
            report_content.push_str(&format!("- {result}\n"));
        }

        std::fs::write(report_path, report_content)
            .with_context(|| format!("Failed to write report to {}", report_path.display()))?;

        println!("\n📋 Benchmark report saved to: {}", report_path.display());
    }

    println!("\n🏆 Benchmark completed!");

    Ok(())
}

/// Benchmark read operation (open and basic info)
async fn benchmark_read_operation(sstable_path: &Path) -> Result<usize> {
    let reader = BulletproofReader::open(sstable_path).with_context(|| "Failed to open SSTable")?;

    let _info = reader.info();
    Ok(1) // Return 1 as we processed the file info
}

/// Benchmark scan operation (iterate through all entries)
async fn benchmark_scan_operation(sstable_path: &Path) -> Result<usize> {
    let mut reader =
        BulletproofReader::open(sstable_path).with_context(|| "Failed to open SSTable")?;

    match reader.parse_sstable_data() {
        Ok(entries) => Ok(entries.len()),
        Err(_) => {
            // Fallback to basic read
            let _info = reader.info();
            Ok(0)
        }
    }
}

/// Benchmark query operation (with schema parsing if available)
async fn benchmark_query_operation(
    sstable_path: &Path,
    schema_path: Option<&Path>,
) -> Result<usize> {
    let mut reader =
        BulletproofReader::open(sstable_path).with_context(|| "Failed to open SSTable")?;

    match reader.parse_sstable_data() {
        Ok(entries) => {
            if let Some(schema_path) = schema_path {
                match load_schema_file(schema_path, true, None) {
                    Ok(schema) => {
                        let parser = RealDataParser::new(schema);
                        let mut parsed_count = 0;

                        for entry in &entries {
                            let key = entry.key.clone();
                            let value = cqlite_core::Value::Text(format!("{:?}", entry.key));

                            if parser.parse_entry(&key, &value).is_ok() {
                                parsed_count += 1;
                            }
                        }

                        Ok(parsed_count)
                    }
                    Err(_) => Ok(entries.len()), // Fallback to just entry count
                }
            } else {
                Ok(entries.len())
            }
        }
        Err(_) => Ok(0),
    }
}