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
//! Schema Registry for Centralized Schema Management
//!
//! This module provides a centralized registry for managing table schemas, UDTs,
//! and other schema-related information with support for schema discovery,
//! validation, caching, and version management.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;

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

use crate::{
    platform::Platform,
    schema::{
        discovery::{SchemaDiscoveryConfig, SchemaDiscoveryEngine, SchemaInfo},
        CqlType, TableSchema, UdtRegistry,
    },
    types::{ComparatorType, UdtTypeDef},
    Config, Error, Result,
};

/// Configuration for schema registry
#[derive(Debug, Clone)]
pub struct SchemaRegistryConfig {
    /// Enable automatic schema discovery
    pub enable_auto_discovery: bool,
    /// Enable schema caching
    pub enable_caching: bool,
    /// Cache TTL in seconds
    pub cache_ttl_seconds: u64,
    /// Enable schema versioning
    pub enable_versioning: bool,
    /// Maximum versions to keep per schema
    pub max_versions_per_schema: usize,
    /// Enable schema validation
    pub enable_validation: bool,
    /// Auto-refresh schemas on SSTable changes
    pub auto_refresh_on_changes: bool,
    /// Discovery configuration
    pub discovery_config: SchemaDiscoveryConfig,
}

impl Default for SchemaRegistryConfig {
    fn default() -> Self {
        Self {
            enable_auto_discovery: true,
            enable_caching: true,
            cache_ttl_seconds: 3600, // 1 hour
            enable_versioning: true,
            max_versions_per_schema: 5,
            enable_validation: true,
            auto_refresh_on_changes: false, // Disabled by default for performance
            discovery_config: SchemaDiscoveryConfig::default(),
        }
    }
}

/// Centralized schema registry
#[derive(Debug)]
pub struct SchemaRegistry {
    /// Configuration
    config: SchemaRegistryConfig,
    /// Platform abstraction
    _platform: Arc<Platform>,
    /// Core configuration
    _core_config: Config,
    /// Registered table schemas by keyspace.table
    schemas: Arc<RwLock<HashMap<String, SchemaEntry>>>,
    /// UDT registry for managing user-defined types
    udt_registry: Arc<RwLock<UdtRegistry>>,
    /// Schema discovery engine
    discovery_engine: Arc<SchemaDiscoveryEngine>,
    /// Schema validator
    validator: Arc<SchemaValidator>,
    /// Schema version history
    version_history: Arc<RwLock<HashMap<String, Vec<SchemaVersion>>>>,
}

/// Schema entry in the registry
#[derive(Debug, Clone)]
struct SchemaEntry {
    /// The table schema
    schema: TableSchema,
    /// Extended schema information if available
    extended_info: Option<SchemaInfo>,
    /// When the schema was registered/updated
    registered_at: SystemTime,
    /// Source of the schema
    source: SchemaSource,
    /// Validation status
    validation_status: SchemaValidationStatus,
    /// Associated SSTable files
    _associated_files: Vec<PathBuf>,
}

/// Source of schema information
#[derive(Debug, Clone)]
pub enum SchemaSource {
    /// Discovered from SSTable files
    Discovered(Vec<PathBuf>),
    /// Loaded from external definition
    External(PathBuf),
    /// Parsed from CQL DDL
    Cql(String),
    /// Manually registered
    Manual,
}

/// Schema validation status
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaValidationStatus {
    /// Schema is valid
    Valid,
    /// Schema has warnings but is usable
    ValidWithWarnings,
    /// Schema is invalid
    Invalid,
    /// Not yet validated
    NotValidated,
}

/// Schema version information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaVersion {
    /// Version number
    pub version: u32,
    /// When this version was created
    pub created_at: SystemTime,
    /// Schema at this version
    pub schema: TableSchema,
    /// Changes from previous version
    pub changes: Vec<SchemaChange>,
    /// Source of this version
    pub source: String,
}

/// Schema change description
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaChange {
    /// Type of change
    pub change_type: SchemaChangeType,
    /// Component affected
    pub component: String,
    /// Description of the change
    pub description: String,
    /// Old value (if applicable)
    pub old_value: Option<String>,
    /// New value (if applicable)
    pub new_value: Option<String>,
}

/// Types of schema changes
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SchemaChangeType {
    /// Column added
    ColumnAdded,
    /// Column removed
    ColumnRemoved,
    /// Column type changed
    ColumnTypeChanged,
    /// Column renamed
    ColumnRenamed,
    /// Index added
    IndexAdded,
    /// Index removed
    IndexRemoved,
    /// UDT added
    UdtAdded,
    /// UDT modified
    UdtModified,
    /// UDT removed
    UdtRemoved,
    /// Table option changed
    TableOptionChanged,
}

/// Schema validation report
#[derive(Debug, Clone)]
pub struct ValidationReport {
    /// Table identifier
    pub table_id: String,
    /// Overall validation status
    pub status: SchemaValidationStatus,
    /// Validation errors
    pub errors: Vec<ValidationError>,
    /// Validation warnings
    pub warnings: Vec<ValidationWarning>,
    /// Recommendations
    pub recommendations: Vec<String>,
    /// Validation timestamp
    pub validated_at: SystemTime,
}

/// Validation error details
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
    /// Affected component
    pub component: Option<String>,
    /// Severity level
    pub severity: ErrorSeverity,
}

/// Error severity levels
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorSeverity {
    Critical,
    High,
    Medium,
    Low,
}

/// Validation warning details
#[derive(Debug, Clone)]
pub struct ValidationWarning {
    /// Warning code
    pub code: String,
    /// Warning message
    pub message: String,
    /// Affected component
    pub component: Option<String>,
}

/// Schema search query
#[derive(Debug, Clone)]
pub struct SchemaQuery {
    /// Keyspace filter (optional)
    pub keyspace: Option<String>,
    /// Table name pattern (supports wildcards)
    pub table_pattern: Option<String>,
    /// Include schemas with specific source types
    pub source_types: Option<Vec<SchemaSource>>,
    /// Include only validated schemas
    pub validated_only: bool,
    /// Include version history
    pub include_history: bool,
}

impl SchemaRegistry {
    /// Create a new schema registry
    pub async fn new(
        config: SchemaRegistryConfig,
        platform: Arc<Platform>,
        core_config: Config,
    ) -> Result<Self> {
        let discovery_engine = Arc::new(
            SchemaDiscoveryEngine::new(
                config.discovery_config.clone(),
                platform.clone(),
                core_config.clone(),
            )
            .await?,
        );

        let validator = Arc::new(SchemaValidator::new());
        let udt_registry = Arc::new(RwLock::new(UdtRegistry::new()));

        Ok(Self {
            config,
            _platform: platform,
            _core_config: core_config,
            schemas: Arc::new(RwLock::new(HashMap::new())),
            udt_registry,
            discovery_engine,
            validator,
            version_history: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    /// Discover and register schema from SSTable files
    pub async fn discover_schema(
        &self,
        keyspace: &str,
        table: &str,
        sstable_files: &[PathBuf],
    ) -> Result<TableSchema> {
        if !self.config.enable_auto_discovery {
            return Err(Error::Schema("Auto-discovery is disabled".to_string()));
        }

        // Use discovery engine to analyze SSTable files
        let schema_info = self
            .discovery_engine
            .discover_schema(keyspace, table, sstable_files)
            .await?;

        // Convert to TableSchema format for compatibility
        let table_schema = self.convert_schema_info_to_table_schema(&schema_info)?;

        // Register the discovered schema
        self.register_discovered_schema(
            table_schema.clone(),
            Some(schema_info),
            sstable_files.to_vec(),
        )
        .await?;

        Ok(table_schema)
    }

    /// Register a schema from external source
    pub async fn register_schema(&self, schema: TableSchema, source: SchemaSource) -> Result<()> {
        let table_id = format!("{}.{}", schema.keyspace, schema.table);

        // Validate schema if validation is enabled
        let validation_status = if self.config.enable_validation {
            match self.validator.validate_table_schema(&schema).await {
                Ok(_) => SchemaValidationStatus::Valid,
                Err(_) => SchemaValidationStatus::Invalid,
            }
        } else {
            SchemaValidationStatus::NotValidated
        };

        // Create schema entry
        let entry = SchemaEntry {
            schema: schema.clone(),
            extended_info: None,
            registered_at: SystemTime::now(),
            source,
            validation_status,
            _associated_files: Vec::new(),
        };

        // Store in registry
        {
            let mut schemas = self.schemas.write().await;

            // Check if we need to create a new version
            if self.config.enable_versioning && schemas.contains_key(&table_id) {
                self.create_schema_version(&table_id, &schema).await?;
            }

            schemas.insert(table_id, entry);
        }

        Ok(())
    }

    /// Get schema by keyspace and table name
    pub async fn get_schema(&self, keyspace: &str, table: &str) -> Result<TableSchema> {
        let table_id = format!("{}.{}", keyspace, table);
        let schemas = self.schemas.read().await;

        match schemas.get(&table_id) {
            Some(entry) => {
                // Check if schema is still valid (cache TTL)
                if self.is_entry_expired(entry) {
                    drop(schemas); // Release read lock
                    return self.refresh_schema(keyspace, table).await;
                }
                Ok(entry.schema.clone())
            }
            None => {
                drop(schemas); // Release read lock
                               // Try to discover schema if auto-discovery is enabled
                if self.config.enable_auto_discovery {
                    self.auto_discover_schema(keyspace, table).await
                } else {
                    Err(Error::Schema(format!(
                        "Schema not found: {}.{}",
                        keyspace, table
                    )))
                }
            }
        }
    }

    /// Get extended schema information
    pub async fn get_schema_info(&self, keyspace: &str, table: &str) -> Result<Option<SchemaInfo>> {
        let table_id = format!("{}.{}", keyspace, table);
        let schemas = self.schemas.read().await;

        match schemas.get(&table_id) {
            Some(entry) => Ok(entry.extended_info.clone()),
            None => Ok(None),
        }
    }

    /// List all registered schemas
    pub async fn list_schemas(&self, query: Option<SchemaQuery>) -> Result<Vec<TableSchema>> {
        let schemas = self.schemas.read().await;
        let mut results = Vec::new();

        for (_table_id, entry) in schemas.iter() {
            // Apply query filters if provided
            if let Some(ref q) = query {
                if !self.matches_query(&entry.schema, q) {
                    continue;
                }
            }

            results.push(entry.schema.clone());
        }

        // Sort by keyspace, then table name
        results.sort_by(|a, b| {
            a.keyspace
                .cmp(&b.keyspace)
                .then_with(|| a.table.cmp(&b.table))
        });

        Ok(results)
    }

    /// Validate a schema
    #[allow(dead_code)]
    pub async fn validate_schema(&self, keyspace: &str, table: &str) -> Result<ValidationReport> {
        let schema = self.get_schema(keyspace, table).await?;
        let table_id = format!("{}.{}", keyspace, table);

        // Perform comprehensive validation
        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        let mut recommendations = Vec::new();

        // Basic schema structure validation
        if let Err(e) = schema.validate() {
            errors.push(ValidationError {
                code: "SCHEMA_INVALID".to_string(),
                message: e.to_string(),
                component: None,
                severity: ErrorSeverity::Critical,
            });
        }

        // UDT validation
        self.validate_schema_udts(&schema, &mut errors, &mut warnings)
            .await;

        // Column type validation
        self.validate_column_types(&schema, &mut errors, &mut warnings)
            .await;

        // Performance recommendations
        self.generate_performance_recommendations(&schema, &mut recommendations)
            .await;

        // Determine overall status
        let status = if !errors.is_empty() {
            SchemaValidationStatus::Invalid
        } else if !warnings.is_empty() {
            SchemaValidationStatus::ValidWithWarnings
        } else {
            SchemaValidationStatus::Valid
        };

        // Update validation status in registry
        {
            let mut schemas = self.schemas.write().await;
            if let Some(entry) = schemas.get_mut(&table_id) {
                entry.validation_status = status.clone();
            }
        }

        Ok(ValidationReport {
            table_id,
            status,
            errors,
            warnings,
            recommendations,
            validated_at: SystemTime::now(),
        })
    }

    /// Get schema version history
    pub async fn get_schema_history(
        &self,
        keyspace: &str,
        table: &str,
    ) -> Result<Vec<SchemaVersion>> {
        if !self.config.enable_versioning {
            return Err(Error::Schema("Schema versioning is disabled".to_string()));
        }

        let table_id = format!("{}.{}", keyspace, table);
        let history = self.version_history.read().await;

        Ok(history.get(&table_id).cloned().unwrap_or_default())
    }

    /// Remove schema from registry
    pub async fn remove_schema(&self, keyspace: &str, table: &str) -> Result<()> {
        let table_id = format!("{}.{}", keyspace, table);

        {
            let mut schemas = self.schemas.write().await;
            schemas.remove(&table_id);
        }

        // Also remove from version history if versioning is enabled
        if self.config.enable_versioning {
            let mut history = self.version_history.write().await;
            history.remove(&table_id);
        }

        Ok(())
    }

    /// Generate CQL CREATE statement for schema
    pub async fn generate_cql(&self, keyspace: &str, table: &str) -> Result<String> {
        // First try to get extended schema info for better CQL generation
        if let Some(schema_info) = self.get_schema_info(keyspace, table).await? {
            return self.discovery_engine.generate_cql(&schema_info).await;
        }

        // Fallback to basic TableSchema CQL generation
        let schema = self.get_schema(keyspace, table).await?;
        Ok(self.generate_basic_cql(&schema))
    }

    /// Export schema as JSON
    #[cfg(feature = "experimental")]
    pub async fn export_schema_json(&self, keyspace: &str, table: &str) -> Result<String> {
        self.export_schema_json_with_config(
            keyspace,
            table,
            &crate::schema::json_exporter::JsonExportConfig::default(),
        )
        .await
    }

    #[cfg(not(feature = "experimental"))]
    pub async fn export_schema_json(&self, _keyspace: &str, _table: &str) -> 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_schema_json_with_config(
        &self,
        keyspace: &str,
        table: &str,
        config: &crate::schema::json_exporter::JsonExportConfig,
    ) -> Result<String> {
        // Try extended schema info first
        if let Some(schema_info) = self.get_schema_info(keyspace, table).await? {
            return self
                .discovery_engine
                .export_json_with_config(&schema_info, config)
                .await;
        }

        // Fallback to basic TableSchema JSON
        let schema = self.get_schema(keyspace, table).await?;
        let exporter = crate::schema::json_exporter::JsonExporter::with_config(config.clone());
        exporter.export_table_schema(&schema)
    }

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

    /// Export schema as compact JSON (minimal format)
    #[cfg(feature = "experimental")]
    pub async fn export_schema_json_compact(&self, keyspace: &str, table: &str) -> 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_schema_json_with_config(keyspace, table, &config)
            .await
    }

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

    /// Export schema for API documentation (OpenAPI-compatible format)
    #[cfg(feature = "experimental")]
    pub async fn export_schema_json_openapi(&self, keyspace: &str, table: &str) -> 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_schema_json_with_config(keyspace, table, &config)
            .await
    }

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

    /// Export schema for data pipeline tools
    #[cfg(feature = "experimental")]
    pub async fn export_schema_json_pipeline(&self, keyspace: &str, table: &str) -> 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_schema_json_with_config(keyspace, table, &config)
            .await
    }

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

    /// Export multiple schemas as a JSON collection
    #[cfg(feature = "experimental")]
    pub async fn export_multiple_schemas_json(
        &self,
        schema_infos: &[SchemaInfo],
    ) -> Result<String> {
        let exporter = crate::schema::json_exporter::JsonExporter::new();
        exporter.export_multiple_schemas(schema_infos)
    }

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

    /// Export all schemas in a keyspace as JSON collection
    #[cfg(feature = "experimental")]
    pub async fn export_keyspace_schemas_json(&self, keyspace: &str) -> Result<String> {
        let mut schema_infos = Vec::new();

        // Get all schemas in the keyspace
        for (_table_id, entry) in self.schemas.read().await.iter() {
            if entry.schema.keyspace == keyspace {
                // Try to get extended schema info
                if let Ok(Some(schema_info)) = self
                    .get_schema_info(&entry.schema.keyspace, &entry.schema.table)
                    .await
                {
                    schema_infos.push(schema_info);
                }
            }
        }

        if schema_infos.is_empty() {
            return Err(Error::NotFound(format!(
                "No schemas found in keyspace '{}'",
                keyspace
            )));
        }

        self.export_multiple_schemas_json(&schema_infos).await
    }

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

    /// Register UDT in the registry
    pub async fn register_udt(&self, udt_def: UdtTypeDef) -> Result<()> {
        let mut registry = self.udt_registry.write().await;
        registry.register_udt(udt_def);
        Ok(())
    }

    /// Get UDT definition
    pub async fn get_udt(&self, keyspace: &str, name: &str) -> Result<Option<UdtTypeDef>> {
        let registry = self.udt_registry.read().await;
        Ok(registry.get_udt(keyspace, name).cloned())
    }

    /// Get the internal UDT registry (crate-only access for schema manager)
    ///
    /// This method is used by SchemaManager when initialized with a pre-loaded registry
    /// to preserve the UDT definitions loaded during ingestion.
    pub(crate) fn get_udt_registry(&self) -> Arc<RwLock<UdtRegistry>> {
        self.udt_registry.clone()
    }

    /// Get ComparatorType for a specific column in a table
    pub async fn get_column_comparator(
        &self,
        keyspace: &str,
        table: &str,
        column: &str,
    ) -> Result<ComparatorType> {
        let schema = self.get_schema(keyspace, table).await?;

        // Find the column
        let column_def = schema
            .columns
            .iter()
            .find(|c| c.name == column)
            .ok_or_else(|| {
                Error::Schema(format!(
                    "Column '{}' not found in table '{}.{}'",
                    column, keyspace, table
                ))
            })?;

        // Parse the column type and create comparator
        let cql_type = CqlType::parse(&column_def.data_type)?;
        ComparatorType::from_cql_type(&cql_type)
    }

    /// Get ComparatorType for all columns in a table
    pub async fn get_table_comparators(
        &self,
        keyspace: &str,
        table: &str,
    ) -> Result<HashMap<String, ComparatorType>> {
        let schema = self.get_schema(keyspace, table).await?;
        let mut comparators = HashMap::new();

        for column in &schema.columns {
            let cql_type = CqlType::parse(&column.data_type)?;
            let comparator = ComparatorType::from_cql_type(&cql_type)?;
            comparators.insert(column.name.clone(), comparator);
        }

        Ok(comparators)
    }

    /// Get ComparatorType for partition key columns (for key comparison)
    pub async fn get_partition_key_comparator(
        &self,
        keyspace: &str,
        table: &str,
    ) -> Result<Vec<ComparatorType>> {
        let schema = self.get_schema(keyspace, table).await?;
        let mut comparators = Vec::new();

        // Get partition keys in order
        let ordered_keys = schema.ordered_partition_keys();
        for key_column in ordered_keys {
            let cql_type = CqlType::parse(&key_column.data_type)?;
            let comparator = ComparatorType::from_cql_type(&cql_type)?;
            comparators.push(comparator);
        }

        Ok(comparators)
    }

    /// Get the complete schema context for parsing operations
    pub async fn get_parsing_context(&self, keyspace: &str, table: &str) -> Result<ParsingContext> {
        let schema = self.get_schema(keyspace, table).await?;
        let partition_comparators = self.get_partition_key_comparator(keyspace, table).await?;
        let clustering_comparators = self.get_clustering_key_comparator(keyspace, table).await?;
        let column_comparators = self.get_table_comparators(keyspace, table).await?;

        Ok(ParsingContext {
            schema,
            partition_comparators,
            clustering_comparators,
            column_comparators,
        })
    }

    /// Get ComparatorType for clustering key columns (for clustering comparison)
    pub async fn get_clustering_key_comparator(
        &self,
        keyspace: &str,
        table: &str,
    ) -> Result<Vec<ComparatorType>> {
        let schema = self.get_schema(keyspace, table).await?;
        let mut comparators = Vec::new();

        // Get clustering keys in order
        let ordered_keys = schema.ordered_clustering_keys();
        for key_column in ordered_keys {
            let cql_type = CqlType::parse(&key_column.data_type)?;
            let comparator = ComparatorType::from_cql_type(&cql_type)?;
            comparators.push(comparator);
        }

        Ok(comparators)
    }

    /// Validate column type compatibility using ComparatorType
    pub async fn validate_column_type_compatibility(
        &self,
        keyspace: &str,
        table: &str,
        column: &str,
        expected_type: &str,
    ) -> Result<bool> {
        let column_comparator = self.get_column_comparator(keyspace, table, column).await?;
        let expected_cql_type = CqlType::parse(expected_type)?;
        let expected_comparator = ComparatorType::from_cql_type(&expected_cql_type)?;

        // Check if comparators are compatible (same type structure)
        Ok(self.comparators_are_compatible(&column_comparator, &expected_comparator))
    }

    /// Check if two ComparatorTypes are compatible
    #[allow(clippy::only_used_in_recursion)]
    fn comparators_are_compatible(&self, left: &ComparatorType, right: &ComparatorType) -> bool {
        match (left, right) {
            // Exact matches
            (ComparatorType::Boolean, ComparatorType::Boolean) => true,
            (ComparatorType::TinyInt, ComparatorType::TinyInt) => true,
            (ComparatorType::SmallInt, ComparatorType::SmallInt) => true,
            (ComparatorType::Int, ComparatorType::Int) => true,
            (ComparatorType::BigInt, ComparatorType::BigInt) => true,
            (ComparatorType::Float32, ComparatorType::Float32) => true,
            (ComparatorType::Float, ComparatorType::Float) => true,
            (ComparatorType::Text, ComparatorType::Text) => true,
            (ComparatorType::Blob, ComparatorType::Blob) => true,
            (ComparatorType::Timestamp, ComparatorType::Timestamp) => true,
            (ComparatorType::Uuid, ComparatorType::Uuid) => true,
            (ComparatorType::Json, ComparatorType::Json) => true,

            // Collection types
            (ComparatorType::List(l_elem), ComparatorType::List(r_elem)) => {
                self.comparators_are_compatible(l_elem, r_elem)
            }
            (ComparatorType::Set(l_elem), ComparatorType::Set(r_elem)) => {
                self.comparators_are_compatible(l_elem, r_elem)
            }
            (ComparatorType::Map(l_key, l_val), ComparatorType::Map(r_key, r_val)) => {
                self.comparators_are_compatible(l_key, r_key)
                    && self.comparators_are_compatible(l_val, r_val)
            }

            // Tuple types
            (ComparatorType::Tuple(l_fields), ComparatorType::Tuple(r_fields)) => {
                l_fields.len() == r_fields.len()
                    && l_fields
                        .iter()
                        .zip(r_fields.iter())
                        .all(|(l, r)| self.comparators_are_compatible(l, r))
            }

            // UDT types
            (
                ComparatorType::Udt {
                    type_name: l_name,
                    keyspace: l_ks,
                    ..
                },
                ComparatorType::Udt {
                    type_name: r_name,
                    keyspace: r_ks,
                    ..
                },
            ) => l_name == r_name && l_ks == r_ks,

            // Frozen types
            (ComparatorType::Frozen(l_inner), ComparatorType::Frozen(r_inner)) => {
                self.comparators_are_compatible(l_inner, r_inner)
            }

            // Custom types
            (ComparatorType::Custom(l_name), ComparatorType::Custom(r_name)) => l_name == r_name,

            // No other combinations are compatible
            _ => false,
        }
    }

    /// Get registry statistics
    pub async fn get_statistics(&self) -> Result<RegistryStatistics> {
        let schemas = self.schemas.read().await;
        let udt_registry = self.udt_registry.read().await;
        let version_history = self.version_history.read().await;

        let mut stats = RegistryStatistics {
            total_schemas: schemas.len(),
            schemas_by_keyspace: HashMap::new(),
            validated_schemas: 0,
            schemas_with_warnings: 0,
            invalid_schemas: 0,
            total_udts: udt_registry.total_udts(),
            total_versions: version_history.values().map(|v| v.len()).sum(),
            auto_discovered_schemas: 0,
            manually_registered_schemas: 0,
            cache_hit_rate: 0.0, // TODO: Implement cache metrics
        };

        // Analyze schema distribution and status
        for entry in schemas.values() {
            let keyspace = &entry.schema.keyspace;
            *stats
                .schemas_by_keyspace
                .entry(keyspace.clone())
                .or_insert(0) += 1;

            match entry.validation_status {
                SchemaValidationStatus::Valid => stats.validated_schemas += 1,
                SchemaValidationStatus::ValidWithWarnings => stats.schemas_with_warnings += 1,
                SchemaValidationStatus::Invalid => stats.invalid_schemas += 1,
                SchemaValidationStatus::NotValidated => {}
            }

            match entry.source {
                SchemaSource::Discovered(_) => stats.auto_discovered_schemas += 1,
                _ => stats.manually_registered_schemas += 1,
            }
        }

        Ok(stats)
    }

    // Private helper methods

    async fn register_discovered_schema(
        &self,
        schema: TableSchema,
        schema_info: Option<SchemaInfo>,
        sstable_files: Vec<PathBuf>,
    ) -> Result<()> {
        let table_id = format!("{}.{}", schema.keyspace, schema.table);
        let source = SchemaSource::Discovered(sstable_files.clone());

        let entry = SchemaEntry {
            schema,
            extended_info: schema_info,
            registered_at: SystemTime::now(),
            source,
            validation_status: SchemaValidationStatus::Valid, // Discovery implies validation
            _associated_files: sstable_files,
        };

        let mut schemas = self.schemas.write().await;
        schemas.insert(table_id, entry);

        Ok(())
    }

    fn convert_schema_info_to_table_schema(&self, schema_info: &SchemaInfo) -> Result<TableSchema> {
        let mut columns = Vec::new();
        let mut partition_keys = Vec::new();
        let mut clustering_keys = Vec::new();

        // Convert partition keys
        for (pos, pk) in schema_info.partition_key.iter().enumerate() {
            partition_keys.push(crate::schema::KeyColumn {
                name: pk.name.clone(),
                data_type: pk.data_type.clone(),
                position: pos,
            });
        }

        // Convert clustering keys
        for ck in &schema_info.clustering_keys {
            clustering_keys.push(ck.clone());
        }

        // Convert all columns
        for col in &schema_info.regular_columns {
            columns.push(crate::schema::Column {
                name: col.name.clone(),
                data_type: col.data_type.clone(),
                nullable: col.nullable,
                default: None, // ColumnDefinition doesn't have default_value
                is_static: false,
            });
        }

        // Add static columns
        for col in &schema_info.static_columns {
            columns.push(crate::schema::Column {
                name: col.name.clone(),
                data_type: col.data_type.clone(),
                nullable: col.nullable,
                default: None, // ColumnDefinition doesn't have default_value
                is_static: true,
            });
        }

        Ok(TableSchema {
            keyspace: schema_info.keyspace.clone(),
            table: schema_info.table.clone(),
            partition_keys,
            clustering_keys,
            columns,
            comments: HashMap::new(),
        })
    }

    fn is_entry_expired(&self, entry: &SchemaEntry) -> bool {
        if !self.config.enable_caching {
            return false;
        }

        let ttl = std::time::Duration::from_secs(self.config.cache_ttl_seconds);
        entry
            .registered_at
            .elapsed()
            .unwrap_or(std::time::Duration::ZERO)
            > ttl
    }

    async fn refresh_schema(&self, keyspace: &str, table: &str) -> Result<TableSchema> {
        // Implementation for refreshing expired schema
        // For now, just try auto-discovery
        self.auto_discover_schema(keyspace, table).await
    }

    async fn auto_discover_schema(&self, keyspace: &str, table: &str) -> Result<TableSchema> {
        // Try to find SSTable files for this table
        // This is a placeholder - in practice, you'd scan the data directory
        let sstable_files = self.find_sstable_files(keyspace, table).await?;

        if sstable_files.is_empty() {
            return Err(Error::Schema(format!(
                "No SSTables found for {}.{}",
                keyspace, table
            )));
        }

        self.discover_schema(keyspace, table, &sstable_files).await
    }

    async fn find_sstable_files(&self, _keyspace: &str, _table: &str) -> Result<Vec<PathBuf>> {
        // Placeholder implementation
        // In practice, this would scan the data directory structure
        Ok(Vec::new())
    }

    fn matches_query(&self, schema: &TableSchema, query: &SchemaQuery) -> bool {
        // Apply keyspace filter
        if let Some(ref ks) = query.keyspace {
            if &schema.keyspace != ks {
                return false;
            }
        }

        // Apply table pattern filter
        if let Some(ref pattern) = query.table_pattern {
            if !self.matches_pattern(&schema.table, pattern) {
                return false;
            }
        }

        // Other filters would be applied here
        true
    }

    fn matches_pattern(&self, text: &str, pattern: &str) -> bool {
        // Simple wildcard matching (can be enhanced)
        if pattern == "*" {
            return true;
        }

        // For now, just exact match or contains
        text == pattern || text.contains(pattern)
    }

    async fn create_schema_version(&self, table_id: &str, new_schema: &TableSchema) -> Result<()> {
        let mut version_history = self.version_history.write().await;
        let versions = version_history
            .entry(table_id.to_string())
            .or_insert_with(Vec::new);

        let version_number = versions.len() as u32 + 1;
        let changes = if versions.is_empty() {
            vec![SchemaChange {
                change_type: SchemaChangeType::ColumnAdded,
                component: "initial".to_string(),
                description: "Initial schema version".to_string(),
                old_value: None,
                new_value: None,
            }]
        } else {
            // Compare with previous version to detect changes
            self.detect_schema_changes(&versions.last().unwrap().schema, new_schema)
        };

        let new_version = SchemaVersion {
            version: version_number,
            created_at: SystemTime::now(),
            schema: new_schema.clone(),
            changes,
            source: "registry".to_string(),
        };

        versions.push(new_version);

        // Limit version history size
        if versions.len() > self.config.max_versions_per_schema {
            versions.remove(0);
        }

        Ok(())
    }

    fn detect_schema_changes(
        &self,
        old_schema: &TableSchema,
        new_schema: &TableSchema,
    ) -> Vec<SchemaChange> {
        let mut changes = Vec::new();

        // Compare columns
        let old_columns: HashMap<_, _> = old_schema.columns.iter().map(|c| (&c.name, c)).collect();
        let new_columns: HashMap<_, _> = new_schema.columns.iter().map(|c| (&c.name, c)).collect();

        // Find added columns
        for (name, column) in &new_columns {
            if !old_columns.contains_key(name) {
                changes.push(SchemaChange {
                    change_type: SchemaChangeType::ColumnAdded,
                    component: name.to_string(),
                    description: format!(
                        "Column '{}' added with type '{}'",
                        name, column.data_type
                    ),
                    old_value: None,
                    new_value: Some(column.data_type.clone()),
                });
            }
        }

        // Find removed columns
        for name in old_columns.keys() {
            if !new_columns.contains_key(name) {
                changes.push(SchemaChange {
                    change_type: SchemaChangeType::ColumnRemoved,
                    component: name.to_string(),
                    description: format!("Column '{}' removed", name),
                    old_value: None,
                    new_value: None,
                });
            }
        }

        // Find type changes
        for (name, new_column) in &new_columns {
            if let Some(old_column) = old_columns.get(name) {
                if old_column.data_type != new_column.data_type {
                    changes.push(SchemaChange {
                        change_type: SchemaChangeType::ColumnTypeChanged,
                        component: name.to_string(),
                        description: format!("Column '{}' type changed", name),
                        old_value: Some(old_column.data_type.clone()),
                        new_value: Some(new_column.data_type.clone()),
                    });
                }
            }
        }

        changes
    }

    async fn validate_schema_udts(
        &self,
        schema: &TableSchema,
        errors: &mut Vec<ValidationError>,
        warnings: &mut Vec<ValidationWarning>,
    ) {
        let udt_registry = self.udt_registry.read().await;

        for column in &schema.columns {
            // Check if column type references a UDT
            if let Ok(cql_type) = CqlType::parse(&column.data_type) {
                self.validate_cql_type_udts(
                    &cql_type,
                    &schema.keyspace,
                    &udt_registry,
                    errors,
                    warnings,
                );
            }
        }
    }

    #[allow(clippy::only_used_in_recursion)]
    fn validate_cql_type_udts(
        &self,
        cql_type: &CqlType,
        keyspace: &str,
        udt_registry: &UdtRegistry,
        errors: &mut Vec<ValidationError>,
        _warnings: &mut Vec<ValidationWarning>,
    ) {
        match cql_type {
            CqlType::Udt(udt_name, _) => {
                if !udt_registry.contains_udt(keyspace, udt_name) {
                    errors.push(ValidationError {
                        code: "UDT_NOT_FOUND".to_string(),
                        message: format!("UDT '{}' not found in keyspace '{}'", udt_name, keyspace),
                        component: Some(udt_name.clone()),
                        severity: ErrorSeverity::High,
                    });
                }
            }
            CqlType::List(inner) | CqlType::Set(inner) | CqlType::Frozen(inner) => {
                self.validate_cql_type_udts(inner, keyspace, udt_registry, errors, _warnings);
            }
            CqlType::Map(key_type, value_type) => {
                self.validate_cql_type_udts(key_type, keyspace, udt_registry, errors, _warnings);
                self.validate_cql_type_udts(value_type, keyspace, udt_registry, errors, _warnings);
            }
            CqlType::Tuple(types) => {
                for t in types {
                    self.validate_cql_type_udts(t, keyspace, udt_registry, errors, _warnings);
                }
            }
            _ => {} // Primitive types don't need UDT validation
        }
    }

    async fn validate_column_types(
        &self,
        schema: &TableSchema,
        errors: &mut Vec<ValidationError>,
        _warnings: &mut [ValidationWarning],
    ) {
        for column in &schema.columns {
            if let Err(e) = CqlType::parse(&column.data_type) {
                errors.push(ValidationError {
                    code: "INVALID_COLUMN_TYPE".to_string(),
                    message: format!("Invalid column type '{}': {}", column.data_type, e),
                    component: Some(column.name.clone()),
                    severity: ErrorSeverity::High,
                });
            }
        }
    }

    async fn generate_performance_recommendations(
        &self,
        schema: &TableSchema,
        recommendations: &mut Vec<String>,
    ) {
        // Check for potential performance issues

        // Large partition keys
        if schema.partition_keys.len() > 3 {
            recommendations.push(
                "Consider reducing the number of partition key columns for better performance"
                    .to_string(),
            );
        }

        // Many clustering keys
        if schema.clustering_keys.len() > 5 {
            recommendations
                .push("Large number of clustering keys may impact query performance".to_string());
        }

        // Column count
        if schema.columns.len() > 50 {
            recommendations.push(
                "Consider using UDTs or denormalizing wide tables for better performance"
                    .to_string(),
            );
        }
    }

    fn generate_basic_cql(&self, schema: &TableSchema) -> String {
        let mut cql = format!("CREATE TABLE {}.{} (\n", schema.keyspace, schema.table);

        // Add columns
        for (i, column) in schema.columns.iter().enumerate() {
            if i > 0 {
                cql.push_str(",\n");
            }
            cql.push_str(&format!("  {} {}", column.name, column.data_type));
        }

        // Add primary key
        if !schema.partition_keys.is_empty() {
            cql.push_str(",\n  PRIMARY KEY (");

            if schema.partition_keys.len() == 1 && schema.clustering_keys.is_empty() {
                cql.push_str(&schema.partition_keys[0].name);
            } else {
                // Composite primary key
                cql.push('(');
                for (i, pk) in schema.partition_keys.iter().enumerate() {
                    if i > 0 {
                        cql.push_str(", ");
                    }
                    cql.push_str(&pk.name);
                }
                cql.push(')');

                if !schema.clustering_keys.is_empty() {
                    for ck in &schema.clustering_keys {
                        cql.push_str(", ");
                        cql.push_str(&ck.name);
                    }
                }
            }

            cql.push(')');
        }

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

/// Registry statistics
#[derive(Debug, Clone)]
pub struct RegistryStatistics {
    /// Total number of registered schemas
    pub total_schemas: usize,
    /// Schemas grouped by keyspace
    pub schemas_by_keyspace: HashMap<String, usize>,
    /// Number of validated schemas
    pub validated_schemas: usize,
    /// Schemas with validation warnings
    pub schemas_with_warnings: usize,
    /// Invalid schemas
    pub invalid_schemas: usize,
    /// Total UDTs registered
    pub total_udts: usize,
    /// Total schema versions stored
    pub total_versions: usize,
    /// Auto-discovered schemas
    pub auto_discovered_schemas: usize,
    /// Manually registered schemas
    pub manually_registered_schemas: usize,
    /// Cache hit rate
    pub cache_hit_rate: f64,
}

/// Schema-driven parsing context containing all necessary type information
#[derive(Debug, Clone)]
pub struct ParsingContext {
    /// The complete table schema
    pub schema: TableSchema,
    /// Comparators for partition key components
    pub partition_comparators: Vec<ComparatorType>,
    /// Comparators for clustering key components
    pub clustering_comparators: Vec<ComparatorType>,
    /// Comparators for all columns by name
    pub column_comparators: HashMap<String, ComparatorType>,
}

impl ParsingContext {
    /// Get comparator for a specific column
    pub fn get_column_comparator(&self, column_name: &str) -> Option<&ComparatorType> {
        self.column_comparators.get(column_name)
    }

    /// Check if schema-driven parsing is fully configured
    pub fn is_complete(&self) -> bool {
        !self.partition_comparators.is_empty() || !self.schema.partition_keys.is_empty()
    }

    /// Get all key columns (partition + clustering) names in order
    pub fn get_all_key_column_names(&self) -> Vec<String> {
        let mut names = Vec::new();
        names.extend(
            self.schema
                .ordered_partition_keys()
                .iter()
                .map(|k| k.name.clone()),
        );
        names.extend(
            self.schema
                .ordered_clustering_keys()
                .iter()
                .map(|k| k.name.clone()),
        );
        names
    }
}

/// Schema validator for comprehensive validation
#[derive(Debug)]
pub struct SchemaValidator;

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

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

    pub async fn validate_table_schema(&self, schema: &TableSchema) -> Result<()> {
        schema.validate()
    }
}

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

    async fn make_registry(mut reg_config: SchemaRegistryConfig) -> SchemaRegistry {
        reg_config.enable_auto_discovery = false;
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.expect("platform"));
        SchemaRegistry::new(reg_config, platform, core_config)
            .await
            .expect("registry")
    }

    fn simple_schema(name: &str) -> TableSchema {
        TableSchema {
            keyspace: "test_ks".to_string(),
            table: name.to_string(),
            partition_keys: vec![crate::schema::KeyColumn {
                name: "id".to_string(),
                data_type: "uuid".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![crate::schema::Column {
                name: "id".to_string(),
                data_type: "uuid".to_string(),
                nullable: false,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
        }
    }

    #[tokio::test]
    async fn test_schema_registry_creation() {
        let registry = make_registry(SchemaRegistryConfig::default()).await;
        let stats = registry.get_statistics().await.unwrap();
        assert_eq!(stats.total_schemas, 0);
    }

    #[test]
    fn test_schema_query_creation() {
        let query = SchemaQuery {
            keyspace: Some("test_ks".to_string()),
            table_pattern: Some("user_*".to_string()),
            source_types: None,
            validated_only: false,
            include_history: false,
        };

        assert_eq!(query.keyspace.as_ref().unwrap(), "test_ks");
        assert_eq!(query.table_pattern.as_ref().unwrap(), "user_*");
    }

    #[tokio::test]
    async fn register_and_retrieve_schema() {
        let registry = make_registry(SchemaRegistryConfig::default()).await;
        let schema = simple_schema("users");

        registry
            .register_schema(schema.clone(), SchemaSource::Manual)
            .await
            .expect("register schema");

        let fetched = registry
            .get_schema("test_ks", "users")
            .await
            .expect("fetch schema");
        assert_eq!(fetched.table, "users");
        assert_eq!(fetched.partition_keys.len(), 1);
    }

    #[tokio::test]
    async fn schema_version_history_tracks_changes() {
        let registry = make_registry(SchemaRegistryConfig::default()).await;
        let mut schema = simple_schema("accounts");

        registry
            .register_schema(schema.clone(), SchemaSource::Manual)
            .await
            .expect("register v1");

        schema.columns.push(crate::schema::Column {
            name: "status".to_string(),
            data_type: "text".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        });

        registry
            .register_schema(schema.clone(), SchemaSource::Manual)
            .await
            .expect("register v2");

        let history = registry
            .get_schema_history("test_ks", "accounts")
            .await
            .expect("history");

        assert_eq!(
            history.len(),
            1,
            "Second registration should emit first version"
        );
        assert!(history[0]
            .changes
            .iter()
            .any(|change| matches!(change.change_type, SchemaChangeType::ColumnAdded)));
    }

    #[tokio::test]
    async fn expired_cached_schema_invokes_discovery_path() {
        let mut config = SchemaRegistryConfig::default();
        config.cache_ttl_seconds = 0;
        config.enable_auto_discovery = true;
        let registry = make_registry(config).await;

        registry
            .register_schema(simple_schema("events"), SchemaSource::Manual)
            .await
            .expect("register events schema");

        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        let err = registry
            .get_schema("test_ks", "events")
            .await
            .expect_err("expired schema should attempt discovery");

        assert!(matches!(err, Error::Schema(message) if message.contains("No SSTables found")));
    }
}