cqlite-core 0.11.0

Core engine for CQLite — read Apache Cassandra 5.0 SSTables locally 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
//! Comprehensive Schema Discovery and Validation System
//!
//! This module provides advanced schema discovery capabilities that can extract, parse,
//! validate, and export schema information from SSTable files across different Cassandra versions.
//! It supports all complex data types including UDTs, collections, frozen types, and indexes.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::{
    parser::header::{CassandraVersion, SSTableHeader},
    platform::Platform,
    schema::{ClusteringColumn, UdtRegistry},
    types::Value,
    Config, Result,
};

/// Enhanced schema discovery configuration
#[derive(Debug, Clone)]
pub struct SchemaDiscoveryConfig {
    /// Maximum number of rows to sample for type inference
    pub max_sample_rows: usize,
    /// Enable aggressive type inference
    pub aggressive_inference: bool,
    /// Cache discovered schemas
    pub enable_schema_cache: bool,
    /// Schema cache TTL in seconds
    pub cache_ttl_seconds: u64,
    /// Enable schema versioning
    pub enable_versioning: bool,
    /// Maximum schema versions to keep
    pub max_versions: usize,
    /// Enable UDT discovery
    pub enable_udt_discovery: bool,
    /// Enable collection type analysis
    pub enable_collection_analysis: bool,
    /// Enable index discovery
    pub enable_index_discovery: bool,
    /// Enable cross-file validation
    pub enable_cross_file_validation: bool,
    /// Minimum confidence threshold for type inference
    pub min_confidence_threshold: f64,
}

impl Default for SchemaDiscoveryConfig {
    fn default() -> Self {
        Self {
            max_sample_rows: 2000,
            aggressive_inference: true,
            enable_schema_cache: true,
            cache_ttl_seconds: 3600, // 1 hour
            enable_versioning: true,
            max_versions: 10,
            enable_udt_discovery: true,
            enable_collection_analysis: true,
            enable_index_discovery: true,
            enable_cross_file_validation: true,
            min_confidence_threshold: 0.7,
        }
    }
}

/// Comprehensive schema information extracted from SSTables
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaInfo {
    /// Keyspace name
    pub keyspace: String,
    /// Table name
    pub table: String,
    /// Partition key columns with ordering
    pub partition_key: Vec<ColumnDefinition>,
    /// Clustering key columns with ordering
    pub clustering_keys: Vec<ClusteringColumn>,
    /// Regular data columns
    pub regular_columns: Vec<ColumnDefinition>,
    /// Static columns (if any)
    pub static_columns: Vec<ColumnDefinition>,
    /// Collection type definitions
    pub collection_types: HashMap<String, CollectionType>,
    /// User-defined type definitions
    pub user_defined_types: Vec<UDTDefinition>,
    /// Secondary index definitions
    pub indexes: Vec<IndexDefinition>,
    /// Table configuration options
    pub table_options: TableOptions,
    /// Schema discovery metadata
    pub metadata: SchemaMetadata,
}

/// Enhanced column definition with Cassandra-specific details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnDefinition {
    /// Column name
    pub name: String,
    /// CQL data type
    pub data_type: String,
    /// Parsed type information
    pub type_info: TypeInfo,
    /// Whether column accepts null values
    pub nullable: bool,
    /// Whether column is static (for clustering tables)
    pub is_static: bool,
    /// Default value if specified
    pub default_value: Option<Value>,
    /// Column position in table definition
    pub position: usize,
    /// Type inference confidence (0.0 - 1.0)
    pub confidence: f64,
}

/// Detailed type information for complex types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeInfo {
    /// Base type ID as string representation
    pub type_id: String,
    /// Type parameters for generic types
    pub type_params: Vec<String>,
    /// Whether type is frozen
    pub is_frozen: bool,
    /// Element type for collections
    pub element_type: Option<Box<TypeInfo>>,
    /// Key type for maps
    pub key_type: Option<Box<TypeInfo>>,
    /// Value type for maps
    pub value_type: Option<Box<TypeInfo>>,
    /// UDT field definitions if this is a UDT
    pub udt_fields: Option<Vec<UdtFieldInfo>>,
    /// Tuple element types if this is a tuple
    pub tuple_elements: Option<Vec<TypeInfo>>,
}

/// UDT field information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UdtFieldInfo {
    /// Field name
    pub name: String,
    /// Field type
    pub field_type: TypeInfo,
    /// Whether field is nullable
    pub nullable: bool,
}

/// Collection type definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionType {
    /// Collection kind (list, set, map)
    pub kind: CollectionKind,
    /// Element type for lists and sets
    pub element_type: Option<String>,
    /// Key type for maps
    pub key_type: Option<String>,
    /// Value type for maps
    pub value_type: Option<String>,
    /// Whether the collection is frozen
    pub is_frozen: bool,
}

/// Collection kind enumeration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CollectionKind {
    List,
    Set,
    Map,
    Tuple,
}

/// User-defined type definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UDTDefinition {
    /// UDT name
    pub name: String,
    /// Keyspace where UDT is defined
    pub keyspace: String,
    /// Field definitions
    pub fields: Vec<UdtFieldDefinition>,
    /// Version when UDT was created
    pub version: Option<u32>,
}

/// UDT field definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UdtFieldDefinition {
    /// Field name
    pub name: String,
    /// Field type
    pub field_type: String,
    /// Field position
    pub position: usize,
    /// Whether field is nullable
    pub nullable: bool,
}

/// Secondary index definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexDefinition {
    /// Index name
    pub name: String,
    /// Target column
    pub target_column: String,
    /// Index type
    pub index_type: IndexType,
    /// Index options
    pub options: HashMap<String, String>,
}

/// Index type enumeration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IndexType {
    /// Regular secondary index
    Secondary,
    /// Composite index
    Composite,
    /// Custom index
    Custom(String),
}

/// Table configuration options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableOptions {
    /// Compaction strategy
    pub compaction: Option<CompactionStrategy>,
    /// Compression options
    pub compression: Option<CompressionOptions>,
    /// Cache settings
    pub caching: Option<CachingOptions>,
    /// Bloom filter settings
    pub bloom_filter_fp_chance: Option<f64>,
    /// GC grace seconds
    pub gc_grace_seconds: Option<u32>,
    /// Default time to live
    pub default_time_to_live: Option<u32>,
    /// Memtable flush period
    pub memtable_flush_period_in_ms: Option<u32>,
    /// Additional properties
    pub additional_properties: HashMap<String, String>,
}

/// Compaction strategy information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompactionStrategy {
    /// Strategy class name
    pub class: String,
    /// Strategy options
    pub options: HashMap<String, String>,
}

/// Compression options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressionOptions {
    /// Compression algorithm
    pub algorithm: String,
    /// Chunk length
    pub chunk_length_kb: Option<u32>,
    /// CRC check chance
    pub crc_check_chance: Option<f32>,
}

/// Caching options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachingOptions {
    /// Keys cache setting
    pub keys: String,
    /// Rows cache setting
    pub rows_per_partition: String,
}

/// Schema discovery metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaMetadata {
    /// When schema was discovered
    pub discovered_at: SystemTime,
    /// Source SSTable files
    pub source_files: Vec<PathBuf>,
    /// Total rows sampled across all files
    pub total_rows_sampled: usize,
    /// Cassandra version detected
    pub cassandra_version: Option<CassandraVersion>,
    /// Discovery method used
    pub discovery_method: DiscoveryMethod,
    /// Schema version
    pub version: u32,
    /// Validation results
    pub validation_results: ValidationResults,
    /// Discovery performance metrics
    pub performance_metrics: DiscoveryMetrics,
}

/// Schema discovery method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DiscoveryMethod {
    /// Extracted from SSTable header metadata
    HeaderMetadata,
    /// Inferred from data sampling and analysis
    DataSampling,
    /// Combination of header metadata and data sampling
    Hybrid,
    /// From external schema definition file
    External,
}

/// Schema validation results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResults {
    /// Overall validation status
    pub status: ValidationStatus,
    /// Validation errors
    pub errors: Vec<ValidationError>,
    /// Validation warnings
    pub warnings: Vec<ValidationWarning>,
    /// Cross-file consistency results
    pub consistency_results: ConsistencyResults,
}

/// Validation status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ValidationStatus {
    /// Schema is valid and consistent
    Valid,
    /// Schema has minor issues but is usable
    ValidWithWarnings,
    /// Schema has significant issues
    Invalid,
    /// Schema validation failed
    ValidationFailed,
}

/// Validation error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// Error type
    pub error_type: ValidationErrorType,
    /// Error message
    pub message: String,
    /// Affected column or component
    pub component: Option<String>,
    /// Source file where error was found
    pub source_file: Option<PathBuf>,
}

/// Validation error types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationErrorType {
    /// Type mismatch between files
    TypeMismatch,
    /// Missing required component
    MissingComponent,
    /// Invalid type definition
    InvalidTypeDefinition,
    /// Constraint violation
    ConstraintViolation,
    /// UDT definition inconsistency
    UdtInconsistency,
    /// Index definition error
    IndexError,
}

/// Validation warning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationWarning {
    /// Warning type
    pub warning_type: ValidationWarningType,
    /// Warning message
    pub message: String,
    /// Affected component
    pub component: Option<String>,
}

/// Validation warning types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationWarningType {
    /// Low confidence type inference
    LowConfidence,
    /// Deprecated feature usage
    DeprecatedFeature,
    /// Version compatibility issue
    VersionCompatibility,
    /// Performance recommendation
    PerformanceRecommendation,
}

/// Cross-file consistency results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsistencyResults {
    /// Files analyzed
    pub files_analyzed: usize,
    /// Schema mismatches found
    pub schema_mismatches: usize,
    /// Type inconsistencies
    pub type_inconsistencies: Vec<TypeInconsistency>,
    /// UDT definition conflicts
    pub udt_conflicts: Vec<UdtConflict>,
}

/// Type inconsistency information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeInconsistency {
    /// Column name
    pub column_name: String,
    /// Conflicting type definitions
    pub conflicting_types: Vec<String>,
    /// Files with different definitions
    pub conflicting_files: Vec<PathBuf>,
}

/// UDT definition conflict
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UdtConflict {
    /// UDT name
    pub udt_name: String,
    /// Conflicting field definitions
    pub field_conflicts: Vec<FieldConflict>,
    /// Files with conflicts
    pub conflicting_files: Vec<PathBuf>,
}

/// UDT field conflict
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldConflict {
    /// Field name
    pub field_name: String,
    /// Conflicting types
    pub conflicting_types: Vec<String>,
}

/// Discovery performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveryMetrics {
    /// Total discovery time in milliseconds
    pub total_time_ms: u64,
    /// Time spent on header parsing
    pub header_parsing_time_ms: u64,
    /// Time spent on data sampling
    pub data_sampling_time_ms: u64,
    /// Time spent on type inference
    pub type_inference_time_ms: u64,
    /// Time spent on validation
    pub validation_time_ms: u64,
    /// Memory usage peak during discovery
    pub peak_memory_usage_bytes: usize,
}

/// Main schema discovery engine
#[derive(Debug)]
pub struct SchemaDiscoveryEngine {
    /// Configuration
    config: SchemaDiscoveryConfig,
    /// Platform abstraction
    #[allow(dead_code)]
    platform: Arc<Platform>,
    /// Core configuration
    #[allow(dead_code)]
    core_config: Config,
    /// Schema cache
    schema_cache: Arc<RwLock<HashMap<String, (SchemaInfo, SystemTime)>>>,
    /// UDT registry for managing discovered UDTs
    #[allow(dead_code)]
    udt_registry: Arc<RwLock<UdtRegistry>>,
    /// Type inference engine
    #[allow(dead_code)]
    type_inference: Arc<TypeInferenceEngine>,
    /// Schema validator
    #[allow(dead_code)]
    validator: Arc<SchemaValidator>,
    /// Schema exporter
    exporter: Arc<SchemaExporter>,
}

impl SchemaDiscoveryEngine {
    /// Create a new schema discovery engine
    pub async fn new(
        config: SchemaDiscoveryConfig,
        platform: Arc<Platform>,
        core_config: Config,
    ) -> Result<Self> {
        let udt_registry = Arc::new(RwLock::new(UdtRegistry::new()));
        let type_inference = Arc::new(TypeInferenceEngine::new());
        let validator = Arc::new(SchemaValidator::new());
        let exporter = Arc::new(SchemaExporter::new());

        Ok(Self {
            config,
            platform,
            core_config,
            schema_cache: Arc::new(RwLock::new(HashMap::new())),
            udt_registry,
            type_inference,
            validator,
            exporter,
        })
    }

    /// Discover schema from a collection of SSTable files
    pub async fn discover_schema(
        &self,
        keyspace: &str,
        table: &str,
        sstable_files: &[PathBuf],
    ) -> Result<SchemaInfo> {
        let cache_key = format!("{}.{}", keyspace, table);
        let start_time = SystemTime::now();

        // Check cache first
        if self.config.enable_schema_cache {
            if let Some(cached_schema) = self.get_cached_schema(&cache_key).await {
                return Ok(cached_schema);
            }
        }

        // Perform comprehensive schema discovery
        let mut discovery_context = DiscoveryContext::new(keyspace, table, sstable_files);

        // Phase 1: Extract metadata from headers
        self.extract_header_metadata(&mut discovery_context).await?;

        // Phase 2: Sample data for type inference
        self.sample_data_for_inference(&mut discovery_context)
            .await?;

        // Phase 3: Discover UDTs and complex types
        if self.config.enable_udt_discovery {
            self.discover_udts(&mut discovery_context).await?;
        }

        // Phase 4: Analyze collections
        if self.config.enable_collection_analysis {
            self.analyze_collection_types(&mut discovery_context)
                .await?;
        }

        // Phase 5: Discover indexes
        if self.config.enable_index_discovery {
            self.discover_indexes(&mut discovery_context).await?;
        }

        // Phase 6: Infer complete schema
        let schema_info = self.build_schema_info(&mut discovery_context).await?;

        // Phase 7: Schema validation (disabled - unimplemented)
        let validated_schema = schema_info;

        // Calculate discovery metrics
        let discovery_time = start_time.elapsed().unwrap_or(Duration::ZERO);
        let final_schema =
            self.add_performance_metrics(validated_schema, discovery_time, &discovery_context);

        // Cache the result
        if self.config.enable_schema_cache {
            self.cache_schema(cache_key, final_schema.clone()).await;
        }

        Ok(final_schema)
    }

    /// Generate CQL CREATE TABLE statement from schema
    pub async fn generate_cql(&self, schema: &SchemaInfo) -> Result<String> {
        self.exporter.generate_cql(schema).await
    }

    /// Export schema as JSON
    #[cfg(feature = "experimental")]
    pub async fn export_json(&self, schema: &SchemaInfo) -> Result<String> {
        self.exporter.export_json(schema).await
    }

    #[cfg(not(feature = "experimental"))]
    pub async fn export_json(&self, _schema: &SchemaInfo) -> Result<String> {
        Err(crate::error::Error::unsupported_format(
            "JSON export requires experimental feature",
        ))
    }

    /// Export schema as JSON with custom configuration
    #[cfg(feature = "experimental")]
    pub async fn export_json_with_config(
        &self,
        schema: &SchemaInfo,
        config: &crate::schema::json_exporter::JsonExportConfig,
    ) -> Result<String> {
        self.exporter.export_json_with_config(schema, config).await
    }

    #[cfg(not(feature = "experimental"))]
    pub async fn export_json_with_config<T>(
        &self,
        _schema: &SchemaInfo,
        _config: &T,
    ) -> Result<String> {
        Err(crate::error::Error::unsupported_format(
            "JSON export requires experimental feature",
        ))
    }

    /// Generate schema comparison report
    pub async fn compare_schemas(
        &self,
        schema1: &SchemaInfo,
        schema2: &SchemaInfo,
    ) -> Result<String> {
        self.exporter
            .generate_comparison_report(schema1, schema2)
            .await
    }

    // Private implementation methods follow...

    async fn get_cached_schema(&self, cache_key: &str) -> Option<SchemaInfo> {
        let cache = self.schema_cache.read().await;
        if let Some((schema, cached_at)) = cache.get(cache_key) {
            let ttl = Duration::from_secs(self.config.cache_ttl_seconds);
            if cached_at.elapsed().unwrap_or(Duration::MAX) < ttl {
                return Some(schema.clone());
            }
        }
        None
    }

    async fn cache_schema(&self, cache_key: String, schema: SchemaInfo) {
        let mut cache = self.schema_cache.write().await;
        cache.insert(cache_key, (schema, SystemTime::now()));

        // Simple cache eviction
        if cache.len() > 100 {
            let oldest_key = cache
                .iter()
                .min_by_key(|(_, (_, time))| time)
                .map(|(key, _)| key.clone());

            if let Some(key) = oldest_key {
                cache.remove(&key);
            }
        }
    }
}

/// Context for schema discovery process
#[derive(Debug)]
struct DiscoveryContext {
    #[allow(dead_code)]
    keyspace: String,
    #[allow(dead_code)]
    table: String,
    #[allow(dead_code)]
    source_files: Vec<PathBuf>,
    #[allow(dead_code)]
    headers: Vec<SSTableHeader>,
    #[allow(dead_code)]
    column_samples: HashMap<String, Vec<Value>>,
    #[allow(dead_code)]
    discovered_udts: HashMap<String, UDTDefinition>,
    #[allow(dead_code)]
    collection_types: HashMap<String, CollectionType>,
    #[allow(dead_code)]
    indexes: Vec<IndexDefinition>,
    #[allow(dead_code)]
    table_options: TableOptions,
    #[allow(dead_code)]
    total_rows_sampled: usize,
    #[allow(dead_code)]
    cassandra_version: Option<CassandraVersion>,
}

impl DiscoveryContext {
    fn new(keyspace: &str, table: &str, files: &[PathBuf]) -> Self {
        Self {
            keyspace: keyspace.to_string(),
            table: table.to_string(),
            source_files: files.to_vec(),
            headers: Vec::new(),
            column_samples: HashMap::new(),
            discovered_udts: HashMap::new(),
            collection_types: HashMap::new(),
            indexes: Vec::new(),
            table_options: TableOptions {
                compaction: None,
                compression: None,
                caching: None,
                bloom_filter_fp_chance: None,
                gc_grace_seconds: None,
                default_time_to_live: None,
                memtable_flush_period_in_ms: None,
                additional_properties: HashMap::new(),
            },
            total_rows_sampled: 0,
            cassandra_version: None,
        }
    }
}

/// Type inference engine for complex type analysis
#[derive(Debug)]
pub struct TypeInferenceEngine {
    // Implementation details for type inference
}

impl TypeInferenceEngine {
    fn new() -> Self {
        Self {}
    }

    /// Infer column type from sample values
    #[allow(dead_code)]
    fn infer_column_type<'a>(
        &'a self,
        samples: &'a [Value],
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<TypeInfo>> + 'a>> {
        Box::pin(async move {
            if samples.is_empty() {
                return Ok(TypeInfo {
                    type_id: "text".to_string(),
                    type_params: vec![],
                    is_frozen: false,
                    element_type: None,
                    key_type: None,
                    value_type: None,
                    udt_fields: None,
                    tuple_elements: None,
                });
            }

            // Count occurrences of each type
            let mut type_counts = HashMap::new();
            let mut has_complex_types = false;

            for sample in samples {
                let type_name = self.get_value_type_name(sample);
                *type_counts.entry(type_name.clone()).or_insert(0) += 1;

                // Check for complex types that need special handling
                if matches!(
                    sample,
                    Value::List(_)
                        | Value::Set(_)
                        | Value::Map(_)
                        | Value::Tuple(_)
                        | Value::Udt(_)
                ) {
                    has_complex_types = true;
                }
            }

            // Find the most common type
            let most_common_type = type_counts
                .iter()
                .max_by_key(|(_, count)| *count)
                .map(|(type_name, _)| type_name.clone())
                .unwrap_or_else(|| "text".to_string());

            // Handle complex types
            if has_complex_types {
                return self.infer_complex_type(samples, &most_common_type).await;
            }

            // Handle simple types
            Ok(TypeInfo {
                type_id: self.normalize_type_name(&most_common_type),
                type_params: vec![],
                is_frozen: false,
                element_type: None,
                key_type: None,
                value_type: None,
                udt_fields: None,
                tuple_elements: None,
            })
        })
    }

    /// Get type name for a Value
    fn get_value_type_name(&self, value: &Value) -> String {
        match value {
            Value::Null => "null".to_string(),
            Value::Text(_) => "text".to_string(),
            Value::Integer(_) => "int".to_string(),
            Value::BigInt(_) => "bigint".to_string(),
            Value::Counter(_) => "counter".to_string(),
            Value::Float(_) => "double".to_string(),
            Value::Boolean(_) => "boolean".to_string(),
            Value::Uuid(_) => "uuid".to_string(),
            Value::Timestamp(_) => "timestamp".to_string(),
            Value::Date(_) => "date".to_string(),
            Value::Time(_) => "time".to_string(),
            Value::Inet(_) => "inet".to_string(),
            Value::Blob(_) => "blob".to_string(),
            Value::List(_) => "list".to_string(),
            Value::Set(_) => "set".to_string(),
            Value::Map(_) => "map".to_string(),
            Value::Json(_) => "text".to_string(), // JSON stored as text
            Value::TinyInt(_) => "tinyint".to_string(),
            Value::SmallInt(_) => "smallint".to_string(),
            Value::Float32(_) => "float".to_string(),
            Value::Tuple(_) => "tuple".to_string(),
            Value::Udt(_) => "udt".to_string(),
            Value::Frozen(_) => "frozen".to_string(),
            Value::Varint(_) => "varint".to_string(),
            Value::Decimal { .. } => "decimal".to_string(),
            Value::Duration { .. } => "duration".to_string(),
            Value::Tombstone(_) => "tombstone".to_string(),
        }
    }

    /// Normalize type name to CQL standard
    fn normalize_type_name(&self, type_name: &str) -> String {
        match type_name.to_lowercase().as_str() {
            "int" | "integer" => "int".to_string(),
            "bigint" | "biginteger" => "bigint".to_string(),
            "double" | "float64" => "double".to_string(),
            "float" | "float32" => "float".to_string(),
            "text" | "varchar" | "string" => "text".to_string(),
            "bool" | "boolean" => "boolean".to_string(),
            "timestamp" | "datetime" => "timestamp".to_string(),
            "blob" | "bytes" => "blob".to_string(),
            "uuid" => "uuid".to_string(),
            "decimal" => "decimal".to_string(),
            "varint" => "varint".to_string(),
            "tinyint" => "tinyint".to_string(),
            "smallint" => "smallint".to_string(),
            "duration" => "duration".to_string(),
            _ => type_name.to_string(),
        }
    }

    /// Infer complex type information
    async fn infer_complex_type(&self, samples: &[Value], base_type: &str) -> Result<TypeInfo> {
        match base_type {
            "list" => self.infer_list_type(samples).await,
            "set" => self.infer_set_type(samples).await,
            "map" => self.infer_map_type(samples).await,
            "tuple" => self.infer_tuple_type(samples).await,
            "udt" => self.infer_udt_type(samples).await,
            _ => Ok(TypeInfo {
                type_id: self.normalize_type_name(base_type),
                type_params: vec![],
                is_frozen: false,
                element_type: None,
                key_type: None,
                value_type: None,
                udt_fields: None,
                tuple_elements: None,
            }),
        }
    }

    /// Infer list type from samples
    async fn infer_list_type(&self, samples: &[Value]) -> Result<TypeInfo> {
        let mut element_samples = Vec::new();

        for sample in samples {
            if let Value::List(elements) = sample {
                element_samples.extend(elements.iter().cloned());
            }
        }

        let element_type = if !element_samples.is_empty() {
            Box::new(self.infer_column_type(&element_samples).await?)
        } else {
            Box::new(TypeInfo {
                type_id: "text".to_string(),
                type_params: vec![],
                is_frozen: false,
                element_type: None,
                key_type: None,
                value_type: None,
                udt_fields: None,
                tuple_elements: None,
            })
        };

        Ok(TypeInfo {
            type_id: "list".to_string(),
            type_params: vec![element_type.type_id.clone()],
            is_frozen: false,
            element_type: Some(element_type),
            key_type: None,
            value_type: None,
            udt_fields: None,
            tuple_elements: None,
        })
    }

    /// Infer set type from samples
    async fn infer_set_type(&self, samples: &[Value]) -> Result<TypeInfo> {
        let mut element_samples = Vec::new();

        for sample in samples {
            if let Value::Set(elements) = sample {
                element_samples.extend(elements.iter().cloned());
            }
        }

        let element_type = if !element_samples.is_empty() {
            Box::new(self.infer_column_type(&element_samples).await?)
        } else {
            Box::new(TypeInfo {
                type_id: "text".to_string(),
                type_params: vec![],
                is_frozen: false,
                element_type: None,
                key_type: None,
                value_type: None,
                udt_fields: None,
                tuple_elements: None,
            })
        };

        Ok(TypeInfo {
            type_id: "set".to_string(),
            type_params: vec![element_type.type_id.clone()],
            is_frozen: false,
            element_type: Some(element_type),
            key_type: None,
            value_type: None,
            udt_fields: None,
            tuple_elements: None,
        })
    }

    /// Infer map type from samples
    async fn infer_map_type(&self, samples: &[Value]) -> Result<TypeInfo> {
        let mut key_samples = Vec::new();
        let mut value_samples = Vec::new();

        for sample in samples {
            if let Value::Map(map) = sample {
                for (key, value) in map {
                    key_samples.push(key.clone());
                    value_samples.push(value.clone());
                }
            }
        }

        let key_type = if !key_samples.is_empty() {
            Box::new(self.infer_column_type(&key_samples).await?)
        } else {
            Box::new(TypeInfo {
                type_id: "text".to_string(),
                type_params: vec![],
                is_frozen: false,
                element_type: None,
                key_type: None,
                value_type: None,
                udt_fields: None,
                tuple_elements: None,
            })
        };

        let value_type = if !value_samples.is_empty() {
            Box::new(self.infer_column_type(&value_samples).await?)
        } else {
            Box::new(TypeInfo {
                type_id: "text".to_string(),
                type_params: vec![],
                is_frozen: false,
                element_type: None,
                key_type: None,
                value_type: None,
                udt_fields: None,
                tuple_elements: None,
            })
        };

        Ok(TypeInfo {
            type_id: "map".to_string(),
            type_params: vec![key_type.type_id.clone(), value_type.type_id.clone()],
            is_frozen: false,
            element_type: None,
            key_type: Some(key_type),
            value_type: Some(value_type),
            udt_fields: None,
            tuple_elements: None,
        })
    }

    /// Infer tuple type from samples
    async fn infer_tuple_type(&self, samples: &[Value]) -> Result<TypeInfo> {
        let mut max_elements = 0;
        let mut element_positions: Vec<Vec<Value>> = Vec::new();

        // Collect samples by position
        for sample in samples {
            if let Value::Tuple(elements) = sample {
                max_elements = max_elements.max(elements.len());

                // Ensure we have enough position vectors
                while element_positions.len() < elements.len() {
                    element_positions.push(Vec::new());
                }

                // Add elements to their position vectors
                for (i, element) in elements.iter().enumerate() {
                    element_positions[i].push(element.clone());
                }
            }
        }

        // Infer type for each position
        let mut tuple_elements = Vec::new();
        for position_samples in element_positions {
            if !position_samples.is_empty() {
                let element_type = self.infer_column_type(&position_samples).await?;
                tuple_elements.push(element_type);
            }
        }

        let type_params: Vec<String> = tuple_elements.iter().map(|t| t.type_id.clone()).collect();

        Ok(TypeInfo {
            type_id: "tuple".to_string(),
            type_params,
            is_frozen: false,
            element_type: None,
            key_type: None,
            value_type: None,
            udt_fields: None,
            tuple_elements: Some(tuple_elements),
        })
    }

    /// Infer UDT type from samples (basic implementation)
    async fn infer_udt_type(&self, samples: &[Value]) -> Result<TypeInfo> {
        // UDT inference requires more sophisticated analysis
        // This is a basic implementation - would need expansion for production
        let mut field_map: HashMap<String, Vec<Value>> = HashMap::new();

        for sample in samples {
            if let Value::Udt(udt_value) = sample {
                for field in &udt_value.fields {
                    if let Some(field_value) = &field.value {
                        field_map
                            .entry(field.name.clone())
                            .or_default()
                            .push(field_value.clone());
                    }
                }
            }
        }

        let mut udt_fields = Vec::new();
        for (field_name, field_samples) in field_map {
            let field_type = self.infer_column_type(&field_samples).await?;
            udt_fields.push(UdtFieldInfo {
                name: field_name,
                field_type,
                nullable: true, // Assume nullable for safety
            });
        }

        Ok(TypeInfo {
            type_id: "udt".to_string(),
            type_params: vec![],
            is_frozen: false,
            element_type: None,
            key_type: None,
            value_type: None,
            udt_fields: Some(udt_fields),
            tuple_elements: None,
        })
    }
}

/// Schema validator for consistency checking
#[derive(Debug)]
pub struct SchemaValidator {
    // Implementation details for validation
}

impl SchemaValidator {
    fn new() -> Self {
        Self {}
    }
}

/// Schema exporter for generating output formats
#[derive(Debug)]
pub struct SchemaExporter {
    // Implementation details for export
}

impl SchemaExporter {
    fn new() -> Self {
        Self {}
    }

    /// Generate CQL CREATE TABLE statement
    async fn generate_cql(&self, schema: &SchemaInfo) -> Result<String> {
        let mut cql = String::new();

        // CREATE TABLE statement
        cql.push_str(&format!(
            "CREATE TABLE {}.{} (\n",
            schema.keyspace, schema.table
        ));

        // Partition key columns
        for column in &schema.partition_key {
            cql.push_str(&format!(
                "    {} {},\n",
                column.name,
                self.format_column_type(&column.type_info)
            ));
        }

        // Clustering key columns
        for clustering in &schema.clustering_keys {
            cql.push_str(&format!(
                "    {} {},\n",
                clustering.name, clustering.data_type
            ));
        }

        // Static columns
        for column in &schema.static_columns {
            let static_modifier = if column.is_static { " STATIC" } else { "" };
            cql.push_str(&format!(
                "    {} {}{},\n",
                column.name,
                self.format_column_type(&column.type_info),
                static_modifier
            ));
        }

        // Regular columns
        for column in &schema.regular_columns {
            cql.push_str(&format!(
                "    {} {},\n",
                column.name,
                self.format_column_type(&column.type_info)
            ));
        }

        // Primary key definition
        if !schema.partition_key.is_empty() {
            let partition_keys: Vec<String> = schema
                .partition_key
                .iter()
                .map(|col| col.name.clone())
                .collect();

            if schema.clustering_keys.is_empty() {
                cql.push_str(&format!("    PRIMARY KEY ({})", partition_keys.join(", ")));
            } else {
                let clustering_keys: Vec<String> = schema
                    .clustering_keys
                    .iter()
                    .map(|col| col.name.clone())
                    .collect();

                if partition_keys.len() == 1 {
                    cql.push_str(&format!(
                        "    PRIMARY KEY ({}, {})",
                        partition_keys[0],
                        clustering_keys.join(", ")
                    ));
                } else {
                    cql.push_str(&format!(
                        "    PRIMARY KEY (({}) {})",
                        partition_keys.join(", "),
                        clustering_keys.join(", ")
                    ));
                }
            }
        }

        cql.push_str("\n);");

        // Add clustering order if specified
        if !schema.clustering_keys.is_empty() {
            let mut clustering_order = Vec::new();
            for clustering in &schema.clustering_keys {
                let order = match clustering.order {
                    crate::schema::ClusteringOrder::Asc => "ASC",
                    crate::schema::ClusteringOrder::Desc => "DESC",
                };
                clustering_order.push(format!("{} {}", clustering.name, order));
            }

            if clustering_order.iter().any(|o| o.contains("DESC")) {
                cql.push_str(&format!(
                    "\nWITH CLUSTERING ORDER BY ({});",
                    clustering_order.join(", ")
                ));
            }
        }

        // Add table options if present
        let mut options = Vec::new();

        if let Some(compaction) = &schema.table_options.compaction {
            options.push(format!("compaction = {{'class': '{}'}}", compaction.class));
        }

        if let Some(compression) = &schema.table_options.compression {
            options.push(format!(
                "compression = {{'algorithm': '{}'}}",
                compression.algorithm
            ));
        }

        if let Some(gc_grace) = schema.table_options.gc_grace_seconds {
            options.push(format!("gc_grace_seconds = {}", gc_grace));
        }

        if let Some(ttl) = schema.table_options.default_time_to_live {
            options.push(format!("default_time_to_live = {}", ttl));
        }

        if !options.is_empty() {
            if !cql.ends_with(';') {
                cql.push_str(" WITH ");
            } else {
                cql.pop(); // Remove the semicolon
                cql.push_str("\nWITH ");
            }
            cql.push_str(&options.join("\n  AND "));
            cql.push(';');
        }

        Ok(cql)
    }

    /// Format column type information for CQL
    #[allow(clippy::only_used_in_recursion)]
    fn format_column_type(&self, type_info: &TypeInfo) -> String {
        match type_info.type_id.as_str() {
            "list" => {
                if let Some(element_type) = &type_info.element_type {
                    format!("list<{}>", self.format_column_type(element_type))
                } else {
                    "list<text>".to_string()
                }
            }
            "set" => {
                if let Some(element_type) = &type_info.element_type {
                    format!("set<{}>", self.format_column_type(element_type))
                } else {
                    "set<text>".to_string()
                }
            }
            "map" => {
                if let (Some(key_type), Some(value_type)) =
                    (&type_info.key_type, &type_info.value_type)
                {
                    format!(
                        "map<{}, {}>",
                        self.format_column_type(key_type),
                        self.format_column_type(value_type)
                    )
                } else {
                    "map<text, text>".to_string()
                }
            }
            "tuple" => {
                if let Some(tuple_elements) = &type_info.tuple_elements {
                    let element_types: Vec<String> = tuple_elements
                        .iter()
                        .map(|t| self.format_column_type(t))
                        .collect();
                    format!("tuple<{}>", element_types.join(", "))
                } else {
                    "tuple<text>".to_string()
                }
            }
            "frozen" => {
                if let Some(element_type) = &type_info.element_type {
                    format!("frozen<{}>", self.format_column_type(element_type))
                } else {
                    "frozen<text>".to_string()
                }
            }
            _ => type_info.type_id.clone(),
        }
    }

    /// Export schema as JSON
    #[cfg(feature = "experimental")]
    async fn export_json(&self, schema: &SchemaInfo) -> Result<String> {
        self.export_json_with_config(
            schema,
            &crate::schema::json_exporter::JsonExportConfig::default(),
        )
        .await
    }

    /// Export schema as JSON with custom configuration
    #[cfg(feature = "experimental")]
    async fn export_json_with_config(
        &self,
        schema: &SchemaInfo,
        config: &crate::schema::json_exporter::JsonExportConfig,
    ) -> Result<String> {
        let exporter = crate::schema::json_exporter::JsonExporter::with_config(config.clone());
        exporter.export_schema_info(schema)
    }

    #[cfg(not(feature = "experimental"))]
    #[allow(dead_code)]
    async fn export_json(&self, _schema: &SchemaInfo) -> Result<String> {
        Err(crate::error::Error::unsupported_format(
            "JSON export requires experimental feature",
        ))
    }

    #[cfg(not(feature = "experimental"))]
    #[allow(dead_code)]
    async fn export_json_with_config<T>(
        &self,
        _schema: &SchemaInfo,
        _config: &T, // Generic placeholder for when experimental feature is disabled
    ) -> Result<String> {
        Err(crate::error::Error::unsupported_format(
            "JSON export requires experimental feature",
        ))
    }

    /// Export schema as compact JSON (minimal format)
    #[allow(dead_code)]
    #[cfg(feature = "experimental")]
    async fn export_json_compact(&self, schema: &SchemaInfo) -> Result<String> {
        let config = crate::schema::json_exporter::JsonExportConfig {
            format_variant: crate::schema::json_exporter::JsonFormat::Compact,
            include_metadata: false,
            include_performance_metrics: false,
            include_type_details: false,
            pretty_format: false,
            ..Default::default()
        };
        self.export_json_with_config(schema, &config).await
    }

    /// Export schema for API documentation (OpenAPI-compatible format)
    #[allow(dead_code)]
    #[cfg(feature = "experimental")]
    async fn export_json_openapi(&self, schema: &SchemaInfo) -> Result<String> {
        let config = crate::schema::json_exporter::JsonExportConfig {
            format_variant: crate::schema::json_exporter::JsonFormat::OpenApi,
            include_documentation: true,
            include_type_details: true,
            include_metadata: false,
            ..Default::default()
        };
        self.export_json_with_config(schema, &config).await
    }

    /// Export schema for data pipeline tools
    #[allow(dead_code)]
    #[cfg(feature = "experimental")]
    async fn export_json_pipeline(&self, schema: &SchemaInfo) -> Result<String> {
        let config = crate::schema::json_exporter::JsonExportConfig {
            format_variant: crate::schema::json_exporter::JsonFormat::DataPipeline,
            include_type_details: true,
            include_table_options: false,
            include_performance_metrics: true,
            ..Default::default()
        };
        self.export_json_with_config(schema, &config).await
    }

    /// Generate schema comparison report
    async fn generate_comparison_report(
        &self,
        _schema1: &SchemaInfo,
        _schema2: &SchemaInfo,
    ) -> Result<String> {
        // TODO: Implement schema comparison logic for production
        // This is a minimal viable stub to enable compilation and basic testing
        // Real implementation would compare schemas and generate detailed reports
        Ok(
            "Schema comparison not yet implemented. Both schemas analyzed as equivalent."
                .to_string(),
        )
    }
}

// Additional implementation methods for SchemaDiscoveryEngine
impl SchemaDiscoveryEngine {
    async fn extract_header_metadata(&self, context: &mut DiscoveryContext) -> Result<()> {
        // Parse headers from each source file
        for file_path in &context.source_files.clone() {
            match self.parse_sstable_header(file_path).await {
                Ok(header) => {
                    context.headers.push(header.clone());

                    // Update Cassandra version if not set
                    if context.cassandra_version.is_none() {
                        context.cassandra_version = Some(header.cassandra_version);
                    }
                }
                Err(e) => {
                    // Log error but continue with other files
                    log::warn!("Failed to parse header from {:?}: {}", file_path, e);
                }
            }
        }

        Ok(())
    }

    /// Parse SSTable header from file
    async fn parse_sstable_header(&self, file_path: &std::path::Path) -> Result<SSTableHeader> {
        use crate::storage::sstable::reader::SSTableReader;

        let reader =
            SSTableReader::open(file_path, &self.core_config, self.platform.clone()).await?;
        Ok(reader.header().clone())
    }

    async fn sample_data_for_inference(&self, context: &mut DiscoveryContext) -> Result<()> {
        let mut total_sampled = 0;

        for file_path in &context.source_files.clone() {
            if total_sampled >= self.config.max_sample_rows {
                break;
            }

            match self
                .sample_sstable_data(file_path, self.config.max_sample_rows - total_sampled)
                .await
            {
                Ok(samples) => {
                    total_sampled += samples.len();

                    // Organize samples by column
                    for row in samples {
                        for (column_name, value) in row {
                            context
                                .column_samples
                                .entry(column_name)
                                .or_default()
                                .push(value);
                        }
                    }
                }
                Err(e) => {
                    log::warn!("Failed to sample data from {:?}: {}", file_path, e);
                }
            }
        }

        context.total_rows_sampled = total_sampled;
        Ok(())
    }

    /// Sample data from an SSTable file
    async fn sample_sstable_data(
        &self,
        file_path: &std::path::Path,
        max_rows: usize,
    ) -> Result<Vec<HashMap<String, Value>>> {
        use crate::storage::sstable::reader::SSTableReader;

        let reader =
            SSTableReader::open(file_path, &self.core_config, self.platform.clone()).await?;
        let header = reader.header();
        let column_names: Vec<String> = header.columns.iter().map(|col| col.name.clone()).collect();

        // Get all entries and sample up to max_rows
        let all_entries = reader.get_all_entries().await?;

        // TODO(Issue #190): SSTableReader returns Vec<(TableId, RowKey, Value)> where Value
        // is typically a single parsed value per entry. This differs from BulletproofReader's
        // SSTableEntry which had `values: Vec<Value>` for multiple columns per row.
        // For schema discovery type inference, we map each entry's Value to the first column
        // as a conservative approach. Future enhancement: use scan() with schema-aware parsing
        // or enhance SSTableReader to return row-level multi-column data.
        let samples: Vec<HashMap<String, Value>> = all_entries
            .into_iter()
            .take(max_rows)
            .filter_map(|(_table_id, _row_key, value)| {
                let mut row_data = HashMap::new();

                // Map the single Value to the first column for type inference
                // This works for simple tables and provides data for type analysis
                if !column_names.is_empty() {
                    row_data.insert(column_names[0].clone(), value);
                } else {
                    // If no column names are available, skip this entry
                    return None;
                }

                Some(row_data)
            })
            .collect();

        Ok(samples)
    }

    async fn discover_udts(&self, context: &mut DiscoveryContext) -> Result<()> {
        // UDT discovery from headers and data samples
        for header in &context.headers {
            for column_def in &header.columns {
                // Check if column type indicates a UDT
                if self.is_udt_type(&column_def.column_type) {
                    let udt_name = self.extract_udt_name(&column_def.column_type);

                    if !context.discovered_udts.contains_key(&udt_name) {
                        // Create basic UDT definition from type info
                        let udt_def = UDTDefinition {
                            name: udt_name.clone(),
                            keyspace: context.keyspace.clone(),
                            fields: self.parse_udt_fields(&column_def.column_type),
                            version: Some(1),
                        };

                        context.discovered_udts.insert(udt_name, udt_def);
                    }
                }
            }
        }

        // Analyze UDT usage in sample data
        for (column_name, samples) in &context.column_samples {
            for sample in samples {
                if let Value::Udt(udt_map) = sample {
                    // Infer UDT structure from data
                    let udt_name = format!("{}_udt", column_name); // Generate name if not available

                    if !context.discovered_udts.contains_key(&udt_name) {
                        let mut fields = Vec::new();

                        for (position, field) in udt_map.fields.iter().enumerate() {
                            let field_def = UdtFieldDefinition {
                                name: field.name.clone(),
                                field_type: "text".to_string(), // Would need type inference here
                                position,
                                nullable: true,
                            };
                            fields.push(field_def);
                        }

                        let udt_def = UDTDefinition {
                            name: udt_name.clone(),
                            keyspace: context.keyspace.clone(),
                            fields,
                            version: Some(1),
                        };

                        context.discovered_udts.insert(udt_name, udt_def);
                    }
                }
            }
        }

        Ok(())
    }

    /// Check if a type string indicates a UDT
    fn is_udt_type(&self, type_str: &str) -> bool {
        // UDTs are typically not standard CQL types
        !matches!(
            type_str.to_lowercase().as_str(),
            "text"
                | "varchar"
                | "ascii"
                | "int"
                | "bigint"
                | "smallint"
                | "tinyint"
                | "float"
                | "double"
                | "boolean"
                | "timestamp"
                | "date"
                | "time"
                | "uuid"
                | "timeuuid"
                | "blob"
                | "varint"
                | "decimal"
                | "duration"
                | "inet"
                | "counter"
        ) && !type_str.starts_with("list<")
            && !type_str.starts_with("set<")
            && !type_str.starts_with("map<")
            && !type_str.starts_with("tuple<")
            && !type_str.starts_with("frozen<")
    }

    /// Extract UDT name from type string
    fn extract_udt_name(&self, type_str: &str) -> String {
        // Remove any qualifiers and get base type name
        type_str.split('<').next().unwrap_or(type_str).to_string()
    }

    /// Parse UDT field definitions from type string
    fn parse_udt_fields(&self, _type_str: &str) -> Vec<UdtFieldDefinition> {
        // This is a simplified implementation
        // Real UDT parsing would require more sophisticated type parsing
        vec![UdtFieldDefinition {
            name: "field".to_string(),
            field_type: "text".to_string(),
            position: 0,
            nullable: true,
        }]
    }

    async fn analyze_collection_types(&self, context: &mut DiscoveryContext) -> Result<()> {
        // Analyze collection types from headers
        for header in &context.headers {
            for column_def in &header.columns {
                if let Some(collection_type) = self.parse_collection_type(&column_def.column_type) {
                    context
                        .collection_types
                        .insert(column_def.name.clone(), collection_type);
                }
            }
        }

        // Analyze collection types from sample data
        for (column_name, samples) in &context.column_samples {
            let mut detected_collections = Vec::new();

            for sample in samples {
                match sample {
                    Value::List(elements) => {
                        let element_type = if !elements.is_empty() {
                            self.infer_element_type(elements)
                        } else {
                            "text".to_string()
                        };

                        detected_collections.push(CollectionType {
                            kind: CollectionKind::List,
                            element_type: Some(element_type),
                            key_type: None,
                            value_type: None,
                            is_frozen: false,
                        });
                    }
                    Value::Set(elements) => {
                        let element_type = if !elements.is_empty() {
                            self.infer_element_type(elements)
                        } else {
                            "text".to_string()
                        };

                        detected_collections.push(CollectionType {
                            kind: CollectionKind::Set,
                            element_type: Some(element_type),
                            key_type: None,
                            value_type: None,
                            is_frozen: false,
                        });
                    }
                    Value::Map(map) => {
                        let (key_type, value_type) = if !map.is_empty() {
                            let keys: Vec<Value> = map.iter().map(|(k, _)| k.clone()).collect();
                            let values: Vec<Value> = map.iter().map(|(_, v)| v.clone()).collect();
                            (
                                self.infer_element_type(&keys),
                                self.infer_element_type(&values),
                            )
                        } else {
                            ("text".to_string(), "text".to_string())
                        };

                        detected_collections.push(CollectionType {
                            kind: CollectionKind::Map,
                            element_type: None,
                            key_type: Some(key_type),
                            value_type: Some(value_type),
                            is_frozen: false,
                        });
                    }
                    Value::Tuple(_) => {
                        detected_collections.push(CollectionType {
                            kind: CollectionKind::Tuple,
                            element_type: None,
                            key_type: None,
                            value_type: None,
                            is_frozen: false,
                        });
                    }
                    _ => {}
                }
            }

            // Use the most common collection type for this column
            if let Some(collection_type) =
                self.select_most_common_collection_type(detected_collections)
            {
                context
                    .collection_types
                    .insert(column_name.clone(), collection_type);
            }
        }

        Ok(())
    }

    /// Parse collection type from type string
    fn parse_collection_type(&self, type_str: &str) -> Option<CollectionType> {
        let lower_type = type_str.to_lowercase();

        if lower_type.starts_with("list<") {
            let element_type = self.extract_inner_type(type_str, "list<");
            Some(CollectionType {
                kind: CollectionKind::List,
                element_type: Some(element_type),
                key_type: None,
                value_type: None,
                is_frozen: false,
            })
        } else if lower_type.starts_with("set<") {
            let element_type = self.extract_inner_type(type_str, "set<");
            Some(CollectionType {
                kind: CollectionKind::Set,
                element_type: Some(element_type),
                key_type: None,
                value_type: None,
                is_frozen: false,
            })
        } else if lower_type.starts_with("map<") {
            let (key_type, value_type) = self.extract_map_types(type_str);
            Some(CollectionType {
                kind: CollectionKind::Map,
                element_type: None,
                key_type: Some(key_type),
                value_type: Some(value_type),
                is_frozen: false,
            })
        } else if lower_type.starts_with("tuple<") {
            Some(CollectionType {
                kind: CollectionKind::Tuple,
                element_type: None,
                key_type: None,
                value_type: None,
                is_frozen: false,
            })
        } else if lower_type.starts_with("frozen<") {
            // Parse the inner type and mark as frozen
            if let Some(mut inner_collection) =
                self.parse_collection_type(&self.extract_inner_type(type_str, "frozen<"))
            {
                inner_collection.is_frozen = true;
                Some(inner_collection)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Extract inner type from generic type string
    fn extract_inner_type(&self, type_str: &str, _prefix: &str) -> String {
        if let Some(start) = type_str.find('<') {
            if let Some(end) = type_str.rfind('>') {
                return type_str[start + 1..end].to_string();
            }
        }
        "text".to_string()
    }

    /// Extract key and value types from map type string
    fn extract_map_types(&self, type_str: &str) -> (String, String) {
        if let Some(start) = type_str.find('<') {
            if let Some(end) = type_str.rfind('>') {
                let inner = &type_str[start + 1..end];
                if let Some(comma_pos) = inner.find(',') {
                    let key_type = inner[..comma_pos].trim().to_string();
                    let value_type = inner[comma_pos + 1..].trim().to_string();
                    return (key_type, value_type);
                }
            }
        }
        ("text".to_string(), "text".to_string())
    }

    /// Infer element type from a collection of values
    fn infer_element_type(&self, elements: &[Value]) -> String {
        if elements.is_empty() {
            return "text".to_string();
        }

        // Count type occurrences
        let mut type_counts = HashMap::new();
        for element in elements {
            let type_name = match element {
                Value::Text(_) => "text",
                Value::Integer(_) => "int",
                Value::BigInt(_) => "bigint",
                Value::Float(_) => "double",
                Value::Boolean(_) => "boolean",
                Value::Uuid(_) => "uuid",
                Value::Timestamp(_) => "timestamp",
                Value::Blob(_) => "blob",
                _ => "text",
            };
            *type_counts.entry(type_name).or_insert(0) += 1;
        }

        // Return most common type
        type_counts
            .into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(type_name, _)| type_name.to_string())
            .unwrap_or_else(|| "text".to_string())
    }

    /// Select the most common collection type from detected types
    fn select_most_common_collection_type(
        &self,
        mut types: Vec<CollectionType>,
    ) -> Option<CollectionType> {
        if types.is_empty() {
            return None;
        }

        // For simplicity, just return the first type
        // In a real implementation, you'd want to find the most common type
        types.sort_by(|a, b| format!("{:?}", a.kind).cmp(&format!("{:?}", b.kind)));
        types.into_iter().next()
    }

    async fn discover_indexes(&self, context: &mut DiscoveryContext) -> Result<()> {
        // Index discovery from SSTable metadata and headers
        for header in &context.headers {
            // Check for index-related metadata in the header
            if let Some(index_info) = self.extract_index_info_from_header(header) {
                context.indexes.extend(index_info);
            }
        }

        // Infer potential indexes from column usage patterns
        for (column_name, samples) in &context.column_samples {
            // Check if column has characteristics that suggest indexing
            if self.should_suggest_index(column_name, samples) {
                let index_def = IndexDefinition {
                    name: format!("{}_idx", column_name),
                    target_column: column_name.clone(),
                    index_type: IndexType::Secondary,
                    options: HashMap::new(),
                };

                // Only add if not already present
                if !context
                    .indexes
                    .iter()
                    .any(|idx| idx.target_column == *column_name)
                {
                    context.indexes.push(index_def);
                }
            }
        }

        Ok(())
    }

    /// Extract index information from SSTable header
    fn extract_index_info_from_header(
        &self,
        _header: &SSTableHeader,
    ) -> Option<Vec<IndexDefinition>> {
        // SSTable headers don't typically contain direct index information
        // This would need to be enhanced with actual index discovery logic
        // from Cassandra's system tables or index files
        None
    }

    /// Determine if a column should have an index based on usage patterns
    fn should_suggest_index(&self, column_name: &str, samples: &[Value]) -> bool {
        // Simple heuristics for index suggestion

        // 1. Columns with "id" in the name (common lookup pattern)
        if column_name.to_lowercase().contains("id") {
            return true;
        }

        // 2. Columns with high cardinality (many unique values)
        let unique_values: std::collections::HashSet<_> = samples.iter().collect();
        let cardinality_ratio = unique_values.len() as f64 / samples.len() as f64;
        if cardinality_ratio > 0.7 && samples.len() > 10 {
            return true;
        }

        // 3. Columns that look like foreign keys or references
        if column_name.to_lowercase().ends_with("_id")
            || column_name.to_lowercase().ends_with("_ref")
            || column_name.to_lowercase().contains("email")
            || column_name.to_lowercase().contains("username")
        {
            return true;
        }

        // 4. UUID columns (often used for lookups)
        if samples.iter().any(|v| matches!(v, Value::Uuid(_))) {
            return true;
        }

        false
    }

    async fn build_schema_info(&self, context: &mut DiscoveryContext) -> Result<SchemaInfo> {
        let mut partition_key = Vec::new();
        let mut clustering_keys = Vec::new();
        let mut regular_columns = Vec::new();
        let mut static_columns = Vec::new();

        // Extract column information from headers
        let mut position = 0;
        for header in &context.headers {
            for column_def in &header.columns {
                // Infer type from header and samples
                let samples = context
                    .column_samples
                    .get(&column_def.name)
                    .cloned()
                    .unwrap_or_default();
                let type_info = self
                    .type_inference
                    .infer_column_type(&samples)
                    .await
                    .unwrap_or_else(|_| TypeInfo {
                        type_id: column_def.column_type.clone(),
                        type_params: vec![],
                        is_frozen: false,
                        element_type: None,
                        key_type: None,
                        value_type: None,
                        udt_fields: None,
                        tuple_elements: None,
                    });

                let confidence = self.calculate_type_confidence(&samples, &type_info);

                let column = ColumnDefinition {
                    name: column_def.name.clone(),
                    data_type: column_def.column_type.clone(),
                    type_info,
                    nullable: true,   // Assume nullable unless proven otherwise
                    is_static: false, // Would need additional logic to detect static columns
                    default_value: None,
                    position,
                    confidence,
                };

                // Classify column based on position and naming patterns
                if self.is_partition_key_column(&column_def.name, position) {
                    partition_key.push(column);
                } else if self.is_clustering_column(&column_def.name, position) {
                    clustering_keys.push(ClusteringColumn {
                        name: column_def.name.clone(),
                        data_type: column_def.column_type.clone(),
                        position: clustering_keys.len(), // Use current size as position
                        order: crate::schema::ClusteringOrder::Asc, // Default to ascending
                    });
                } else if column.is_static {
                    static_columns.push(column);
                } else {
                    regular_columns.push(column);
                }

                position += 1;
            }
        }

        // If no partition key was found, assume first column is partition key
        if partition_key.is_empty() && !regular_columns.is_empty() {
            let first_column = regular_columns.remove(0);
            partition_key.push(first_column);
        }

        // Build validation results
        let validation_results = ValidationResults {
            status: self.determine_validation_status(&partition_key, &regular_columns),
            errors: Vec::new(), // Would be populated by actual validation
            warnings: self.generate_validation_warnings(&partition_key, &regular_columns),
            consistency_results: ConsistencyResults {
                files_analyzed: context.source_files.len(),
                schema_mismatches: 0,
                type_inconsistencies: Vec::new(),
                udt_conflicts: Vec::new(),
            },
        };

        Ok(SchemaInfo {
            keyspace: context.keyspace.clone(),
            table: context.table.clone(),
            partition_key,
            clustering_keys,
            regular_columns,
            static_columns,
            collection_types: context.collection_types.clone(),
            user_defined_types: context.discovered_udts.values().cloned().collect(),
            indexes: context.indexes.clone(),
            table_options: context.table_options.clone(),
            metadata: SchemaMetadata {
                discovered_at: std::time::SystemTime::now(),
                source_files: context.source_files.clone(),
                total_rows_sampled: context.total_rows_sampled,
                cassandra_version: context.cassandra_version,
                discovery_method: DiscoveryMethod::Hybrid,
                version: 1,
                validation_results,
                performance_metrics: DiscoveryMetrics {
                    total_time_ms: 0, // Will be filled in later
                    header_parsing_time_ms: 0,
                    data_sampling_time_ms: 0,
                    type_inference_time_ms: 0,
                    validation_time_ms: 0,
                    peak_memory_usage_bytes: 0,
                },
            },
        })
    }

    /// Calculate confidence score for type inference
    fn calculate_type_confidence(&self, samples: &[Value], type_info: &TypeInfo) -> f64 {
        if samples.is_empty() {
            return 0.0;
        }

        let matching_samples = samples
            .iter()
            .filter(|sample| self.value_matches_type(sample, type_info))
            .count();

        matching_samples as f64 / samples.len() as f64
    }

    /// Check if a value matches the expected type
    fn value_matches_type(&self, value: &Value, type_info: &TypeInfo) -> bool {
        #[allow(clippy::match_like_matches_macro)]
        match (value, type_info.type_id.as_str()) {
            (Value::Text(_), "text") => true,
            (Value::Integer(_), "int") => true,
            (Value::BigInt(_), "bigint") => true,
            (Value::Float(_), "double") => true,
            (Value::Boolean(_), "boolean") => true,
            (Value::Uuid(_), "uuid") => true,
            (Value::Timestamp(_), "timestamp") => true,
            (Value::Blob(_), "blob") => true,
            (Value::List(_), "list") => true,
            (Value::Set(_), "set") => true,
            (Value::Map(_), "map") => true,
            (Value::Tuple(_), "tuple") => true,
            (Value::Udt(_), "udt") => true,
            _ => false,
        }
    }

    /// Heuristic to determine if a column is a partition key
    fn is_partition_key_column(&self, column_name: &str, position: usize) -> bool {
        // Simple heuristics - in practice this would be more sophisticated
        position == 0
            || column_name.to_lowercase().contains("key")
            || column_name.to_lowercase() == "id"
            || column_name.to_lowercase().ends_with("_id")
    }

    /// Heuristic to determine if a column is a clustering column
    fn is_clustering_column(&self, column_name: &str, position: usize) -> bool {
        // Simple heuristics
        (position == 1 && !self.is_partition_key_column(column_name, position))
            || column_name.to_lowercase().contains("time")
            || column_name.to_lowercase().contains("date")
            || column_name.to_lowercase().contains("order")
    }

    /// Determine overall validation status
    fn determine_validation_status(
        &self,
        partition_key: &[ColumnDefinition],
        regular_columns: &[ColumnDefinition],
    ) -> ValidationStatus {
        // Check for basic requirements
        if partition_key.is_empty() {
            return ValidationStatus::Invalid;
        }

        // Check confidence levels
        let all_columns: Vec<_> = partition_key.iter().chain(regular_columns.iter()).collect();
        let low_confidence_count = all_columns
            .iter()
            .filter(|col| col.confidence < 0.7)
            .count();

        if low_confidence_count > all_columns.len() / 2 {
            ValidationStatus::Invalid
        } else if low_confidence_count > 0 {
            ValidationStatus::ValidWithWarnings
        } else {
            ValidationStatus::Valid
        }
    }

    /// Generate validation warnings
    fn generate_validation_warnings(
        &self,
        _partition_key: &[ColumnDefinition],
        regular_columns: &[ColumnDefinition],
    ) -> Vec<ValidationWarning> {
        let mut warnings = Vec::new();

        // Check for low confidence type inference
        for column in regular_columns {
            if column.confidence < 0.7 {
                warnings.push(ValidationWarning {
                    warning_type: ValidationWarningType::LowConfidence,
                    message: format!(
                        "Low confidence type inference for column '{}': {:.2}",
                        column.name, column.confidence
                    ),
                    component: Some(column.name.clone()),
                });
            }
        }

        warnings
    }

    fn add_performance_metrics(
        &self,
        mut schema: SchemaInfo,
        discovery_time: Duration,
        _context: &DiscoveryContext,
    ) -> SchemaInfo {
        schema.metadata.performance_metrics = DiscoveryMetrics {
            total_time_ms: discovery_time.as_millis() as u64,
            header_parsing_time_ms: 0, // TODO: Track individual phase times
            data_sampling_time_ms: 0,
            type_inference_time_ms: 0,
            validation_time_ms: 0,
            peak_memory_usage_bytes: 0, // TODO: Track memory usage
        };
        schema
    }
}

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

    #[tokio::test]
    async fn test_schema_discovery_engine_creation() {
        let config = SchemaDiscoveryConfig::default();
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.unwrap());

        let engine = SchemaDiscoveryEngine::new(config, platform, core_config)
            .await
            .unwrap();

        // Test basic functionality
        assert!(engine.schema_cache.read().await.is_empty());
    }

    #[test]
    fn test_discovery_context_creation() {
        let files = vec![PathBuf::from("test.sst")];
        let context = DiscoveryContext::new("test_ks", "test_table", &files);

        assert_eq!(context.keyspace, "test_ks");
        assert_eq!(context.table, "test_table");
        assert_eq!(context.source_files.len(), 1);
    }

    #[test]
    fn test_schema_info_serialization() {
        let schema_info = SchemaInfo {
            keyspace: "test".to_string(),
            table: "users".to_string(),
            partition_key: Vec::new(),
            clustering_keys: Vec::new(),
            regular_columns: Vec::new(),
            static_columns: Vec::new(),
            collection_types: HashMap::new(),
            user_defined_types: Vec::new(),
            indexes: Vec::new(),
            table_options: TableOptions {
                compaction: None,
                compression: None,
                caching: None,
                bloom_filter_fp_chance: None,
                gc_grace_seconds: None,
                default_time_to_live: None,
                memtable_flush_period_in_ms: None,
                additional_properties: HashMap::new(),
            },
            metadata: SchemaMetadata {
                discovered_at: std::time::UNIX_EPOCH,
                source_files: Vec::new(),
                total_rows_sampled: 0,
                cassandra_version: None,
                discovery_method: DiscoveryMethod::HeaderMetadata,
                version: 1,
                validation_results: ValidationResults {
                    status: ValidationStatus::Valid,
                    errors: Vec::new(),
                    warnings: Vec::new(),
                    consistency_results: ConsistencyResults {
                        files_analyzed: 0,
                        schema_mismatches: 0,
                        type_inconsistencies: Vec::new(),
                        udt_conflicts: Vec::new(),
                    },
                },
                performance_metrics: DiscoveryMetrics {
                    total_time_ms: 0,
                    header_parsing_time_ms: 0,
                    data_sampling_time_ms: 0,
                    type_inference_time_ms: 0,
                    validation_time_ms: 0,
                    peak_memory_usage_bytes: 0,
                },
            },
        };

        // Test that it can be serialized and deserialized
        let json = serde_json::to_string(&schema_info).unwrap();
        let deserialized: SchemaInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.keyspace, "test");
        assert_eq!(deserialized.table, "users");
    }

    #[tokio::test]
    async fn test_extract_header_metadata_stub() {
        let config = SchemaDiscoveryConfig::default();
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.unwrap());

        let engine = SchemaDiscoveryEngine::new(config, platform, core_config)
            .await
            .unwrap();

        let mut context = DiscoveryContext::new("test_ks", "test_table", &[]);

        // Test that the stub method executes without panicking
        let result = engine.extract_header_metadata(&mut context).await;
        assert!(
            result.is_ok(),
            "extract_header_metadata stub should return Ok(())"
        );
    }

    #[tokio::test]
    async fn test_sample_data_for_inference_stub() {
        let config = SchemaDiscoveryConfig::default();
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.unwrap());

        let engine = SchemaDiscoveryEngine::new(config, platform, core_config)
            .await
            .unwrap();

        let mut context = DiscoveryContext::new("test_ks", "test_table", &[]);

        // Test that the stub method executes without panicking
        let result = engine.sample_data_for_inference(&mut context).await;
        assert!(
            result.is_ok(),
            "sample_data_for_inference stub should return Ok(())"
        );
    }

    #[tokio::test]
    async fn test_generate_comparison_report_stub() {
        let exporter = SchemaExporter::new();

        let schema_info = SchemaInfo {
            keyspace: "test".to_string(),
            table: "users".to_string(),
            partition_key: Vec::new(),
            clustering_keys: Vec::new(),
            regular_columns: Vec::new(),
            static_columns: Vec::new(),
            collection_types: HashMap::new(),
            user_defined_types: Vec::new(),
            indexes: Vec::new(),
            table_options: TableOptions {
                compaction: None,
                compression: None,
                caching: None,
                bloom_filter_fp_chance: None,
                gc_grace_seconds: None,
                default_time_to_live: None,
                memtable_flush_period_in_ms: None,
                additional_properties: HashMap::new(),
            },
            metadata: SchemaMetadata {
                discovered_at: std::time::UNIX_EPOCH,
                source_files: Vec::new(),
                total_rows_sampled: 0,
                cassandra_version: None,
                discovery_method: DiscoveryMethod::HeaderMetadata,
                version: 1,
                validation_results: ValidationResults {
                    status: ValidationStatus::Valid,
                    errors: Vec::new(),
                    warnings: Vec::new(),
                    consistency_results: ConsistencyResults {
                        files_analyzed: 0,
                        schema_mismatches: 0,
                        type_inconsistencies: Vec::new(),
                        udt_conflicts: Vec::new(),
                    },
                },
                performance_metrics: DiscoveryMetrics {
                    total_time_ms: 0,
                    header_parsing_time_ms: 0,
                    data_sampling_time_ms: 0,
                    type_inference_time_ms: 0,
                    validation_time_ms: 0,
                    peak_memory_usage_bytes: 0,
                },
            },
        };

        // Test that the stub method executes without panicking and returns expected result
        let result = exporter
            .generate_comparison_report(&schema_info, &schema_info)
            .await;
        assert!(
            result.is_ok(),
            "generate_comparison_report stub should return Ok"
        );

        let report = result.unwrap();
        assert!(
            report.contains("Schema comparison not yet implemented"),
            "Report should contain stub message"
        );
    }
}