olai-codegen 0.0.1

Proto-driven code generation for REST handlers, clients, and resource registries
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
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

use crate::analysis::{GenerationPlan, RequestType};
use crate::google::api::FieldBehavior;
use crate::parsing::CodeGenMetadata;
use crate::parsing::types::BaseType;

use super::{CodeGenConfig, format_tokens};

/// Generate the `labels.rs` file containing `Resource` and `ObjectLabel` enums
/// derived from `google.api.resource` annotations on message types.
///
/// The package prefix is inferred from the service packages in `plan`: the longest
/// common dot-delimited prefix across all services, formatted as `".<prefix>."`.
/// The `super::` depth is always `1` since `labels.rs` is placed one level inside
/// the models subdirectory alongside the service `pub mod` blocks.
///
/// When `error_type_path` is `Some`, also emits:
/// - An inherent `Resource::resource_label()` method
/// - `From<T> for Resource` and `TryFrom<Resource> for T` impls for each resource type
///
/// When `config.generate_object_conversions` is `true`, also emits:
/// - A `::olai_derive::object_conversions!` invocation for all resources
///   that have an `IDENTIFIER`-annotated field
/// - A `qualified_name()` inherent method on each resource type
pub(crate) fn generate_resource_enum(
    plan: &GenerationPlan,
    metadata: &CodeGenMetadata,
    config: &CodeGenConfig,
    error_type_path: Option<&str>,
) -> String {
    if !config.generate_resource_enum {
        return String::new();
    }

    // Infer package prefix from service packages (e.g. "unitycatalog.catalogs.v1" → ".unitycatalog.")
    let package_prefix = infer_package_prefix(
        &plan
            .services
            .iter()
            .map(|s| s.package.as_str())
            .collect::<Vec<_>>(),
    );

    // Collect all messages that have a resource annotation matching the inferred prefix
    let mut resources: Vec<ResourceEntry> = metadata
        .messages
        .iter()
        .filter_map(|(name, info)| {
            let rd = info.resource_descriptor.as_ref()?;
            // Only include packages matching the inferred prefix (excludes google/gnostic messages)
            if !name.starts_with(&package_prefix) {
                return None;
            }
            // Extract variant name from resource type (e.g. "acme.io/Widget" -> "Widget")
            let variant_name = match rd.r#type.split('/').next_back() {
                Some(v) if !v.is_empty() => v.to_string(),
                _ => {
                    tracing::warn!(
                        "Skipping resource `{}`: type `{}` has no `/`-separated variant name",
                        name,
                        rd.r#type
                    );
                    return None;
                }
            };
            // labels.rs always lives one level inside the models subdir, so super:: reaches the subdir
            // module which has all the service pub mods as siblings.
            let rust_path = message_name_to_rust_path(name, &package_prefix, 1)?;

            // Find the IDENTIFIER-annotated field
            let id_field = info
                .fields
                .iter()
                .find(|f| f.field_behavior.contains(&FieldBehavior::Identifier));
            let (id_field_name, id_is_optional) = match id_field {
                Some(f) => (Some(f.name.clone()), f.unified_type.is_optional),
                None => (None, false),
            };

            // Derive path_names from the service plan for this resource.
            // A resource is hierarchical if its descriptor explicitly sets name_field (any value)
            // OR if the message has a full_name field (server-computed dot-joined composite).
            let message_has_full_name = info.fields.iter().any(|f| f.name == "full_name");
            let path_names = derive_path_names(
                &rd.singular,
                !rd.name_field.is_empty() || message_has_full_name,
                plan,
                metadata,
            );

            // Compute field descriptors with roles for the resource registry.
            let known_managed_fields: &[&str] =
                &["created_at", "updated_at", "created_by", "updated_by"];
            let field_descriptors: Vec<FieldDescriptorEntry> = info
                .fields
                .iter()
                .map(|f| {
                    let role = if f.field_behavior.contains(&FieldBehavior::Identifier) {
                        FieldRoleEntry::Identifier
                    } else if f.is_sensitive {
                        FieldRoleEntry::Sensitive
                    } else if f.field_behavior.contains(&FieldBehavior::OutputOnly)
                        && known_managed_fields.contains(&f.name.as_str())
                    {
                        FieldRoleEntry::Managed
                    } else {
                        FieldRoleEntry::Data
                    };
                    FieldDescriptorEntry {
                        name: f.name.clone(),
                        role,
                    }
                })
                .collect();

            Some(ResourceEntry {
                variant_name,
                rust_path,
                singular: rd.singular.clone(),
                id_field: id_field_name,
                id_is_optional,
                path_names,
                has_full_name: message_has_full_name,
                field_descriptors,
            })
        })
        .collect();

    // Sort deterministically by singular name
    resources.sort_by(|a, b| a.singular.cmp(&b.singular));

    let resource_variants: Vec<TokenStream> = resources
        .iter()
        .map(|r| {
            let variant = format_ident!("{}", r.variant_name);
            let path: syn::Type = syn::parse_str(&r.rust_path)
                .unwrap_or_else(|e| panic!("Invalid rust path `{}`: {}", r.rust_path, e));
            quote! { #variant(#path) }
        })
        .collect();

    let label_variants: Vec<TokenStream> = resources
        .iter()
        .map(|r| {
            let variant = format_ident!("{}", r.variant_name);
            quote! { #variant }
        })
        .collect();

    // Inherent impl and From/TryFrom impls — only emitted when error_type_path is set
    let extra_impls: TokenStream = if let Some(error_path) = error_type_path {
        let error_ty: syn::Type = syn::parse_str(error_path)
            .unwrap_or_else(|e| panic!("Invalid error_type_path `{error_path}`: {e}"));

        let label_arms: Vec<TokenStream> = resources
            .iter()
            .map(|r| {
                let variant = format_ident!("{}", r.variant_name);
                quote! { Resource::#variant(_) => &ObjectLabel::#variant, }
            })
            .collect();

        let from_impls: Vec<TokenStream> = resources
            .iter()
            .map(|r| {
                let variant = format_ident!("{}", r.variant_name);
                let path: syn::Type = syn::parse_str(&r.rust_path)
                    .unwrap_or_else(|e| panic!("Invalid rust path `{}`: {}", r.rust_path, e));
                quote! {
                    impl From<#path> for Resource {
                        fn from(v: #path) -> Self {
                            Resource::#variant(v)
                        }
                    }

                    impl TryFrom<Resource> for #path {
                        type Error = #error_ty;

                        fn try_from(r: Resource) -> Result<Self, Self::Error> {
                            match r {
                                Resource::#variant(v) => Ok(v),
                                _ => Err(<#error_ty>::generic(concat!(
                                    "Resource is not a ",
                                    stringify!(#variant)
                                ))),
                            }
                        }
                    }
                }
            })
            .collect();

        quote! {
            impl Resource {
                /// Return the discriminant label for this resource.
                pub fn resource_label(&self) -> &ObjectLabel {
                    match self {
                        #(#label_arms)*
                    }
                }
            }

            #(#from_impls)*
        }
    } else {
        quote! {}
    };

    // Object conversion impl blocks and qualified_name() methods
    let object_conversions_impl: TokenStream = if config.generate_object_conversions {
        let mut conversion_impls: Vec<TokenStream> = Vec::new();
        let mut qualified_name_impls: Vec<TokenStream> = Vec::new();

        for r in &resources {
            let Some(ref id_field) = r.id_field else {
                // No IDENTIFIER annotation — skip
                continue;
            };

            let path: syn::Type = syn::parse_str(&r.rust_path)
                .unwrap_or_else(|e| panic!("Invalid rust path `{}`: {}", r.rust_path, e));
            let label_expr: syn::Expr = syn::parse_str(&format!("ObjectLabel::{}", r.variant_name))
                .unwrap_or_else(|e| panic!("Invalid label expr: {e}"));
            let id_ident = format_ident!("{}", id_field);
            let is_optional = r.id_is_optional;

            let path_name_idents: Vec<proc_macro2::Ident> = r
                .path_names
                .iter()
                .map(|n| format_ident!("{}", n))
                .collect();

            conversion_impls.push(emit_from_object(&path, &id_ident, is_optional));
            conversion_impls.push(emit_to_object(&path, &label_expr, &id_ident, is_optional));
            conversion_impls.push(emit_resource_impl(
                &path,
                &label_expr,
                &id_ident,
                &path_name_idents,
                is_optional,
            ));

            // qualified_name() impl
            let format_expr: TokenStream = build_qualified_name_expr(&r.path_names);
            qualified_name_impls.push(quote! {
                impl #path {
                    /// Returns the fully-qualified dot-separated name computed from component fields.
                    pub fn qualified_name(&self) -> String {
                        #format_expr
                    }
                }
            });
        }

        quote! {
            use crate::Error;
            use crate::models::object::Object;
            use crate::models::resources::{ResourceExt, ResourceIdent, ResourceName, ResourceRef};

            #(#conversion_impls)*

            #(#qualified_name_impls)*
        }
    } else {
        quote! {}
    };

    let tokens = quote! {
        /// All resource types managed by the service.
        #[allow(clippy::derive_partial_eq_without_eq)]
        #[derive(Clone, Debug, PartialEq)]
        pub enum Resource {
            #(#resource_variants),*
        }

        /// Discriminant label for each resource type.
        #[derive(
            ::strum::AsRefStr,
            ::strum::Display,
            ::strum::EnumIter,
            ::strum::EnumString,
            ::serde::Serialize,
            ::serde::Deserialize,
            Hash,
            Clone,
            Copy,
            Debug,
            PartialEq,
            Eq,
            PartialOrd,
            Ord,
        )]
        #[strum(serialize_all = "snake_case", ascii_case_insensitive)]
        #[serde(rename_all = "snake_case")]
        #[cfg_attr(feature = "sqlx", derive(::sqlx::Type))]
        #[cfg_attr(
            feature = "sqlx",
            sqlx(type_name = "object_label", rename_all = "snake_case")
        )]
        pub enum ObjectLabel {
            #(#label_variants),*
        }

        #extra_impls

        #object_conversions_impl
    };

    // Generate the resource descriptor registry and Label impl (only when store integration is enabled)
    let registry_impl = if config.generate_store_integration {
        generate_resource_registry(&resources, config, plan, metadata)
    } else {
        quote! {}
    };

    let all_tokens = quote! {
        #tokens

        #registry_impl
    };

    format_tokens(all_tokens)
}

struct ResourceEntry {
    variant_name: String,
    rust_path: String,
    singular: String,
    /// Field name carrying `FieldBehavior::Identifier`, if present.
    id_field: Option<String>,
    /// Whether the IDENTIFIER field is `optional`.
    id_is_optional: bool,
    /// Ordered list of field names used to build `ResourceName`, e.g. `["catalog_name", "schema_name", "name"]`.
    path_names: Vec<String>,
    /// Whether the message has a `full_name` field (used for `qualified_name()` generation).
    #[allow(dead_code)]
    has_full_name: bool,
    /// All fields with their computed roles for the resource descriptor registry.
    field_descriptors: Vec<FieldDescriptorEntry>,
}

/// A field entry for the generated resource descriptor registry.
struct FieldDescriptorEntry {
    name: String,
    role: FieldRoleEntry,
}

/// The computed role of a field, matching `olai_store::FieldRole`.
enum FieldRoleEntry {
    Data,
    Identifier,
    Sensitive,
    Managed,
}

/// Derive the ordered list of field names used to build a `ResourceName` for a resource.
///
/// **Annotation-driven path** (preferred): when the service for `singular` has
/// `hierarchy` entries from `resource_reference { child_type }` annotations, the
/// parent field names are taken directly from those entries (in the order they appear
/// as List method query params), followed by `"name"`.
///
/// **Heuristic fallback** (when no annotations present): uses the same two-signal logic:
/// 1. `name_field` non-empty on the descriptor → resource has decomposable composite name
/// 2. Check the List method's required string-typed query params for parent names
///
/// Returns e.g. `["catalog_name", "schema_name", "name"]` for Table,
/// `["catalog_name", "name"]` for Schema, `["name"]` for Catalog.
fn derive_path_names(
    singular: &str,
    has_full_name_field: bool,
    plan: &GenerationPlan,
    metadata: &CodeGenMetadata,
) -> Vec<String> {
    // Find the service whose singular resource name matches
    let service = plan.services.iter().find(|s| {
        s.managed_resources
            .iter()
            .any(|r| r.descriptor.singular == singular)
    });

    let Some(service) = service else {
        return vec!["name".to_string()];
    };

    // Find this resource's type string from metadata
    let resource_type = metadata
        .resource_from_singular(singular)
        .map(|rd| rd.r#type.clone())
        .unwrap_or_default();

    // --- Annotation-driven path ---
    // Collect hierarchy entries for this resource type, in List-method param order.
    if !service.hierarchy.is_empty() && !resource_type.is_empty() {
        let annotation_parents: Vec<String> = service
            .hierarchy
            .iter()
            .filter(|h| h.child_resource_type == resource_type)
            .map(|h| h.parent_field_name.clone())
            .collect();

        if !annotation_parents.is_empty() {
            let mut params = annotation_parents;
            params.push("name".to_string());
            return params;
        }
    }

    // --- Heuristic fallback ---
    // Get the Get method's path param name
    let get_path_param = service
        .methods
        .iter()
        .find(|m| m.request_type == RequestType::Get)
        .and_then(|m| m.path_parameters().next().map(|p| p.name.clone()));

    // Get the List method's required string query params (these are the parent hierarchy params)
    let parent_params: Vec<String> = service
        .methods
        .iter()
        .find(|m| m.request_type == RequestType::List)
        .map(|m| {
            m.parameters
                .iter()
                .filter(|p| !p.is_path_param() && !p.is_optional())
                .filter(|p| matches!(p.field_type().base_type, BaseType::String))
                .map(|p| p.name().to_string())
                .collect()
        })
        .unwrap_or_default();

    let should_decompose = has_full_name_field
        || (get_path_param.as_deref() == Some("name") && !parent_params.is_empty());

    if should_decompose {
        let mut params = parent_params;
        params.push(format!("{singular}_name"));
        // Replace the final `{singular}_name` with just `name` since the proto field is always `name`.
        // last_mut() is infallible: we just pushed an element above.
        let last = params.last_mut().unwrap();
        *last = "name".to_string();
        params
    } else {
        vec!["name".to_string()]
    }
}

/// Build a `qualified_name()` return expression from an ordered list of path field names.
///
/// - `["name"]` → `self.name.clone()`
/// - `["catalog_name", "name"]` → `format!("{}.{}", self.catalog_name, self.name)`
/// - `["catalog_name", "schema_name", "name"]` → `format!("{}.{}.{}", ...)`
fn build_qualified_name_expr(path_names: &[String]) -> TokenStream {
    if path_names.len() == 1 {
        let field = format_ident!("{}", &path_names[0]);
        return quote! { self.#field.clone() };
    }
    let format_str = path_names
        .iter()
        .map(|_| "{}")
        .collect::<Vec<_>>()
        .join(".");
    let field_refs: Vec<TokenStream> = path_names
        .iter()
        .map(|n| {
            let ident = format_ident!("{}", n);
            quote! { self.#ident }
        })
        .collect();
    quote! { format!(#format_str, #(#field_refs),*) }
}

/// Infer the package prefix from a list of proto package names.
///
/// Finds the longest common leading dot-segment and returns it as `".<prefix>."`.
///
/// Examples:
/// - `["unitycatalog.catalogs.v1", "unitycatalog.tables.v1"]` → `".unitycatalog."`
/// - `["example.catalog.v1"]` → `".example."`
fn infer_package_prefix(packages: &[&str]) -> String {
    if packages.is_empty() {
        return String::new();
    }
    let first_parts: Vec<&str> = packages[0].split('.').collect();
    let _common_len = first_parts
        .iter()
        .enumerate()
        .take_while(|(i, seg)| {
            packages
                .iter()
                .skip(1)
                .all(|p| p.split('.').nth(*i) == Some(seg))
        })
        .count();
    // Take only the top-level shared segment (one dot-level), not the full common prefix,
    // so version segments like "v1" don't get included when all packages share them.
    // Use the first segment as the meaningful namespace prefix.
    format!(".{}.", first_parts[0])
}

/// Convert a fully-qualified protobuf message name to a Rust type path relative to
/// `labels.rs` inside the models subdirectory.
///
/// `prefix` is stripped from the message name (e.g. `".unitycatalog."`).
/// One `super::` hop is prepended since `labels.rs` is a sibling of the service modules
/// inside the same generated subdirectory.
///
/// Examples (prefix = `".unitycatalog."`):
/// - `.unitycatalog.catalogs.v1.Catalog` → `super::catalogs::v1::Catalog`
/// - `.unitycatalog.external_locations.v1.ExternalLocation` → `super::external_locations::v1::ExternalLocation`
fn message_name_to_rust_path(name: &str, prefix: &str, super_levels: u32) -> Option<String> {
    // Strip leading prefix (e.g. ".unitycatalog.")
    let without_prefix = name.strip_prefix(prefix)?;
    // Split remaining parts and join with `::`
    let parts: Vec<&str> = without_prefix.split('.').collect();
    if parts.is_empty() {
        return None;
    }
    let super_prefix = "super::".repeat(super_levels as usize);
    Some(format!("{}{}", super_prefix, parts.join("::")))
}

/// Generate the `RESOURCE_DESCRIPTORS` static registry and `Label` impl for `ObjectLabel`.
///
/// This emits:
/// 1. `impl olai_store::Label for ObjectLabel` — making the generated
///    label type compatible with the generic resource store.
/// 2. `pub static RESOURCE_DESCRIPTORS: &[ResourceTypeDescriptor]` — a static registry
///    of all resource types with field roles, path names, and parent relationships.
fn generate_resource_registry(
    resources: &[ResourceEntry],
    config: &CodeGenConfig,
    plan: &GenerationPlan,
    metadata: &CodeGenMetadata,
) -> TokenStream {
    let store_crate = format_ident!("{}", config.resource_store_crate_name);

    // --- Label impl for ObjectLabel ---
    let label_impl = quote! {
        impl ::#store_crate::Label for ObjectLabel {
            fn as_str(&self) -> &str {
                // strum's AsRefStr gives us the snake_case string
                self.as_ref()
            }
        }
    };

    // --- RESOURCE_DESCRIPTORS static ---
    // Compute parent_label for each resource.
    // Annotation-driven: look for hierarchy entries across all services where
    // child_resource_type matches this resource's type string. The parent singular
    // is stored directly on the hierarchy entry.
    // Heuristic fallback: for resources without annotation data, strip "_name" from
    // the second-to-last path_names component and match against known resource singulars.
    let parent_labels: Vec<Option<String>> = resources
        .iter()
        .map(|r| {
            if r.path_names.len() <= 1 {
                return None;
            }

            // Try annotation-driven path first
            let resource_type = metadata
                .resource_from_singular(&r.singular)
                .map(|rd| rd.r#type.as_str())
                .unwrap_or("");
            if !resource_type.is_empty() {
                for service in &plan.services {
                    for h in &service.hierarchy {
                        if h.child_resource_type == resource_type {
                            if let Some(ref parent_sing) = h.parent_singular {
                                let found = resources.iter().find_map(|candidate| {
                                    if candidate.singular == *parent_sing {
                                        Some(candidate.variant_name.clone())
                                    } else {
                                        None
                                    }
                                });
                                if found.is_some() {
                                    return found;
                                }
                            }
                        }
                    }
                }
            }

            // Heuristic fallback: strip "_name" from second-to-last path component
            let parent_path_component = &r.path_names[r.path_names.len() - 2];
            let parent_singular = parent_path_component
                .strip_suffix("_name")
                .unwrap_or(parent_path_component);
            resources.iter().find_map(|candidate| {
                if candidate.singular == parent_singular {
                    Some(candidate.variant_name.clone())
                } else {
                    None
                }
            })
        })
        .collect();

    let descriptor_entries: Vec<TokenStream> = resources
        .iter()
        .zip(parent_labels.iter())
        .map(|(r, parent)| {
            let label_variant = format_ident!("{}", r.variant_name);

            let field_entries: Vec<TokenStream> = r
                .field_descriptors
                .iter()
                .map(|fd| {
                    let name = &fd.name;
                    let role = match fd.role {
                        FieldRoleEntry::Data => {
                            quote! { ::#store_crate::FieldRole::Data }
                        }
                        FieldRoleEntry::Identifier => {
                            quote! { ::#store_crate::FieldRole::Identifier }
                        }
                        FieldRoleEntry::Sensitive => {
                            quote! { ::#store_crate::FieldRole::Sensitive }
                        }
                        FieldRoleEntry::Managed => {
                            quote! { ::#store_crate::FieldRole::Managed }
                        }
                    };
                    quote! {
                        ::#store_crate::ResourceFieldDescriptor {
                            name: #name,
                            role: #role,
                        }
                    }
                })
                .collect();

            let path_name_strs: Vec<&str> = r.path_names.iter().map(|s| s.as_str()).collect();

            let parent_expr = match parent {
                Some(parent_name) => {
                    let parent_variant = format_ident!("{}", parent_name);
                    quote! { Some(ObjectLabel::#parent_variant) }
                }
                None => quote! { None },
            };

            quote! {
                ::#store_crate::ResourceTypeDescriptor {
                    label: ObjectLabel::#label_variant,
                    fields: &[#(#field_entries),*],
                    path_names: &[#(#path_name_strs),*],
                    parent_label: #parent_expr,
                }
            }
        })
        .collect();

    let registry = quote! {
        /// Static resource type descriptors derived from proto annotations.
        ///
        /// Each entry describes a resource type's fields (with roles: data, identifier,
        /// sensitive, managed), hierarchical name components, and parent relationship.
        ///
        /// Use `ResourceRegistry::from_static` to build a runtime registry from this data.
        pub static RESOURCE_DESCRIPTORS: &[::#store_crate::ResourceTypeDescriptor<ObjectLabel>] = &[
            #(#descriptor_entries),*
        ];
    };

    quote! {
        #label_impl
        #registry
    }
}

// ---------------------------------------------------------------------------
// Object conversion helpers (emit the impl blocks formerly produced by
// olai_derive::object_conversions!)
// ---------------------------------------------------------------------------

fn emit_from_object(
    path: &syn::Type,
    id_ident: &proc_macro2::Ident,
    is_optional: bool,
) -> TokenStream {
    let id_assignment = if is_optional {
        quote! { res.#id_ident = Some(object.id.hyphenated().to_string()); }
    } else {
        quote! { res.#id_ident = object.id.hyphenated().to_string(); }
    };
    quote! {
        impl TryFrom<Object> for #path {
            type Error = Error;

            fn try_from(object: Object) -> Result<Self, Self::Error> {
                let props = object
                    .properties
                    .ok_or_else(|| Error::generic("expected properties"))?;
                let mut res: #path = ::serde_json::from_value(props)?;
                #id_assignment
                Ok(res)
            }
        }
    }
}

fn emit_to_object(
    path: &syn::Type,
    label_expr: &syn::Expr,
    id_ident: &proc_macro2::Ident,
    is_optional: bool,
) -> TokenStream {
    let id_field = if is_optional {
        quote! {
            let id = obj
                .#id_ident
                .as_ref()
                .map(|id| ::uuid::Uuid::parse_str(id))
                .transpose()?
                .unwrap_or_else(|| ::uuid::Uuid::nil());
        }
    } else {
        quote! {
            let id = ::uuid::Uuid::parse_str(&obj.#id_ident).unwrap_or_else(|_| ::uuid::Uuid::nil());
        }
    };
    quote! {
        impl TryFrom<#path> for Object {
            type Error = Error;

            fn try_from(obj: #path) -> Result<Self, Self::Error> {
                #id_field
                Ok(Object {
                    id,
                    name: obj.resource_name(),
                    label: #label_expr,
                    properties: Some(::serde_json::to_value(obj)?),
                    updated_at: None,
                    created_at: chrono::Utc::now(),
                })
            }
        }
    }
}

fn emit_resource_impl(
    path: &syn::Type,
    label_expr: &syn::Expr,
    id_ident: &proc_macro2::Ident,
    path_name_idents: &[proc_macro2::Ident],
    is_optional: bool,
) -> TokenStream {
    let resource_ref = if is_optional {
        quote! {
            self
                .#id_ident
                .as_ref()
                .and_then(|id| ::uuid::Uuid::parse_str(id).ok())
                .map(ResourceRef::Uuid)
                .unwrap_or_else(|| ResourceRef::Name(self.resource_name()))
        }
    } else {
        quote! {
            ::uuid::Uuid::parse_str(&self.#id_ident)
                .ok()
                .map(ResourceRef::Uuid)
                .unwrap_or_else(|| ResourceRef::Name(self.resource_name()))
        }
    };
    quote! {
        impl ResourceExt for #path {
            fn resource_name(&self) -> ResourceName {
                ResourceName::new([#(&self.#path_name_idents),*])
            }
            fn resource_ref(&self) -> ResourceRef {
                #resource_ref
            }
            fn resource_ident(&self) -> ResourceIdent {
                (#label_expr).to_ident(self.resource_ref())
            }
        }
    }
}

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

    #[test]
    fn test_message_name_to_rust_path() {
        assert_eq!(
            message_name_to_rust_path(".unitycatalog.catalogs.v1.Catalog", ".unitycatalog.", 1),
            Some("super::catalogs::v1::Catalog".to_string())
        );
        assert_eq!(
            message_name_to_rust_path(
                ".unitycatalog.external_locations.v1.ExternalLocation",
                ".unitycatalog.",
                1
            ),
            Some("super::external_locations::v1::ExternalLocation".to_string())
        );
        assert_eq!(
            message_name_to_rust_path(".google.api.Something", ".unitycatalog.", 1),
            None
        );
    }

    #[test]
    fn test_infer_package_prefix() {
        assert_eq!(
            infer_package_prefix(&["unitycatalog.catalogs.v1", "unitycatalog.tables.v1"]),
            ".unitycatalog."
        );
        assert_eq!(infer_package_prefix(&["example.catalog.v1"]), ".example.");
        assert_eq!(
            infer_package_prefix(&["example.catalog.v1", "example.items.v1"]),
            ".example."
        );
    }

    #[test]
    fn test_build_qualified_name_expr_flat() {
        let expr = build_qualified_name_expr(&["name".to_string()]);
        let s = expr.to_string();
        assert!(s.contains("self"), "expr: {s}");
        assert!(s.contains("name"), "expr: {s}");
        assert!(s.contains("clone"), "expr: {s}");
    }

    #[test]
    fn test_build_qualified_name_expr_hierarchical() {
        let expr = build_qualified_name_expr(&[
            "catalog_name".to_string(),
            "schema_name".to_string(),
            "name".to_string(),
        ]);
        let s = expr.to_string();
        assert!(s.contains("format"), "expr: {s}");
        assert!(s.contains("catalog_name"), "expr: {s}");
        assert!(s.contains("schema_name"), "expr: {s}");
    }
}