data-modelling-core 2.4.0

Core SDK library for model operations across platforms
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
//! Shared utilities for ODCS and ODCL parsing.
//!
//! This module contains common types, utility functions, and parsing helpers
//! used by both the ODCS (Open Data Contract Standard) and ODCL (legacy Data Contract)
//! importers. Separating these shared components allows for cleaner code organization
//! and easier testing.

use crate::models::column::ForeignKey;
use crate::models::enums::{DataVaultClassification, MedallionLayer, SCDPattern};
use crate::models::{Column, Tag};
use anyhow::Result;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::str::FromStr;

/// Parser error structure for detailed error reporting.
#[derive(Debug, Clone)]
pub struct ParserError {
    pub error_type: String,
    pub field: String,
    pub message: String,
}

/// Convert YAML Value to JSON Value for easier manipulation.
pub fn yaml_to_json_value(yaml: &serde_yaml::Value) -> Result<JsonValue> {
    use anyhow::Context;
    // Convert YAML to JSON via serialization
    let json_str = serde_json::to_string(yaml).context("Failed to convert YAML to JSON")?;
    serde_json::from_str(&json_str).context("Failed to parse JSON")
}

/// Convert JSON Value to serde_json::Value for storage in HashMap.
pub fn json_value_to_serde_value(value: &JsonValue) -> serde_json::Value {
    value.clone()
}

/// Normalize data type to uppercase, preserving STRUCT<...>, ARRAY<...>, MAP<...> format.
pub fn normalize_data_type(data_type: &str) -> String {
    if data_type.is_empty() {
        return data_type.to_string();
    }

    let upper = data_type.to_uppercase();

    // Handle STRUCT<...>, ARRAY<...>, MAP<...> preserving inner content
    if upper.starts_with("STRUCT") {
        if let Some(start) = data_type.find('<')
            && let Some(end) = data_type.rfind('>')
        {
            let inner = &data_type[start + 1..end];
            return format!("STRUCT<{}>", inner);
        }
        return format!("STRUCT{}", &data_type[6..]);
    } else if upper.starts_with("ARRAY") {
        if let Some(start) = data_type.find('<')
            && let Some(end) = data_type.rfind('>')
        {
            let inner = &data_type[start + 1..end];
            return format!("ARRAY<{}>", inner);
        }
        return format!("ARRAY{}", &data_type[5..]);
    } else if upper.starts_with("MAP") {
        if let Some(start) = data_type.find('<')
            && let Some(end) = data_type.rfind('>')
        {
            let inner = &data_type[start + 1..end];
            return format!("MAP<{}>", inner);
        }
        return format!("MAP{}", &data_type[3..]);
    }

    upper
}

/// Parse medallion layer from string.
pub fn parse_medallion_layer(s: &str) -> Result<MedallionLayer> {
    match s.to_uppercase().as_str() {
        "BRONZE" => Ok(MedallionLayer::Bronze),
        "SILVER" => Ok(MedallionLayer::Silver),
        "GOLD" => Ok(MedallionLayer::Gold),
        "OPERATIONAL" => Ok(MedallionLayer::Operational),
        _ => Err(anyhow::anyhow!("Unknown medallion layer: {}", s)),
    }
}

/// Parse SCD pattern from string.
pub fn parse_scd_pattern(s: &str) -> Result<SCDPattern> {
    match s.to_uppercase().as_str() {
        "TYPE_1" | "TYPE1" => Ok(SCDPattern::Type1),
        "TYPE_2" | "TYPE2" => Ok(SCDPattern::Type2),
        _ => Err(anyhow::anyhow!("Unknown SCD pattern: {}", s)),
    }
}

/// Parse Data Vault classification from string.
pub fn parse_data_vault_classification(s: &str) -> Result<DataVaultClassification> {
    match s.to_uppercase().as_str() {
        "HUB" => Ok(DataVaultClassification::Hub),
        "LINK" => Ok(DataVaultClassification::Link),
        "SATELLITE" | "SAT" => Ok(DataVaultClassification::Satellite),
        _ => Err(anyhow::anyhow!("Unknown Data Vault classification: {}", s)),
    }
}

/// Extract quality rules from a JSON object.
pub fn extract_quality_from_obj(
    obj: &serde_json::Map<String, JsonValue>,
) -> Vec<HashMap<String, serde_json::Value>> {
    let mut quality_rules = Vec::new();
    if let Some(quality_val) = obj.get("quality") {
        if let Some(arr) = quality_val.as_array() {
            // Array of quality rules
            for item in arr {
                if let Some(rule_obj) = item.as_object() {
                    let mut rule = HashMap::new();
                    for (key, value) in rule_obj {
                        rule.insert(key.clone(), json_value_to_serde_value(value));
                    }
                    quality_rules.push(rule);
                }
            }
        } else if let Some(rule_obj) = quality_val.as_object() {
            // Single quality rule object
            let mut rule = HashMap::new();
            for (key, value) in rule_obj {
                rule.insert(key.clone(), json_value_to_serde_value(value));
            }
            quality_rules.push(rule);
        }
    }
    quality_rules
}

/// Parse foreign key from JSON value.
pub fn parse_foreign_key(fk_data: &JsonValue) -> Option<ForeignKey> {
    let obj = fk_data.as_object()?;
    Some(ForeignKey {
        table_id: obj
            .get("table_id")
            .or_else(|| obj.get("table"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        column_name: obj
            .get("column_name")
            .or_else(|| obj.get("column"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
    })
}

/// Parse foreign key from Data Contract field data.
pub fn parse_foreign_key_from_data_contract(
    field_data: &serde_json::Map<String, JsonValue>,
) -> Option<ForeignKey> {
    field_data
        .get("foreignKey")
        .and_then(|v| v.as_object())
        .map(|fk_obj| ForeignKey {
            table_id: fk_obj
                .get("table")
                .or_else(|| fk_obj.get("table_id"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            column_name: fk_obj
                .get("column")
                .or_else(|| fk_obj.get("column_name"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
        })
}

/// Extract metadata from customProperties in ODCS/ODCL format.
pub fn extract_metadata_from_custom_properties(
    data: &JsonValue,
) -> (
    Vec<MedallionLayer>,
    Option<SCDPattern>,
    Option<DataVaultClassification>,
    Vec<Tag>,
) {
    let mut medallion_layers = Vec::new();
    let mut scd_pattern = None;
    let mut data_vault_classification = None;
    let mut tags: Vec<Tag> = Vec::new();

    if let Some(custom_props) = data.get("customProperties").and_then(|v| v.as_array()) {
        for prop in custom_props {
            if let Some(prop_obj) = prop.as_object() {
                let prop_key = prop_obj
                    .get("property")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let prop_value = prop_obj.get("value");

                match prop_key {
                    "medallionLayers" | "medallion_layers" => {
                        if let Some(arr) = prop_value.and_then(|v| v.as_array()) {
                            for item in arr {
                                if let Some(s) = item.as_str()
                                    && let Ok(layer) = parse_medallion_layer(s)
                                {
                                    medallion_layers.push(layer);
                                }
                            }
                        } else if let Some(s) = prop_value.and_then(|v| v.as_str()) {
                            // Comma-separated string
                            for part in s.split(',') {
                                if let Ok(layer) = parse_medallion_layer(part.trim()) {
                                    medallion_layers.push(layer);
                                }
                            }
                        }
                    }
                    "scdPattern" | "scd_pattern" => {
                        if let Some(s) = prop_value.and_then(|v| v.as_str()) {
                            scd_pattern = parse_scd_pattern(s).ok();
                        }
                    }
                    "dataVaultClassification" | "data_vault_classification" => {
                        if let Some(s) = prop_value.and_then(|v| v.as_str()) {
                            data_vault_classification = parse_data_vault_classification(s).ok();
                        }
                    }
                    "tags" => {
                        if let Some(arr) = prop_value.and_then(|v| v.as_array()) {
                            for item in arr {
                                if let Some(s) = item.as_str() {
                                    // Parse tag string to Tag enum
                                    if let Ok(tag) = Tag::from_str(s) {
                                        tags.push(tag);
                                    } else {
                                        tags.push(Tag::Simple(s.to_string()));
                                    }
                                }
                            }
                        } else if let Some(s) = prop_value.and_then(|v| v.as_str()) {
                            // Comma-separated string
                            for part in s.split(',') {
                                let part = part.trim();
                                if let Ok(tag) = Tag::from_str(part) {
                                    tags.push(tag);
                                } else {
                                    tags.push(Tag::Simple(part.to_string()));
                                }
                            }
                        }
                    }
                    "sharedDomains" | "shared_domains" => {
                        // sharedDomains will be stored in metadata by the caller
                        // This match is here for completeness but sharedDomains is handled separately
                    }
                    _ => {}
                }
            }
        }
    }

    // Also extract tags from top-level tags field
    if let Some(tags_arr) = data.get("tags").and_then(|v| v.as_array()) {
        for item in tags_arr {
            if let Some(s) = item.as_str() {
                // Parse tag string to Tag enum
                let tag = Tag::from_str(s).unwrap_or_else(|_| Tag::Simple(s.to_string()));
                if !tags.contains(&tag) {
                    tags.push(tag);
                }
            }
        }
    }

    (
        medallion_layers,
        scd_pattern,
        data_vault_classification,
        tags,
    )
}

/// Extract catalog and schema from customProperties.
pub fn extract_catalog_schema(data: &JsonValue) -> (Option<String>, Option<String>) {
    let mut catalog_name = None;
    let mut schema_name = None;

    if let Some(custom_props) = data.get("customProperties").and_then(|v| v.as_array()) {
        for prop in custom_props {
            if let Some(prop_obj) = prop.as_object() {
                let prop_key = prop_obj
                    .get("property")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let prop_value = prop_obj.get("value").and_then(|v| v.as_str());

                match prop_key {
                    "catalogName" | "catalog_name" => {
                        catalog_name = prop_value.map(|s| s.to_string());
                    }
                    "schemaName" | "schema_name" => {
                        schema_name = prop_value.map(|s| s.to_string());
                    }
                    _ => {}
                }
            }
        }
    }

    // Also check direct fields
    if catalog_name.is_none() {
        catalog_name = data
            .get("catalog_name")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
    }
    if schema_name.is_none() {
        schema_name = data
            .get("schema_name")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
    }

    (catalog_name, schema_name)
}

/// Extract sharedDomains from customProperties.
pub fn extract_shared_domains(data: &JsonValue) -> Vec<String> {
    let mut shared_domains: Vec<String> = Vec::new();
    if let Some(custom_props) = data.get("customProperties").and_then(|v| v.as_array()) {
        for prop in custom_props {
            if let Some(prop_obj) = prop.as_object() {
                let prop_key = prop_obj
                    .get("property")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                if (prop_key == "sharedDomains" || prop_key == "shared_domains")
                    && let Some(arr) = prop_obj.get("value").and_then(|v| v.as_array())
                {
                    for item in arr {
                        if let Some(s) = item.as_str() {
                            shared_domains.push(s.to_string());
                        }
                    }
                }
            }
        }
    }
    shared_domains
}

/// Resolve a $ref reference like '#/definitions/orderAction'.
pub fn resolve_ref<'a>(ref_str: &str, data: &'a JsonValue) -> Option<&'a JsonValue> {
    if !ref_str.starts_with("#/") {
        return None;
    }

    // Remove the leading '#/'
    let path = &ref_str[2..];
    let parts: Vec<&str> = path.split('/').collect();

    // Navigate through the data structure
    let mut current = data;
    for part in parts {
        current = current.get(part)?;
    }

    if current.is_object() {
        Some(current)
    } else {
        None
    }
}

/// Expand a nested column from a schema definition, creating columns with dot notation.
///
/// This helper function recursively expands nested structures (OBJECT/STRUCT types)
/// into flat columns with dot notation (e.g., "address.street", "address.city").
#[allow(clippy::only_used_in_recursion)]
pub fn expand_nested_column(
    column_name: &str,
    schema: &JsonValue,
    nullable: bool,
    columns: &mut Vec<Column>,
    errors: &mut Vec<ParserError>,
) {
    let schema_obj = match schema.as_object() {
        Some(obj) => obj,
        None => {
            errors.push(ParserError {
                error_type: "parse_error".to_string(),
                field: column_name.to_string(),
                message: "Nested schema must be an object".to_string(),
            });
            return;
        }
    };

    // Check both "logicalType" (ODCS v3.1.0) and "type" (legacy/ODCL) for backward compatibility
    let schema_type_raw = schema_obj
        .get("logicalType")
        .and_then(|v| v.as_str())
        .or_else(|| schema_obj.get("type").and_then(|v| v.as_str()))
        .unwrap_or("object");

    // Normalize legacy "type" values to "logicalType" equivalents
    let schema_type = match schema_type_raw {
        "object" | "struct" => "object",
        "array" => "array",
        "string" | "varchar" | "char" | "text" => "string",
        "integer" | "int" | "bigint" | "smallint" | "tinyint" => "integer",
        "number" | "decimal" | "double" | "float" | "numeric" => "number",
        "boolean" | "bool" => "boolean",
        "date" => "date",
        "timestamp" | "datetime" => "timestamp",
        "time" => "time",
        _ => schema_type_raw,
    };

    match schema_type {
        "object" | "struct" => {
            // Check if it has nested properties - handle both object format (legacy/ODCL)
            // and array format (ODCS v3.1.0)
            let properties_obj = schema_obj.get("properties").and_then(|v| v.as_object());
            let properties_arr = schema_obj.get("properties").and_then(|v| v.as_array());

            if let Some(properties) = properties_obj {
                // Object format (legacy/ODCL): properties is a map of name -> schema
                let nested_required: Vec<String> = schema_obj
                    .get("required")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    })
                    .unwrap_or_default();

                for (nested_name, nested_schema) in properties {
                    let nested_nullable = !nested_required.contains(nested_name);
                    expand_nested_column(
                        &format!("{}.{}", column_name, nested_name),
                        nested_schema,
                        nullable || nested_nullable,
                        columns,
                        errors,
                    );
                }
            } else if let Some(properties_list) = properties_arr {
                // Array format (ODCS v3.1.0): properties is an array with 'name' field
                for prop_data in properties_list {
                    if let Some(prop_obj) = prop_data.as_object() {
                        // Extract name from property object (required in v3.1.0)
                        let nested_name = prop_obj
                            .get("name")
                            .or_else(|| prop_obj.get("id"))
                            .and_then(|v| v.as_str())
                            .unwrap_or("");

                        if !nested_name.is_empty() {
                            let nested_nullable = !prop_obj
                                .get("required")
                                .and_then(|v| v.as_bool())
                                .unwrap_or(false);

                            expand_nested_column(
                                &format!("{}.{}", column_name, nested_name),
                                prop_data,
                                nullable || nested_nullable,
                                columns,
                                errors,
                            );
                        }
                    }
                }
            } else {
                // Object without properties - create as OBJECT type
                let physical_type = schema_obj
                    .get("physicalType")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let description = schema_obj
                    .get("description")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                columns.push(Column {
                    name: column_name.to_string(),
                    data_type: "OBJECT".to_string(),
                    physical_type,
                    nullable,
                    description,
                    ..Default::default()
                });
            }
        }
        "array" => {
            // Handle array types
            let items = schema_obj.get("items").unwrap_or(schema);
            // Check both "logicalType" (ODCS v3.1.0) and "type" (legacy) for backward compatibility
            let items_obj = items.as_object();
            let items_type_raw = items_obj
                .and_then(|obj| {
                    obj.get("logicalType")
                        .and_then(|v| v.as_str())
                        .or_else(|| obj.get("type").and_then(|v| v.as_str()))
                })
                .unwrap_or("string");

            // Normalize legacy "type" values to "logicalType" equivalents for backward compatibility
            let items_type = match items_type_raw {
                "object" | "struct" => "object",
                "array" => "array",
                "string" | "varchar" | "char" | "text" => "string",
                "integer" | "int" | "bigint" | "smallint" | "tinyint" => "integer",
                "number" | "decimal" | "double" | "float" | "numeric" => "number",
                "boolean" | "bool" => "boolean",
                "date" => "date",
                "timestamp" | "datetime" => "timestamp",
                "time" => "time",
                _ => items_type_raw,
            };

            if items_type == "object" {
                // Array of objects - expand nested structure
                let physical_type = schema_obj
                    .get("physicalType")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let description = schema_obj
                    .get("description")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                columns.push(Column {
                    name: column_name.to_string(),
                    data_type: "ARRAY<OBJECT>".to_string(),
                    physical_type,
                    nullable,
                    description,
                    ..Default::default()
                });
                // Also expand nested properties with array prefix
                // Handle both object format (legacy) and array format (ODCS v3.1.0)
                let properties_obj = items
                    .as_object()
                    .and_then(|obj| obj.get("properties"))
                    .and_then(|v| v.as_object());
                let properties_arr = items
                    .as_object()
                    .and_then(|obj| obj.get("properties"))
                    .and_then(|v| v.as_array());

                if let Some(properties_map) = properties_obj {
                    // Object format (legacy): properties is a map
                    let nested_required: Vec<String> = items
                        .as_object()
                        .and_then(|obj| obj.get("required").and_then(|v| v.as_array()))
                        .map(|arr| {
                            arr.iter()
                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                                .collect()
                        })
                        .unwrap_or_default();

                    for (nested_name, nested_schema) in properties_map {
                        let nested_nullable = !nested_required.contains(nested_name);
                        expand_nested_column(
                            &format!("{}.[].{}", column_name, nested_name),
                            nested_schema,
                            nullable || nested_nullable,
                            columns,
                            errors,
                        );
                    }
                } else if let Some(properties_list) = properties_arr {
                    // Array format (ODCS v3.1.0): properties is an array with 'name' field
                    for prop_data in properties_list {
                        if let Some(prop_obj) = prop_data.as_object() {
                            // Extract name from property object (required in v3.1.0)
                            let nested_name = prop_obj
                                .get("name")
                                .or_else(|| prop_obj.get("id"))
                                .and_then(|v| v.as_str())
                                .unwrap_or("");

                            if !nested_name.is_empty() {
                                let nested_nullable = !prop_obj
                                    .get("required")
                                    .and_then(|v| v.as_bool())
                                    .unwrap_or(false);

                                expand_nested_column(
                                    &format!("{}.[].{}", column_name, nested_name),
                                    prop_data,
                                    nullable || nested_nullable,
                                    columns,
                                    errors,
                                );
                            }
                        }
                    }
                }
            } else {
                // Array of primitives
                let data_type = format!("ARRAY<{}>", items_type.to_uppercase());
                // Extract physicalType (ODCS v3.1.0) - the actual database type
                let physical_type = schema_obj
                    .get("physicalType")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let description = schema_obj
                    .get("description")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                columns.push(Column {
                    name: column_name.to_string(),
                    data_type,
                    physical_type,
                    nullable,
                    description,
                    ..Default::default()
                });
            }
        }
        _ => {
            // Simple type
            let data_type = schema_type.to_uppercase();
            // Extract physicalType (ODCS v3.1.0) - the actual database type
            let physical_type = schema_obj
                .get("physicalType")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());
            let description = schema_obj
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let enum_values = schema_obj
                .get("enum")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            columns.push(Column {
                name: column_name.to_string(),
                data_type,
                physical_type,
                nullable,
                description,
                enum_values,
                ..Default::default()
            });
        }
    }
}

/// Parse STRUCT fields from string (e.g., "ID: STRING, NAME: STRING").
pub fn parse_struct_fields_from_string(fields_str: &str) -> Result<Vec<(String, String)>> {
    let mut fields = Vec::new();
    let mut current_field = String::new();
    let mut depth = 0;
    let mut in_string = false;
    let mut string_char = None;

    for ch in fields_str.chars() {
        match ch {
            '\'' | '"' if !in_string || Some(ch) == string_char => {
                if in_string {
                    in_string = false;
                    string_char = None;
                } else {
                    in_string = true;
                    string_char = Some(ch);
                }
                current_field.push(ch);
            }
            '<' if !in_string => {
                depth += 1;
                current_field.push(ch);
            }
            '>' if !in_string => {
                depth -= 1;
                current_field.push(ch);
            }
            ',' if !in_string && depth == 0 => {
                // End of current field
                let trimmed = current_field.trim();
                if !trimmed.is_empty()
                    && let Some((name, type_part)) = parse_field_definition(trimmed)
                {
                    fields.push((name, type_part));
                }
                current_field.clear();
            }
            _ => {
                current_field.push(ch);
            }
        }
    }

    // Handle last field
    let trimmed = current_field.trim();
    if !trimmed.is_empty()
        && let Some((name, type_part)) = parse_field_definition(trimmed)
    {
        fields.push((name, type_part));
    }

    Ok(fields)
}

/// Parse a single field definition (e.g., "ID: STRING" or "DETAILS: STRUCT<...>").
pub fn parse_field_definition(field_def: &str) -> Option<(String, String)> {
    // Split by colon, but handle nested STRUCTs
    let colon_pos = field_def.find(':')?;
    let name = field_def[..colon_pos].trim().to_string();
    let type_part = field_def[colon_pos + 1..].trim().to_string();

    if name.is_empty() || type_part.is_empty() {
        return None;
    }

    Some((name, type_part))
}

/// Convert a Column to ColumnData, preserving all ODCS v3.1.0 fields.
/// This is used when importers create Column objects internally and need to
/// return ColumnData in the ImportResult.
pub fn column_to_column_data(c: &Column) -> super::ColumnData {
    super::ColumnData {
        // Core Identity
        id: c.id.clone(),
        name: c.name.clone(),
        business_name: c.business_name.clone(),
        description: if c.description.is_empty() {
            None
        } else {
            Some(c.description.clone())
        },
        // Type Information
        data_type: c.data_type.clone(),
        physical_type: c.physical_type.clone(),
        physical_name: c.physical_name.clone(),
        logical_type_options: c.logical_type_options.clone(),
        // Key Constraints
        primary_key: c.primary_key,
        primary_key_position: c.primary_key_position,
        unique: c.unique,
        nullable: c.nullable,
        // Partitioning & Clustering
        partitioned: c.partitioned,
        partition_key_position: c.partition_key_position,
        clustered: c.clustered,
        // Data Classification & Security
        classification: c.classification.clone(),
        critical_data_element: c.critical_data_element,
        encrypted_name: c.encrypted_name.clone(),
        // Transformation Metadata
        transform_source_objects: c.transform_source_objects.clone(),
        transform_logic: c.transform_logic.clone(),
        transform_description: c.transform_description.clone(),
        // Examples & Documentation
        examples: c.examples.clone(),
        default_value: c.default_value.clone(),
        // Relationships & References
        relationships: c.relationships.clone(),
        authoritative_definitions: c.authoritative_definitions.clone(),
        // Quality & Validation
        quality: if c.quality.is_empty() {
            None
        } else {
            Some(c.quality.clone())
        },
        enum_values: if c.enum_values.is_empty() {
            None
        } else {
            Some(c.enum_values.clone())
        },
        // Tags & Custom Properties
        tags: c.tags.clone(),
        custom_properties: c.custom_properties.clone(),
    }
}

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

    #[test]
    fn test_normalize_data_type() {
        assert_eq!(normalize_data_type("string"), "STRING");
        assert_eq!(normalize_data_type("int"), "INT");
        assert_eq!(normalize_data_type("STRUCT<a: INT>"), "STRUCT<a: INT>");
        assert_eq!(normalize_data_type("array<string>"), "ARRAY<string>");
        assert_eq!(normalize_data_type("MAP<string, int>"), "MAP<string, int>");
    }

    #[test]
    fn test_parse_medallion_layer() {
        assert!(matches!(
            parse_medallion_layer("bronze").unwrap(),
            MedallionLayer::Bronze
        ));
        assert!(matches!(
            parse_medallion_layer("SILVER").unwrap(),
            MedallionLayer::Silver
        ));
        assert!(matches!(
            parse_medallion_layer("Gold").unwrap(),
            MedallionLayer::Gold
        ));
        assert!(parse_medallion_layer("invalid").is_err());
    }

    #[test]
    fn test_parse_scd_pattern() {
        assert!(matches!(
            parse_scd_pattern("TYPE_1").unwrap(),
            SCDPattern::Type1
        ));
        assert!(matches!(
            parse_scd_pattern("type2").unwrap(),
            SCDPattern::Type2
        ));
        assert!(parse_scd_pattern("invalid").is_err());
    }

    #[test]
    fn test_parse_data_vault_classification() {
        assert!(matches!(
            parse_data_vault_classification("hub").unwrap(),
            DataVaultClassification::Hub
        ));
        assert!(matches!(
            parse_data_vault_classification("LINK").unwrap(),
            DataVaultClassification::Link
        ));
        assert!(matches!(
            parse_data_vault_classification("sat").unwrap(),
            DataVaultClassification::Satellite
        ));
        assert!(parse_data_vault_classification("invalid").is_err());
    }

    #[test]
    fn test_parse_field_definition() {
        let result = parse_field_definition("name: STRING");
        assert!(result.is_some());
        let (name, type_part) = result.unwrap();
        assert_eq!(name, "name");
        assert_eq!(type_part, "STRING");

        let result = parse_field_definition("nested: STRUCT<a: INT, b: STRING>");
        assert!(result.is_some());
        let (name, type_part) = result.unwrap();
        assert_eq!(name, "nested");
        assert_eq!(type_part, "STRUCT<a: INT, b: STRING>");
    }

    #[test]
    fn test_parse_struct_fields_from_string() {
        let fields = parse_struct_fields_from_string("id: INT, name: STRING").unwrap();
        assert_eq!(fields.len(), 2);
        assert_eq!(fields[0], ("id".to_string(), "INT".to_string()));
        assert_eq!(fields[1], ("name".to_string(), "STRING".to_string()));

        let fields = parse_struct_fields_from_string(
            "id: INT, nested: STRUCT<a: INT, b: STRING>, name: STRING",
        )
        .unwrap();
        assert_eq!(fields.len(), 3);
        assert_eq!(fields[0], ("id".to_string(), "INT".to_string()));
        assert_eq!(
            fields[1],
            (
                "nested".to_string(),
                "STRUCT<a: INT, b: STRING>".to_string()
            )
        );
        assert_eq!(fields[2], ("name".to_string(), "STRING".to_string()));
    }
}