ftm-types 0.1.1

FollowTheMoney types code generator for Rust
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
//! Code generation for FTM schemas
//!
//! Generates type-safe Rust structs from FTM schema definitions.

use anyhow::{Context, Result};
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use std::fs;
use std::path::{Path, PathBuf};

use crate::schema::{ResolvedSchema, SchemaRegistry};

/// Code generator for FTM schemas
pub struct CodeGenerator {
    registry: SchemaRegistry,
    output_dir: PathBuf,
}

impl CodeGenerator {
    /// Create a new code generator
    pub fn new(registry: SchemaRegistry, output_dir: impl AsRef<Path>) -> Self {
        Self {
            registry,
            output_dir: output_dir.as_ref().to_path_buf(),
        }
    }

    /// Generate all code files
    pub fn generate_all(&self) -> Result<()> {
        // Create output directory
        fs::create_dir_all(&self.output_dir).context(format!(
            "Failed to create output directory: {:?}",
            self.output_dir
        ))?;

        println!("\nGenerating code...");

        // Generate entity structs
        let entities_code = self.generate_entity_structs()?;
        self.write_module("entities.rs", entities_code)?;
        println!("  ✓ entities.rs");

        // Generate FtmEntity enum
        let enum_code = self.generate_ftm_entity_enum()?;
        self.write_module("ftm_entity.rs", enum_code)?;
        println!("  ✓ ftm_entity.rs");

        // Generate traits for abstract schemas
        let traits_code = self.generate_traits()?;
        self.write_module("traits.rs", traits_code)?;
        println!("  ✓ traits.rs");

        // Generate trait implementations
        let trait_impls_code = self.generate_trait_implementations()?;
        self.write_module("trait_impls.rs", trait_impls_code)?;
        println!("  ✓ trait_impls.rs");

        // Generate mod.rs
        let mod_code = self.generate_mod_file();
        self.write_module("mod.rs", mod_code)?;
        println!("  ✓ mod.rs");

        Ok(())
    }

    /// Generate entity structs for all concrete schemas
    fn generate_entity_structs(&self) -> Result<TokenStream> {
        let mut structs = Vec::new();

        for schema_name in self.registry.schema_names() {
            let resolved = self.registry.resolve_inheritance(&schema_name)?;

            // Skip abstract schemas
            if resolved.is_abstract() {
                continue;
            }

            let struct_code = self.generate_entity_struct(&resolved)?;
            structs.push(struct_code);
        }

        Ok(quote! {
            // Auto-generated - DO NOT EDIT
            #![allow(missing_docs)]

            use serde::{Deserialize, Serialize};

            #[cfg(feature = "builder")] use bon::Builder;

            /// Deserialize a `Vec<f64>` whose elements may arrive as JSON strings
            /// (e.g. `["6000.00"]`) or as JSON numbers (e.g. `[6000.0]`).
            fn deserialize_f64_vec<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                Vec::<serde_json::Value>::deserialize(deserializer)?
                    .into_iter()
                    .map(|v| match v {
                        serde_json::Value::Number(n) => {
                            n.as_f64().ok_or_else(|| serde::de::Error::custom("number out of f64 range"))
                        }
                        serde_json::Value::String(s) => {
                            s.parse::<f64>().map_err(serde::de::Error::custom)
                        }
                        other => Err(serde::de::Error::custom(
                            format!("expected number or numeric string, got {other}")
                        )),
                    })
                    .collect()
            }

            /// Same as [`deserialize_f64_vec`] but wrapped in `Some`.
            /// Used for optional number fields so the field can still be absent (`None`)
            /// while a present value tolerates string-encoded numbers.
            fn deserialize_opt_f64_vec<'de, D>(deserializer: D) -> Result<Option<Vec<f64>>, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                deserialize_f64_vec(deserializer).map(Some)
            }

            #(#structs)*
        })
    }

    /// Generate a single entity struct
    fn generate_entity_struct(&self, schema: &ResolvedSchema) -> Result<TokenStream> {
        let struct_name = Ident::new(&schema.name, Span::call_site());
        let label = schema.label().unwrap_or(&schema.name);
        let doc_comment = format!("FTM Schema: {}", label);
        let schema_name_str = &schema.name;

        // Generate fields
        let mut fields = Vec::new();

        // Add id field (required for all entities)
        fields.push(quote! {
            pub id: String
        });

        // Add schema field (always the schema name)
        // For builder: automatically set to the schema name
        // Use LitStr to create a proper string literal token
        let schema_lit = proc_macro2::Literal::string(schema_name_str);
        fields.push(quote! {
            #[cfg_attr(feature = "builder", builder(default = #schema_lit.to_string()))]
            pub schema: String
        });

        // Add properties
        let mut property_names: Vec<_> = schema.all_properties.keys().collect();
        property_names.sort();

        for prop_name in &property_names {
            let property = &schema.all_properties[*prop_name];
            let field_name = self.property_to_field_name(prop_name);

            // FTM default type for untyped properties is "string"
            let prop_type = property.type_.as_deref().unwrap_or("string");

            let is_required = schema.all_required.contains(*prop_name);
            let field_type = self.map_property_type(prop_type, is_required);

            let field_doc = if let Some(label) = &property.label {
                format!("Property: {}", label)
            } else {
                format!("Property: {}", prop_name)
            };

            // Required fields don't skip serializing if empty and are required in builder
            // Note: Option<_> fields don't need builder(default) as they default to None automatically
            let serde_attr = match (prop_type, is_required) {
                // Required number fields: tolerate string-encoded values and absent fields.
                ("number", true) => {
                    quote! { #[serde(deserialize_with = "deserialize_f64_vec", default)] }
                }
                // Optional number fields: same tolerance; `default` makes absent → None.
                ("number", false) => {
                    quote! { #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_opt_f64_vec", default)] }
                }
                // Required Vec<String> / Vec<date> fields: default to empty vec when absent.
                // Real-world FTM data often omits fields that the schema marks required (e.g.
                // `name` on Payment entities), so we tolerate the absence rather than hard-error.
                (_, true) => quote! { #[serde(default)] },
                (_, false) => quote! { #[serde(skip_serializing_if = "Option::is_none")] },
            };

            fields.push(quote! {
                #[doc = #field_doc]
                #serde_attr
                pub #field_name: #field_type
            });
        }

        // Generate field initializers for new() method
        let mut field_inits = vec![
            quote! { id: id.into() },
            quote! { schema: #schema_name_str.to_string() },
        ];

        // Initialize all other fields
        for prop_name in &property_names {
            let property = &schema.all_properties[*prop_name];
            let field_name = self.property_to_field_name(prop_name);

            let prop_type = property.type_.as_deref().unwrap_or("string");

            let is_required = schema.all_required.contains(*prop_name);

            let init_value = if is_required {
                // Required fields get a default empty value
                match prop_type {
                    "json" => quote! { serde_json::Value::Object(serde_json::Map::new()) },
                    _ => quote! { Vec::new() },
                }
            } else {
                // Optional fields are None
                quote! { None }
            };

            field_inits.push(quote! { #field_name: #init_value });
        }

        Ok(quote! {
            #[doc = #doc_comment]
            #[derive(Debug, Clone, Serialize, Deserialize)]
            #[cfg_attr(feature = "builder", derive(Builder))]
            #[serde(rename_all = "camelCase")]
            pub struct #struct_name {
                #(#fields),*
            }

            impl #struct_name {
                /// Create a new entity with the given ID
                #[deprecated(note = "Use the builder() method instead to ensure required fields are set")]
                pub fn new(id: impl Into<String>) -> Self {
                    Self {
                        #(#field_inits),*
                    }
                }

                /// Get the schema name
                pub fn schema_name() -> &'static str {
                    #schema_name_str
                }

                /// Serialize to standard FTM nested JSON format
                ///
                /// Produces `{"id": "...", "schema": "...", "properties": {...}}`
                pub fn to_ftm_json(&self) -> Result<String, serde_json::Error> {
                    let mut value = serde_json::to_value(self)?;
                    if let Some(obj) = value.as_object_mut() {
                        let id = obj.remove("id");
                        let schema = obj.remove("schema");
                        let properties = serde_json::Value::Object(std::mem::take(obj));
                        if let Some(id) = id { obj.insert("id".into(), id); }
                        if let Some(schema) = schema { obj.insert("schema".into(), schema); }
                        obj.insert("properties".into(), properties);
                    }
                    serde_json::to_string(&value)
                }
            }
        })
    }

    /// Generate the FtmEntity enum
    fn generate_ftm_entity_enum(&self) -> Result<TokenStream> {
        let mut variants = Vec::new();
        let mut match_schema_arms = Vec::new();
        let mut match_id_arms = Vec::new();
        let mut dispatch_arms = Vec::new();
        let mut from_impls = Vec::new();

        for schema_name in self.registry.schema_names() {
            let resolved = self.registry.resolve_inheritance(&schema_name)?;

            // Skip abstract schemas
            if resolved.is_abstract() {
                continue;
            }

            let variant_name = Ident::new(&schema_name, Span::call_site());
            let type_name = Ident::new(&schema_name, Span::call_site());

            variants.push(quote! {
                #variant_name(#type_name)
            });

            match_schema_arms.push(quote! {
                FtmEntity::#variant_name(_) => #schema_name
            });

            match_id_arms.push(quote! {
                FtmEntity::#variant_name(entity) => &entity.id
            });

            dispatch_arms.push(quote! {
                #schema_name => Ok(FtmEntity::#variant_name(serde_json::from_value(value)?))
            });

            from_impls.push(quote! {
                impl From<#type_name> for FtmEntity {
                    fn from(entity: #type_name) -> Self {
                        FtmEntity::#variant_name(entity)
                    }
                }
            });
        }

        Ok(quote! {
            // Auto-generated - DO NOT EDIT
            #![allow(missing_docs)]

            use super::entities::*;
            use serde::{Deserialize, Serialize};
            use serde_json::Value;

            /// FTM Entity enum for runtime polymorphism
            #[derive(Debug, Clone, Serialize, Deserialize)]
            #[serde(untagged)]
            #[allow(clippy::large_enum_variant)]
            pub enum FtmEntity {
                #(#variants),*
            }

            impl FtmEntity {
                /// Get the schema name for this entity
                pub fn schema(&self) -> &str {
                    match self {
                        #(#match_schema_arms),*
                    }
                }

                /// Get the entity ID
                pub fn id(&self) -> &str {
                    match self {
                        #(#match_id_arms),*
                    }
                }

                /// Parse FTM entity from nested JSON format
                ///
                /// The standard FTM JSON format has a nested structure:
                /// ```json
                /// {
                ///   "id": "...",
                ///   "schema": "Payment",
                ///   "properties": {
                ///     "amount": ["100"],
                ///     "date": ["2024-01-01"]
                ///   }
                /// }
                /// ```
                ///
                /// This function flattens the structure to match the generated Rust types.
                /// Dispatch is done on the `"schema"` field, so the correct variant is always
                /// selected regardless of declaration order in the enum.
                pub fn from_ftm_json(json_str: &str) -> Result<Self, serde_json::Error> {
                    let mut value: Value = serde_json::from_str(json_str)?;

                    if let Some(obj) = value.as_object_mut()
                        && let Some(properties) = obj.remove("properties")
                        && let Some(props_obj) = properties.as_object()
                    {
                        for (key, val) in props_obj {
                            obj.insert(key.clone(), val.clone());
                        }
                    }

                    let schema = value
                        .get("schema")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");

                    match schema {
                        #(#dispatch_arms,)*
                        _ => Err(serde::de::Error::custom(
                            format!("unknown FTM schema: {schema:?}")
                        )),
                    }
                }

                /// Serialize to standard FTM nested JSON format
                ///
                /// Produces `{"id": "...", "schema": "...", "properties": {...}}`
                pub fn to_ftm_json(&self) -> Result<String, serde_json::Error> {
                    let mut value = serde_json::to_value(self)?;
                    if let Some(obj) = value.as_object_mut() {
                        let id = obj.remove("id");
                        let schema = obj.remove("schema");
                        let properties = serde_json::Value::Object(std::mem::take(obj));
                        if let Some(id) = id { obj.insert("id".into(), id); }
                        if let Some(schema) = schema { obj.insert("schema".into(), schema); }
                        obj.insert("properties".into(), properties);
                    }
                    serde_json::to_string(&value)
                }
            }

            impl TryFrom<String> for FtmEntity {
                type Error = serde_json::Error;

                fn try_from(s: String) -> Result<Self, Self::Error> {
                    Self::from_ftm_json(&s)
                }
            }

            impl TryFrom<&str> for FtmEntity {
                type Error = serde_json::Error;

                fn try_from(s: &str) -> Result<Self, Self::Error> {
                    Self::from_ftm_json(s)
                }
            }

            #(#from_impls)*
        })
    }

    /// Generate mod.rs file
    fn generate_mod_file(&self) -> TokenStream {
        quote! {
            // Auto-generated - DO NOT EDIT
            #![allow(missing_docs)]

            pub mod entities;
            pub mod ftm_entity;
            pub mod trait_impls;
            pub mod traits;

            pub use entities::*;
            pub use ftm_entity::FtmEntity;
            pub use traits::*;
        }
    }

    /// Generate trait definitions for abstract schemas
    fn generate_traits(&self) -> Result<TokenStream> {
        let mut traits = Vec::new();

        for schema_name in self.registry.schema_names() {
            let schema = self
                .registry
                .get(&schema_name)
                .context(format!("Schema not found: {}", schema_name))?;

            // Only generate traits for abstract schemas
            if !schema.abstract_.unwrap_or(false) {
                continue;
            }

            let trait_code = self.generate_trait(&schema_name, schema)?;
            traits.push(trait_code);
        }

        Ok(quote! {
            // Auto-generated - DO NOT EDIT
            #![allow(missing_docs)]

            /// Traits representing FTM schema inheritance hierarchy.
            ///
            /// These traits enable polymorphic code that works across entity types.
            /// All concrete entity structs implement the traits for their parent schemas.

            #(#traits)*
        })
    }

    /// Generate a single trait definition for an abstract schema
    fn generate_trait(
        &self,
        schema_name: &str,
        schema: &crate::schema::FtmSchema,
    ) -> Result<TokenStream> {
        let trait_name = Ident::new(schema_name, Span::call_site());
        let doc_comment = format!(
            "Trait for FTM schema: {}",
            schema.label.as_deref().unwrap_or(schema_name)
        );

        // Determine parent traits
        let parent_traits: Vec<TokenStream> = if let Some(extends) = &schema.extends {
            extends
                .iter()
                .map(|parent| {
                    let parent_ident = Ident::new(parent, Span::call_site());
                    quote! { #parent_ident }
                })
                .collect()
        } else {
            vec![]
        };

        let trait_bounds = if parent_traits.is_empty() {
            quote! {}
        } else {
            quote! { : #(#parent_traits)+* }
        };

        // Generate trait methods for properties
        let mut methods = Vec::new();

        // Add id and schema methods (all entities have these)
        methods.push(quote! {
            /// Get the entity ID
            fn id(&self) -> &str;
        });

        methods.push(quote! {
            /// Get the schema name
            fn schema(&self) -> &str;
        });

        // Add property accessor methods
        let mut property_names: Vec<_> = schema.properties.keys().collect();
        property_names.sort();

        for prop_name in property_names {
            let property = &schema.properties[prop_name];
            let method_name = self.property_to_field_name(prop_name);

            let prop_type = property.type_.as_deref().unwrap_or("string");

            let return_type = match prop_type {
                "number" => quote! { Option<&[f64]> },
                "json" => quote! { Option<&serde_json::Value> },
                _ => quote! { Option<&[String]> },
            };

            let method_doc = if let Some(label) = &property.label {
                format!("Get {} property", label)
            } else {
                format!("Get {} property", prop_name)
            };

            methods.push(quote! {
                #[doc = #method_doc]
                fn #method_name(&self) -> #return_type;
            });
        }

        Ok(quote! {
            #[doc = #doc_comment]
            pub trait #trait_name #trait_bounds {
                #(#methods)*
            }
        })
    }

    /// Generate trait implementations for concrete schemas
    fn generate_trait_implementations(&self) -> Result<TokenStream> {
        let mut impls = Vec::new();

        for schema_name in self.registry.schema_names() {
            let resolved = self.registry.resolve_inheritance(&schema_name)?;

            // Only generate impls for concrete schemas
            if resolved.is_abstract() {
                continue;
            }

            let impl_code = self.generate_trait_impls_for_entity(&resolved)?;
            impls.extend(impl_code);
        }

        Ok(quote! {
            // Auto-generated - DO NOT EDIT
            #![allow(missing_docs)]

            use super::entities::*;
            use super::traits::*;

            #(#impls)*
        })
    }

    /// Generate all trait implementations for a single entity
    fn generate_trait_impls_for_entity(&self, schema: &ResolvedSchema) -> Result<Vec<TokenStream>> {
        let mut impls = Vec::new();
        let struct_name = Ident::new(&schema.name, Span::call_site());

        // Get all parent schemas (including transitive parents)
        let parent_schemas = self.get_all_parent_schemas(&schema.name)?;

        // Generate impl for each parent trait
        for parent_name in parent_schemas {
            let parent_schema = self
                .registry
                .get(&parent_name)
                .context(format!("Parent schema not found: {}", parent_name))?;

            // Only implement traits for abstract schemas
            if !parent_schema.abstract_.unwrap_or(false) {
                continue;
            }

            let trait_name = Ident::new(&parent_name, Span::call_site());
            let mut methods = Vec::new();

            // Implement id and schema methods
            methods.push(quote! {
                fn id(&self) -> &str {
                    &self.id
                }
            });

            methods.push(quote! {
                fn schema(&self) -> &str {
                    &self.schema
                }
            });

            // Implement property accessor methods
            let mut property_names: Vec<_> = parent_schema.properties.keys().collect();
            property_names.sort();

            for prop_name in property_names {
                let property = &parent_schema.properties[prop_name];
                let method_name = self.property_to_field_name(prop_name);
                let field_name = self.property_to_field_name(prop_name);

                let prop_type = property.type_.as_deref().unwrap_or("string");

                // Check if this property is required in the concrete schema
                let is_required = schema.all_required.contains(prop_name);

                let method_impl = if is_required {
                    // Required fields return a direct reference
                    match prop_type {
                        "number" => quote! {
                            fn #method_name(&self) -> Option<&[f64]> {
                                Some(&self.#field_name)
                            }
                        },
                        "json" => quote! {
                            fn #method_name(&self) -> Option<&serde_json::Value> {
                                Some(&self.#field_name)
                            }
                        },
                        _ => quote! {
                            fn #method_name(&self) -> Option<&[String]> {
                                Some(&self.#field_name)
                            }
                        },
                    }
                } else {
                    // Optional fields use as_deref/as_ref
                    match prop_type {
                        "number" => quote! {
                            fn #method_name(&self) -> Option<&[f64]> {
                                self.#field_name.as_deref()
                            }
                        },
                        "json" => quote! {
                            fn #method_name(&self) -> Option<&serde_json::Value> {
                                self.#field_name.as_ref()
                            }
                        },
                        _ => quote! {
                            fn #method_name(&self) -> Option<&[String]> {
                                self.#field_name.as_deref()
                            }
                        },
                    }
                };

                methods.push(method_impl);
            }

            impls.push(quote! {
                impl #trait_name for #struct_name {
                    #(#methods)*
                }
            });
        }

        Ok(impls)
    }

    /// Get all parent schemas (including transitive parents) for a given schema
    fn get_all_parent_schemas(&self, schema_name: &str) -> Result<Vec<String>> {
        let mut parents_set = std::collections::HashSet::new();
        let mut visited = std::collections::HashSet::new();
        self.collect_parents_recursive(schema_name, &mut parents_set, &mut visited)?;

        // Convert to Vec for iteration
        let mut parents: Vec<String> = parents_set.into_iter().collect();
        parents.sort(); // Sort for consistent output
        Ok(parents)
    }

    /// Recursively collect parent schemas
    fn collect_parents_recursive(
        &self,
        schema_name: &str,
        parents: &mut std::collections::HashSet<String>,
        visited: &mut std::collections::HashSet<String>,
    ) -> Result<()> {
        if visited.contains(schema_name) {
            return Ok(());
        }
        visited.insert(schema_name.to_string());

        let schema = self
            .registry
            .get(schema_name)
            .context(format!("Schema not found: {}", schema_name))?;

        if let Some(extends) = &schema.extends {
            for parent_name in extends {
                parents.insert(parent_name.clone());
                self.collect_parents_recursive(parent_name, parents, visited)?;
            }
        }

        Ok(())
    }

    /// Map FTM property types to Rust types
    fn map_property_type(&self, ftm_type: &str, is_required: bool) -> TokenStream {
        if is_required {
            // Required fields are not wrapped in Option
            match ftm_type {
                "number" => quote! { Vec<f64> },
                "date" => quote! { Vec<String> },
                "json" => quote! { serde_json::Value },
                _ => quote! { Vec<String> },
            }
        } else {
            // Optional fields are wrapped in Option
            match ftm_type {
                "number" => quote! { Option<Vec<f64>> },
                "date" => quote! { Option<Vec<String>> },
                "json" => quote! { Option<serde_json::Value> },
                _ => quote! { Option<Vec<String>> },
            }
        }
    }

    /// Convert property name to valid Rust field name
    fn property_to_field_name(&self, prop_name: &str) -> Ident {
        // Convert camelCase/PascalCase to snake_case
        let snake_case = self.to_snake_case(prop_name);

        // Handle Rust keywords
        let field_name = match snake_case.as_str() {
            "type" => "type_".to_string(),
            "match" => "match_".to_string(),
            "ref" => "ref_".to_string(),
            _ => snake_case,
        };

        Ident::new(&field_name, Span::call_site())
    }

    /// Convert string to snake_case
    fn to_snake_case(&self, s: &str) -> String {
        // Handle special cases
        if s.to_uppercase() == s && s.len() <= 3 {
            // Acronyms like "ID", "API", etc. -> all lowercase
            return s.to_lowercase();
        }

        let mut result = String::new();
        let mut prev_is_upper = false;

        for (i, ch) in s.chars().enumerate() {
            if ch.is_uppercase() {
                if i > 0 && !prev_is_upper {
                    result.push('_');
                }
                result.push(ch.to_lowercase().next().unwrap());
                prev_is_upper = true;
            } else {
                result.push(ch);
                prev_is_upper = false;
            }
        }

        result
    }

    /// Write module to file with formatting
    fn write_module(&self, filename: &str, tokens: TokenStream) -> Result<()> {
        let path = self.output_dir.join(filename);

        // Parse and format the generated code
        // If parsing fails (e.g., due to attributes syn doesn't recognize),
        // write the raw tokens and let rustfmt handle it later
        let content = match syn::parse2(tokens.clone()) {
            Ok(syntax_tree) => prettyplease::unparse(&syntax_tree),
            Err(_) => {
                // Fallback: write raw tokens and format with rustfmt
                let raw = tokens.to_string();
                fs::write(&path, &raw).context(format!("Failed to write file: {:?}", path))?;

                // Try to format with rustfmt
                let _result = std::process::Command::new("rustfmt").arg(&path).output();

                // Read back the formatted content
                return fs::read_to_string(&path)
                    .context("Failed to read formatted file")
                    .map(|_| ());
            }
        };

        fs::write(&path, content).context(format!("Failed to write file: {:?}", path))?;

        // Format with rustfmt to match project style
        let _result = std::process::Command::new("rustfmt").arg(&path).output();

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{generated::Person, schema::SchemaRegistry};
    use std::io::Write;
    use tempfile::TempDir;

    fn create_test_schema(dir: &std::path::Path, name: &str, yaml: &str) {
        let path = dir.join(format!("{}.yml", name));
        let mut file = fs::File::create(path).unwrap();
        file.write_all(yaml.as_bytes()).unwrap();
    }

    #[test]
    fn test_code_generation() {
        let temp_dir = TempDir::new().unwrap();

        create_test_schema(
            temp_dir.path(),
            "Thing",
            r#"
label: Thing
abstract: true
properties:
  name:
    label: Name
    type: name
"#,
        );

        create_test_schema(
            temp_dir.path(),
            "Person",
            r#"
label: Person
extends:
  - Thing
properties:
  firstName:
    label: First Name
    type: name
"#,
        );

        let registry = SchemaRegistry::load_from_cache(temp_dir.path()).unwrap();
        let output_dir = temp_dir.path().join("generated");
        let codegen = CodeGenerator::new(registry, &output_dir);

        let result = codegen.generate_all();
        assert!(result.is_ok(), "Code generation failed: {:?}", result);

        // Check generated files exist
        assert!(output_dir.join("mod.rs").exists());
        assert!(output_dir.join("entities.rs").exists());
        assert!(output_dir.join("ftm_entity.rs").exists());
        assert!(output_dir.join("traits.rs").exists());
        assert!(output_dir.join("trait_impls.rs").exists());
    }

    #[test]
    fn test_snake_case_conversion() {
        let temp_dir = TempDir::new().unwrap();

        create_test_schema(
            temp_dir.path(),
            "Thing",
            r#"
label: Thing
properties: {}
"#,
        );

        let registry = SchemaRegistry::load_from_cache(temp_dir.path()).unwrap();
        let codegen = CodeGenerator::new(registry, "/tmp/test");

        assert_eq!(codegen.to_snake_case("firstName"), "first_name");
        assert_eq!(codegen.to_snake_case("birthDate"), "birth_date");
        assert_eq!(codegen.to_snake_case("name"), "name");
        assert_eq!(codegen.to_snake_case("ID"), "id");
        assert_eq!(codegen.to_snake_case("API"), "api");
    }

    #[test]
    fn test_trait_generation() {
        let temp_dir = TempDir::new().unwrap();

        // Create abstract base schema
        create_test_schema(
            temp_dir.path(),
            "Thing",
            r#"
label: Thing
abstract: true
properties:
  name:
    label: Name
    type: name
  description:
    label: Description
    type: text
"#,
        );

        // Create abstract intermediate schema
        create_test_schema(
            temp_dir.path(),
            "LegalEntity",
            r#"
label: Legal Entity
abstract: true
extends:
  - Thing
properties:
  country:
    label: Country
    type: country
"#,
        );

        // Create concrete schemas
        create_test_schema(
            temp_dir.path(),
            "Person",
            r#"
label: Person
extends:
  - LegalEntity
properties:
  firstName:
    label: First Name
    type: name
"#,
        );

        create_test_schema(
            temp_dir.path(),
            "Company",
            r#"
label: Company
extends:
  - LegalEntity
properties:
  registrationNumber:
    label: Registration Number
    type: identifier
"#,
        );

        let registry = SchemaRegistry::load_from_cache(temp_dir.path()).unwrap();
        let output_dir = temp_dir.path().join("generated");
        let codegen = CodeGenerator::new(registry, &output_dir);

        let result = codegen.generate_all();
        assert!(result.is_ok(), "Code generation failed: {:?}", result);

        // Verify traits were generated
        let traits_content = fs::read_to_string(output_dir.join("traits.rs")).unwrap();
        assert!(traits_content.contains("pub trait Thing"));
        assert!(traits_content.contains("pub trait LegalEntity"));
        assert!(traits_content.contains("fn name(&self)"));
        assert!(traits_content.contains("fn country(&self)"));

        // Verify trait implementations were generated
        let trait_impls_content = fs::read_to_string(output_dir.join("trait_impls.rs")).unwrap();
        assert!(trait_impls_content.contains("impl Thing for Person"));
        assert!(trait_impls_content.contains("impl LegalEntity for Person"));
        assert!(trait_impls_content.contains("impl Thing for Company"));
        assert!(trait_impls_content.contains("impl LegalEntity for Company"));

        // Verify concrete structs still exist with flat structure
        let entities_content = fs::read_to_string(output_dir.join("entities.rs")).unwrap();
        assert!(entities_content.contains("pub struct Person"));
        assert!(entities_content.contains("pub struct Company"));
        assert!(entities_content.contains("pub name: Option<Vec<String>>")); // Flattened from Thing
        assert!(entities_content.contains("pub country: Option<Vec<String>>")); // Flattened from LegalEntity
    }

    #[test]
    fn test_builder() {
        let _person = Person::builder()
            .name(vec!["Huh".to_string()])
            .height(vec![123.45]);
    }

    #[test]
    fn test_to_ftm_json() {
        let person = Person::builder()
            .name(vec!["Hello Sir".into()])
            .id("123".into())
            .build();
        let v: serde_json::Value = serde_json::from_str(&person.to_ftm_json().unwrap()).unwrap();
        let v = v.as_object().unwrap();
        let keys: Vec<_> = Vec::from_iter(v.keys());
        assert_eq!(keys, vec!["id", "properties", "schema"]);
    }
}