rh-codegen 0.1.0-beta.1

Code generation library for creating Rust types from FHIR StructureDefinitions
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
//! FHIR type generation functionality
//!
//! This module contains the main code generator that orchestrates the generation of Rust types
//! from FHIR StructureDefinitions using specialized sub-generators.

#![allow(dead_code)] // Allow unused code during refactoring transition

use std::collections::HashMap;
use std::path::Path;

use crate::config::CodegenConfig;
use crate::fhir_types::StructureDefinition;
use crate::generators::token_generator::TokenGenerator;
#[cfg(test)]
use crate::generators::ImportManager;
use crate::generators::{
    EnumGenerator, FieldGenerator, FileGenerator, FileIoManager, NestedStructGenerator,
    PrimitiveGenerator, StructGenerator, TraitGenerator, TypeRegistry, TypeUtilities,
};
use crate::rust_types::{RustEnum, RustStruct, RustTrait};
use crate::value_sets::ValueSetManager;
use crate::CodegenResult;

// Re-export from file_generator for backward compatibility
pub use crate::generators::file_generator::FhirTypeCategory;

/// Main code generator struct that orchestrates specialized generators
pub struct CodeGenerator {
    config: CodegenConfig,
    /// Cache of previously generated types to avoid regenerating the same struct
    type_cache: HashMap<String, RustStruct>,
    /// Cache of generated enums for value set bindings
    enum_cache: HashMap<String, RustEnum>,
    /// ValueSet manager for handling ValueSet operations
    value_set_manager: ValueSetManager,
    /// Token generator for generating Rust code
    token_generator: TokenGenerator,
}

impl CodeGenerator {
    #[allow(dead_code)] // Methods below are preserved during refactoring transition
    /// Create a new code generator with the given configuration
    pub fn new(config: CodegenConfig) -> Self {
        let value_set_manager = ValueSetManager::new();
        let token_generator = TokenGenerator::new();

        Self {
            config,
            type_cache: HashMap::new(),
            enum_cache: HashMap::new(),
            value_set_manager,
            token_generator,
        }
    }

    /// Create a new code generator with a ValueSet directory
    pub fn new_with_value_set_directory<P: AsRef<Path>>(
        config: CodegenConfig,
        value_set_dir: P,
    ) -> Self {
        let value_set_manager = ValueSetManager::new_with_directory(value_set_dir);
        let token_generator = TokenGenerator::new();

        Self {
            config,
            type_cache: HashMap::new(),
            enum_cache: HashMap::new(),
            value_set_manager,
            token_generator,
        }
    }

    /// Load and parse a FHIR StructureDefinition from a JSON file
    pub fn load_structure_definition<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> CodegenResult<StructureDefinition> {
        FileIoManager::load_structure_definition(path)
    }

    /// Generate a Rust struct from a FHIR StructureDefinition
    pub fn generate_struct(
        &mut self,
        structure_def: &StructureDefinition,
    ) -> CodegenResult<RustStruct> {
        // Register the type in the TypeRegistry based on its StructureDefinition
        TypeRegistry::register_from_structure_definition(structure_def);

        let mut struct_generator = StructGenerator::new(
            &self.config,
            &mut self.type_cache,
            &mut self.value_set_manager,
        );
        let rust_struct = struct_generator.generate_struct(structure_def)?;

        Ok(rust_struct)
    }

    /// Generate traits for a structure definition
    pub fn generate_trait(
        &mut self,
        structure_def: &StructureDefinition,
    ) -> CodegenResult<Vec<RustTrait>> {
        let crate_lib_name = self
            .config
            .crate_name
            .as_deref()
            .map(|n| n.replace('-', "_"))
            .unwrap_or_else(|| "hl7_fhir_r4_core".to_string());
        let mut trait_generator = TraitGenerator::new_with_crate_name(crate_lib_name);
        let mut traits = Vec::new();
        let categories = ["Accessors", "Mutators", "Existence"];

        for category in &categories {
            let rust_trait = trait_generator.generate_trait(structure_def, category)?;
            traits.push(rust_trait);
        }

        Ok(traits)
    }

    /// Generate a primitive type struct with special FHIR primitive type semantics
    fn generate_primitive_type_struct(
        &mut self,
        structure_def: &StructureDefinition,
        rust_struct: RustStruct,
    ) -> CodegenResult<RustStruct> {
        let mut primitive_generator = PrimitiveGenerator::new(&self.config, &mut self.type_cache);
        primitive_generator.generate_primitive_type_struct(structure_def, rust_struct)
    }

    /// Generate a type alias for primitive types
    fn generate_primitive_type_alias(
        &self,
        structure_def: &StructureDefinition,
    ) -> CodegenResult<crate::rust_types::RustTypeAlias> {
        let mut temp_cache = HashMap::new();
        let primitive_generator = PrimitiveGenerator::new(&self.config, &mut temp_cache);
        primitive_generator.generate_primitive_type_alias(structure_def)
    }

    /// Generate the companion Element struct for a primitive type
    fn generate_primitive_element_struct(
        &mut self,
        structure_def: &StructureDefinition,
    ) -> CodegenResult<RustStruct> {
        let mut primitive_generator = PrimitiveGenerator::new(&self.config, &mut self.type_cache);
        primitive_generator.generate_primitive_element_struct(structure_def)
    }

    /// Generate a nested struct for BackboneElements
    fn generate_nested_struct(
        &mut self,
        parent_struct_name: &str,
        nested_field_name: &str,
        nested_elements: &[crate::fhir_types::ElementDefinition],
        parent_structure_def: &StructureDefinition,
    ) -> CodegenResult<Option<crate::rust_types::RustStruct>> {
        let mut nested_struct_generator = NestedStructGenerator::new(
            &self.config,
            &mut self.type_cache,
            &mut self.value_set_manager,
        );
        nested_struct_generator.generate_nested_struct(
            parent_struct_name,
            nested_field_name,
            nested_elements,
            parent_structure_def,
        )
    }

    /// Create a RustField from an ElementDefinition
    fn create_field_from_element(
        &mut self,
        element: &crate::fhir_types::ElementDefinition,
    ) -> CodegenResult<Option<crate::rust_types::RustField>> {
        let mut field_generator =
            FieldGenerator::new(&self.config, &self.type_cache, &mut self.value_set_manager);
        field_generator.create_field_from_element(element)
    }

    /// Convert a FHIR field name to a valid Rust field name
    fn to_rust_field_name(&self, name: &str) -> String {
        crate::naming::Naming::field_name(name)
    }

    /// Generate a Rust struct and write it to the appropriate directory based on FHIR type classification
    pub fn generate_to_organized_directories<P: AsRef<Path>>(
        &mut self,
        structure_def: &StructureDefinition,
        base_output_dir: P,
    ) -> CodegenResult<()> {
        let rust_struct = self.generate_struct(structure_def)?;
        let nested_structs =
            FileIoManager::collect_nested_structs(&rust_struct.name, &self.type_cache);

        let file_io_manager = FileIoManager::new(&self.config, &self.token_generator);
        file_io_manager.generate_to_organized_directories(
            structure_def,
            base_output_dir,
            &rust_struct,
            &nested_structs,
        )
    }

    /// Generate traits and write them to the traits directory
    pub fn generate_trait_to_organized_directory<P: AsRef<Path>>(
        &mut self,
        structure_def: &StructureDefinition,
        base_output_dir: P,
    ) -> CodegenResult<()> {
        let rust_traits = self.generate_trait(structure_def)?;

        let file_io_manager = FileIoManager::new(&self.config, &self.token_generator);
        file_io_manager.generate_traits_to_organized_directory(
            structure_def,
            base_output_dir.as_ref(),
            &rust_traits,
        )
    }

    /// Classify a FHIR StructureDefinition into the appropriate category
    pub fn classify_fhir_structure_def(
        &self,
        structure_def: &StructureDefinition,
    ) -> FhirTypeCategory {
        let file_generator = FileGenerator::new(&self.config, &self.token_generator);
        file_generator.classify_fhir_structure_def(structure_def)
    }

    /// Check if a type name represents a known FHIR data type
    fn is_fhir_datatype(&self, name: &str) -> bool {
        TypeUtilities::is_fhir_datatype(name)
    }

    /// Generate a Rust struct and write it to a file
    pub fn generate_to_file<P: AsRef<Path>>(
        &mut self,
        structure_def: &StructureDefinition,
        output_path: P,
    ) -> CodegenResult<()> {
        if structure_def.kind == "primitive-type" {
            // For primitive types, use empty placeholder values
            let empty_struct = RustStruct::new("".to_string());
            let nested_structs = vec![];
            let file_io_manager = FileIoManager::new(&self.config, &self.token_generator);
            file_io_manager.generate_to_file(
                structure_def,
                output_path,
                &empty_struct,
                &nested_structs,
            )
        } else {
            // Generate the main struct for non-primitive types
            let rust_struct = self.generate_struct(structure_def)?;
            let nested_structs =
                FileIoManager::collect_nested_structs(&rust_struct.name, &self.type_cache);
            let file_io_manager = FileIoManager::new(&self.config, &self.token_generator);

            file_io_manager.generate_to_file(
                structure_def,
                output_path,
                &rust_struct,
                &nested_structs,
            )
        }
    }

    /// Generate a Rust trait and write it to a file
    pub fn generate_trait_to_file<P: AsRef<Path>>(
        &mut self,
        structure_def: &StructureDefinition,
        output_path: P,
    ) -> CodegenResult<()> {
        // Generate the trait first
        let rust_traits = self.generate_trait(structure_def)?;

        // Create FileIoManager and delegate
        let file_io_manager = FileIoManager::new(&self.config, &self.token_generator);

        // Use generate_traits_to_file to write all traits to the same file
        file_io_manager.generate_traits_to_file(
            structure_def,
            output_path.as_ref(),
            &rust_traits,
        )?;

        Ok(())
    }

    /// Pre-scan and register all ValueSet enums in the TypeRegistry
    /// This should be called before processing resources to ensure correct import paths
    pub fn pre_register_value_set_enums<P: AsRef<Path>>(
        &mut self,
        package_dir: P,
    ) -> CodegenResult<()> {
        let package_path = package_dir.as_ref();

        // Scan for ValueSet JSON files in the package directory
        if !package_path.exists() {
            return Ok(()); // Nothing to scan
        }

        let entries = match std::fs::read_dir(package_path) {
            Ok(entries) => entries,
            Err(_) => return Ok(()), // Can't read directory, skip
        };

        for entry in entries {
            let entry = match entry {
                Ok(entry) => entry,
                Err(_) => continue, // Skip problematic entries
            };

            let path = entry.path();
            if !path.is_file() || path.extension().is_none_or(|ext| ext != "json") {
                continue;
            }

            // Try to read and parse as ValueSet
            let content = match std::fs::read_to_string(&path) {
                Ok(content) => content,
                Err(_) => continue, // Skip unreadable files
            };

            let json_value: serde_json::Value = match serde_json::from_str(&content) {
                Ok(value) => value,
                Err(_) => continue, // Skip invalid JSON
            };

            // Check if this is a ValueSet resource
            if json_value.get("resourceType").and_then(|v| v.as_str()) != Some("ValueSet") {
                continue;
            }

            // Get the ValueSet URL to generate enum name
            if let Some(url) = json_value.get("url").and_then(|v| v.as_str()) {
                // Generate enum name using the same logic as the enum generator
                let enum_name = self.value_set_manager.generate_enum_name(url);

                // Pre-register this enum in the TypeRegistry
                crate::generators::type_registry::TypeRegistry::register_type_classification_only(
                    &enum_name,
                    crate::generators::type_registry::TypeClassification::ValueSetEnum,
                );
            }
        }

        Ok(())
    }

    /// Generate all ValueSet enums to separate files in the specified directory
    pub fn generate_enum_files<P: AsRef<Path>>(&mut self, enums_dir: P) -> CodegenResult<()> {
        let enum_generator = EnumGenerator::new(&mut self.value_set_manager, &mut self.enum_cache);
        let token_generator = crate::generators::token_generator::TokenGenerator::new();
        let file_generator = FileGenerator::new(&self.config, &token_generator);

        file_generator.generate_enum_files(enums_dir, &enum_generator)
    }

    /// Generate a mod.rs file that re-exports all the enum modules
    pub fn generate_enums_mod_file<P: AsRef<Path>>(&self, enums_dir: P) -> CodegenResult<()> {
        // Create an EnumGenerator with access to the cached enums
        let mut value_set_manager = self.value_set_manager.clone(); // Need to clone for borrow checker
        let mut enum_cache = self.enum_cache.clone();
        let enum_generator = EnumGenerator::new(&mut value_set_manager, &mut enum_cache);

        // Create FileGenerator and delegate
        let file_generator = FileGenerator::new(&self.config, &self.token_generator);
        file_generator.generate_enums_mod_file(enums_dir, &enum_generator)
    }

    /// Generate an enum for a value set binding
    pub fn generate_enum_for_value_set(
        &mut self,
        value_set_url: &str,
    ) -> CodegenResult<Option<RustEnum>> {
        let mut enum_generator =
            EnumGenerator::new(&mut self.value_set_manager, &mut self.enum_cache);
        let result = enum_generator.generate_enum_for_value_set(value_set_url)?;

        Ok(result)
    }

    /// Check if any ValueSet enums have been generated
    pub fn has_cached_enums(&self) -> bool {
        TypeUtilities::has_cached_enums(&self.value_set_manager)
    }

    /// Convert a FHIR resource type name to filename using snake_case
    pub fn to_filename(&self, structure_def: &StructureDefinition) -> String {
        crate::naming::Naming::filename(structure_def)
    }

    /// Generate a comprehensive Resource trait with common FHIR resource methods
    // pub fn generate_resource_trait(&mut self) -> CodegenResult<String> {
    //     let mut trait_generator = TraitGenerator::new();
    //     trait_generator.generate_resource_trait()
    // }
    /// Generate a trait file directly from a RustTrait object
    pub fn generate_trait_file_from_trait<P: AsRef<Path>>(
        &self,
        rust_trait: &RustTrait,
        output_path: P,
    ) -> CodegenResult<()> {
        // Create FileGenerator and delegate
        let file_generator = FileGenerator::new(&self.config, &self.token_generator);
        file_generator.generate_trait_file_from_trait(rust_trait, output_path)
    }

    // Generate an impl block for the Resource trait
    // pub fn generate_resource_impl(&self) -> String {
    //     let trait_generator = TraitGenerator::new();
    //     trait_generator.generate_resource_impl()
    // }
}

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

    #[test]
    fn test_to_valid_rust_identifier_conversion() {
        // Test FHIR resource names that should preserve original case
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("StructureDefinition"),
            "StructureDefinition"
        );
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("Patient"),
            "Patient"
        );
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("Observation"),
            "Observation"
        );
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("CodeSystem"),
            "CodeSystem"
        );

        // Test names that need conversion due to special characters
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("patient"),
            "patient"
        );

        // Test names with spaces
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("Relative Date Criteria"),
            "RelativeDateCriteria"
        );
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("Care Plan"),
            "CarePlan"
        );

        // Test names with dashes and underscores
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("patient-name"),
            "PatientName"
        );
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("patient_name"),
            "patient_name"
        );

        // Test mixed separators
        assert_eq!(
            crate::naming::Naming::to_rust_identifier("some-complex_name with.spaces"),
            "SomeComplexNameWithSpaces"
        );

        // Test empty and edge cases
        assert_eq!(crate::naming::Naming::to_rust_identifier(""), "_");
        assert_eq!(crate::naming::Naming::to_rust_identifier("   "), "_");
        assert_eq!(crate::naming::Naming::to_rust_identifier("a"), "a");
    }

    #[test]
    fn test_logical_model_skipping() {
        use crate::fhir_types::StructureDefinition;

        let config = CodegenConfig::default();
        let mut generator = CodeGenerator::new(config);

        // Create a test LogicalModel StructureDefinition
        let logical_model = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "test-logical-model".to_string(),
            url: "http://example.org/fhir/StructureDefinition/test-logical-model".to_string(),
            name: "test-logical-model".to_string(),
            title: Some("Test Logical Model".to_string()),
            status: "active".to_string(),
            kind: "logical".to_string(),
            is_abstract: false,
            description: Some("A test logical model".to_string()),
            purpose: None,
            base_type: "Base".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Base".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        // Test that LogicalModels are rejected
        let result = generator.generate_struct(&logical_model);
        assert!(result.is_err());

        if let Err(crate::CodegenError::Generation { message }) = result {
            assert!(message.contains("Skipping LogicalModel"));
            assert!(message.contains("test-logical-model"));
        } else {
            panic!("Expected CodegenError::Generation for LogicalModel");
        }
    }

    #[test]
    fn test_nested_struct_generation() {
        use crate::fhir_types::{
            ElementDefinition, ElementType, StructureDefinition, StructureDefinitionDifferential,
        };

        let config = CodegenConfig::default();
        let mut generator = CodeGenerator::new(config);

        // Create a simplified Bundle StructureDefinition with nested entry
        let bundle_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Bundle".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Bundle".to_string(),
            name: "Bundle".to_string(),
            title: Some("Bundle".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A container for a collection of resources".to_string()),
            purpose: None,
            base_type: "Bundle".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Resource".to_string()),
            version: None,
            differential: Some(StructureDefinitionDifferential {
                element: vec![
                    ElementDefinition {
                        id: Some("Bundle.entry".to_string()),
                        path: "Bundle.entry".to_string(),
                        short: Some("Entry in the bundle".to_string()),
                        definition: None,
                        min: Some(0),
                        max: Some("*".to_string()),
                        element_type: Some(vec![ElementType {
                            code: Some("BackboneElement".to_string()),
                            target_profile: None,
                        }]),
                        fixed: None,
                        pattern: None,
                        binding: None,
                        constraint: None,
                    },
                    ElementDefinition {
                        id: Some("Bundle.entry.resource".to_string()),
                        path: "Bundle.entry.resource".to_string(),
                        short: Some("A resource in the bundle".to_string()),
                        definition: None,
                        min: Some(0),
                        max: Some("1".to_string()),
                        element_type: Some(vec![ElementType {
                            code: Some("Resource".to_string()),
                            target_profile: None,
                        }]),
                        fixed: None,
                        pattern: None,
                        binding: None,
                        constraint: None,
                    },
                ],
            }),
            snapshot: None,
        };

        // Generate the struct
        let result = generator.generate_struct(&bundle_structure);
        assert!(result.is_ok());

        let bundle_struct = result.unwrap();

        // Check that the main Bundle struct was generated
        assert_eq!(bundle_struct.name, "Bundle");

        // Check that an entry field exists
        let entry_field = bundle_struct.fields.iter().find(|f| f.name == "entry");
        assert!(entry_field.is_some(), "Bundle should have an entry field");

        // Check that the nested BundleEntry struct was generated and cached
        assert!(
            generator.type_cache.contains_key("BundleEntry"),
            "BundleEntry struct should be generated"
        );

        let bundle_entry_struct = generator.type_cache.get("BundleEntry").unwrap();
        assert_eq!(bundle_entry_struct.name, "BundleEntry");

        // Check that BundleEntry has the expected fields
        let resource_field = bundle_entry_struct
            .fields
            .iter()
            .find(|f| f.name == "resource");
        assert!(
            resource_field.is_some(),
            "BundleEntry should have a resource field"
        );
    }

    #[test]
    fn test_primitive_type_naming() {
        use crate::fhir_types::StructureDefinition;

        // Test primitive type - should not be capitalized
        let primitive_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "string".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/string".to_string(),
            name: "string".to_string(),
            title: Some("string".to_string()),
            status: "active".to_string(),
            kind: "primitive-type".to_string(),
            is_abstract: false,
            description: Some("A sequence of Unicode characters".to_string()),
            purpose: None,
            base_type: "string".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Element".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        // Test that primitive types are not capitalized
        let struct_name = crate::naming::Naming::struct_name(&primitive_structure);
        assert_eq!(
            struct_name, "string",
            "Primitive type 'string' should not be capitalized"
        );

        let filename = crate::naming::Naming::filename(&primitive_structure);
        assert_eq!(
            filename, "string.rs",
            "Primitive type filename should not be capitalized"
        );

        // Test another primitive type
        let boolean_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "boolean".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/boolean".to_string(),
            name: "boolean".to_string(),
            title: Some("boolean".to_string()),
            status: "active".to_string(),
            kind: "primitive-type".to_string(),
            is_abstract: false,
            description: Some("Value of 'true' or 'false'".to_string()),
            purpose: None,
            base_type: "boolean".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Element".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        let struct_name = crate::naming::Naming::struct_name(&boolean_structure);
        assert_eq!(
            struct_name, "boolean",
            "Primitive type 'boolean' should not be capitalized"
        );

        // Test complex type - should be capitalized
        let complex_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Period".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Period".to_string(),
            name: "Period".to_string(),
            title: Some("Period".to_string()),
            status: "active".to_string(),
            kind: "complex-type".to_string(),
            is_abstract: false,
            description: Some("A time period defined by a start and end date".to_string()),
            purpose: None,
            base_type: "Period".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Element".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        let struct_name = crate::naming::Naming::struct_name(&complex_structure);
        assert_eq!(
            struct_name, "Period",
            "Complex type 'Period' should be capitalized"
        );
    }

    #[test]
    fn test_primitive_type_generation() {
        use crate::fhir_types::StructureDefinition;
        use crate::rust_types::RustType;

        let config = CodegenConfig::default();
        let mut generator = CodeGenerator::new(config);

        // Test primitive type generation
        let uri_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "uri".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/uri".to_string(),
            name: "uri".to_string(),
            title: Some("uri".to_string()),
            status: "active".to_string(),
            kind: "primitive-type".to_string(),
            is_abstract: false,
            description: Some(
                "String of characters used to identify a name or a resource".to_string(),
            ),
            purpose: None,
            base_type: "uri".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Element".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        // Test that primitive type alias is generated correctly
        let type_alias_result = generator.generate_primitive_type_alias(&uri_structure);
        assert!(
            type_alias_result.is_ok(),
            "Should generate primitive type alias successfully"
        );

        let uri_type_alias = type_alias_result.unwrap();

        // Check that the type alias name follows the new PascalCase Type suffix convention
        assert_eq!(
            uri_type_alias.name, "UriType",
            "Primitive type alias should use PascalCase with Type suffix"
        );

        // Check that the type alias target is String for uri
        if let RustType::String = uri_type_alias.target_type {
            // Expected
        } else {
            panic!(
                "URI primitive type alias should target String, got: {:?}",
                uri_type_alias.target_type
            );
        }

        // Test boolean primitive type
        let boolean_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "boolean".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/boolean".to_string(),
            name: "boolean".to_string(),
            title: Some("boolean".to_string()),
            status: "active".to_string(),
            kind: "primitive-type".to_string(),
            is_abstract: false,
            description: Some("Value of 'true' or 'false'".to_string()),
            purpose: None,
            base_type: "boolean".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Element".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        let type_alias_result = generator.generate_primitive_type_alias(&boolean_structure);
        assert!(
            type_alias_result.is_ok(),
            "Should generate boolean primitive type alias successfully"
        );

        let boolean_type_alias = type_alias_result.unwrap();

        // Check that the boolean type alias targets bool
        if let RustType::Boolean = boolean_type_alias.target_type {
            // Expected
        } else {
            panic!(
                "Boolean primitive type alias should target bool, got: {:?}",
                boolean_type_alias.target_type
            );
        }

        // Test that the companion Element struct is generated
        let element_struct = generator.generate_primitive_element_struct(&uri_structure);
        assert!(
            element_struct.is_ok(),
            "Should generate companion Element struct successfully"
        );

        let element_struct = element_struct.unwrap();
        assert_eq!(
            element_struct.name, "_uri",
            "Companion Element struct should be named '_uri'"
        );
        assert_eq!(
            element_struct.base_definition,
            Some("Element".to_string()),
            "Companion Element struct should inherit from Element"
        );
    }

    #[test]
    fn test_trait_generation() {
        use crate::fhir_types::{
            ElementDefinition, ElementType, StructureDefinition, StructureDefinitionDifferential,
        };

        let config = CodegenConfig::default();
        let mut generator = CodeGenerator::new(config);

        // Create a simplified Patient StructureDefinition for trait generation
        let patient_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Patient".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Patient".to_string(),
            name: "Patient".to_string(),
            title: Some("Patient".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("Demographics and other administrative information about an individual receiving care.".to_string()),
            purpose: None,
            base_type: "DomainResource".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/DomainResource".to_string()),
            version: None,
            differential: Some(StructureDefinitionDifferential {
                element: vec![
                    ElementDefinition {
                        id: Some("Patient.active".to_string()),
                        path: "Patient.active".to_string(),
                        short: Some("Whether this patient record is in active use".to_string()),
                        definition: Some("Whether this patient record is in active use".to_string()),
                        min: Some(0),
                        max: Some("1".to_string()),
                        element_type: Some(vec![ElementType {
                            code: Some("boolean".to_string()),
                            target_profile: None,
                        }]),
                        fixed: None,
                        pattern: None,
                        binding: None,
                        constraint: None,
                    },
                    ElementDefinition {
                        id: Some("Patient.name".to_string()),
                        path: "Patient.name".to_string(),
                        short: Some("A name associated with the patient".to_string()),
                        definition: Some("A name associated with the patient".to_string()),
                        min: Some(0),
                        max: Some("*".to_string()),
                        element_type: Some(vec![ElementType {
                            code: Some("HumanName".to_string()),
                            target_profile: None,
                        }]),
                        fixed: None,
                        pattern: None,
                        binding: None,
                        constraint: None,
                    },
                ],
            }),
            snapshot: None,
        };

        // Generate the trait
        let result = generator.generate_trait(&patient_structure);
        assert!(result.is_ok(), "Should generate Patient trait successfully");

        let patient_traits = result.unwrap();
        let patient_trait = patient_traits
            .iter()
            .find(|t| t.name == "PatientAccessors")
            .expect("PatientAccessors trait not found");

        assert_eq!(
            patient_trait.name, "PatientAccessors",
            "Trait should be named 'PatientAccessors'"
        );

        // Check that the Patient trait properly inherits from DomainResource
        assert!(
            patient_trait
                .super_traits
                .contains(&"DomainResourceAccessors".to_string()),
            "Patient trait should inherit from DomainResourceAccessors"
        );

        // The Patient trait should NOT have methods that are inherited from parent traits
        let has_extensions = patient_trait.methods.iter().any(|m| m.name == "extensions");
        assert!(
            !has_extensions,
            "Patient trait should NOT have extensions method - it should be inherited from Resource"
        );

        let has_narrative = patient_trait.methods.iter().any(|m| m.name == "narrative");
        assert!(
            !has_narrative,
            "Patient trait should NOT have narrative method - it should be inherited from DomainResource"
        );

        let has_id = patient_trait.methods.iter().any(|m| m.name == "id");
        assert!(
            !has_id,
            "Patient trait should NOT have id method - it should be inherited from Resource"
        );

        // Note: The new trait generator focuses on resource-level methods rather than
        // field-specific methods like 'active' and 'name', which are handled by struct implementations
    }

    #[test]
    fn test_filename_generation() {
        // Test PascalCase struct names generate snake_case filenames
        let patient_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Patient".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Patient".to_string(),
            name: "Patient".to_string(),
            title: Some("Patient".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A patient resource".to_string()),
            purpose: None,
            base_type: "DomainResource".to_string(),
            base_definition: Some(
                "http://hl7.org/fhir/StructureDefinition/DomainResource".to_string(),
            ),
            version: None,
            differential: None,
            snapshot: None,
        };

        let observation_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Observation".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Observation".to_string(),
            name: "Observation".to_string(),
            title: Some("Observation".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("An observation resource".to_string()),
            purpose: None,
            base_type: "DomainResource".to_string(),
            base_definition: Some(
                "http://hl7.org/fhir/StructureDefinition/DomainResource".to_string(),
            ),
            version: None,
            differential: None,
            snapshot: None,
        };

        // Test that struct names remain PascalCase
        let patient_struct_name = crate::naming::Naming::struct_name(&patient_structure);
        assert_eq!(patient_struct_name, "Patient");

        let observation_struct_name = crate::naming::Naming::struct_name(&observation_structure);
        assert_eq!(observation_struct_name, "Observation");

        // Test that filenames are snake_case
        let patient_filename = crate::naming::Naming::filename(&patient_structure);
        assert_eq!(patient_filename, "patient.rs");

        let observation_filename = crate::naming::Naming::filename(&observation_structure);
        assert_eq!(observation_filename, "observation.rs");

        // Test more complex PascalCase names
        let structure_definition = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "StructureDefinition".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/StructureDefinition".to_string(),
            name: "StructureDefinition".to_string(),
            title: Some("StructureDefinition".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A structure definition".to_string()),
            purpose: None,
            base_type: "DomainResource".to_string(),
            base_definition: Some(
                "http://hl7.org/fhir/StructureDefinition/DomainResource".to_string(),
            ),
            version: None,
            differential: None,
            snapshot: None,
        };

        let struct_def_struct_name = crate::naming::Naming::struct_name(&structure_definition);
        assert_eq!(struct_def_struct_name, "StructureDefinition");

        let struct_def_filename = crate::naming::Naming::filename(&structure_definition);
        assert_eq!(struct_def_filename, "structure_definition.rs");

        // Test enum filename generation
        let enum_filename = crate::naming::Naming::enum_filename("AdministrativeGender");
        assert_eq!(enum_filename, "administrative_gender.rs");

        let enum_module_name = crate::naming::Naming::module_name("AdministrativeGender");
        assert_eq!(enum_module_name, "administrative_gender");
    }

    #[test]
    fn test_import_classification() {
        // Test resource classification
        assert!(ImportManager::is_fhir_resource_type("DomainResource"));
        assert!(ImportManager::is_fhir_resource_type("Patient"));
        assert!(ImportManager::is_fhir_resource_type("ActivityDefinition"));
        assert!(!ImportManager::is_fhir_resource_type("Identifier"));

        // Test datatype classification
        assert!(ImportManager::is_fhir_datatype("Identifier"));
        assert!(ImportManager::is_fhir_datatype("CodeableConcept"));
        assert!(ImportManager::is_fhir_datatype("Reference"));
        assert!(!ImportManager::is_fhir_datatype("DomainResource"));

        // Test import path generation
        assert_eq!(
            ImportManager::get_import_path_for_type("DomainResource"),
            "crate::resources::domain_resource::DomainResource"
        );
        assert_eq!(
            ImportManager::get_import_path_for_type("Identifier"),
            "crate::datatypes::identifier::Identifier"
        );
        assert_eq!(
            ImportManager::get_import_path_for_type("PublicationStatus"),
            "crate::bindings::publication_status::PublicationStatus"
        );
    }
}