olai-codegen 0.0.8

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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
//! PyO3 wrapper `#[pyclass]` generation for the protobuf-defined model types.
//!
//! ## Why wrappers
//!
//! Models are generated by `buf` (the buffa or prost plugin), not by trestle, so
//! we can neither add `#[pyclass]` to the struct definition nor a `#[derive]`.
//! An earlier approach implemented PyO3's [`FromPyObject`]/[`IntoPyObject`]
//! directly on the model types via [`pythonize`], so a model crossed the FFI
//! boundary as a plain Python **dict**. That compiled, but the Python side never
//! got *real objects*: no attribute access (`catalog.name`), no `isinstance`, no
//! `__repr__`, and enums arrived as bare proto-name strings.
//!
//! Instead we emit, for every project message, a newtype `#[pyclass]` wrapper
//! (`PyCatalog(Catalog)`) with native, typed getters/setters, a keyword
//! constructor, and `__repr__`/`__eq__`. The wrapper is *local* to the model
//! crate (orphan rule satisfied), and `From`/`Into` conversions bridge it to the
//! bare model type so the generated client bindings can convert at the boundary.
//! Enums get their own `#[pyclass(eq, eq_int)]` wrapper (see [`enum_wrappers`]).
//!
//! Everything is emitted into a sibling `pyo3_impls.rs` of the generated models
//! module and gated behind `#[cfg(feature = "python")]`, so pure-Rust /
//! server-only / WASM consumers never pull `pyo3` into their dependency tree.
//!
//! ## Runtime differences
//!
//! Unlike the old pythonize impls, the wrapper *bodies* are runtime-aware: buffa
//! stores singular messages as `MessageField<T>` and enums as `EnumValue<E>`,
//! while prost uses `Option<T>` (or `Option<Box<T>>` for fields prost boxes to
//! break a recursion cycle) and bare `i32`. The accessor expressions are selected
//! by [`Runtime`] and, for messages, by per-field boxing (see [`boxed_fields`]);
//! the *public* wrapper surface (class + method names + Python-visible types) is
//! identical across runtimes.
//!
//! [`FromPyObject`]: pyo3::FromPyObject
//! [`IntoPyObject`]: pyo3::IntoPyObject
//! [`pythonize`]: https://docs.rs/pythonize

use std::collections::BTreeSet;

use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

use super::super::format_tokens;
use crate::analysis::GenerationPlan;
use crate::codegen::Runtime;
use crate::parsing::types::{BaseType, UnifiedType};
use crate::parsing::{CodeGenMetadata, EnumInfo, MessageField, MessageInfo, OneofVariant};
use crate::utils::{extract_qualified_type_name, extract_simple_type_name};

/// Generate the `pyo3_impls.rs` content: a `#[pyclass]` wrapper for every message
/// and enum defined in the project's own packages, plus their `From`/`Into`
/// bridges to the bare model types.
///
/// Returns an empty string when there are no project messages/enums to emit (e.g.
/// a service-less descriptor), so the caller can skip writing the file.
pub(crate) fn generate_pyo3_impls(
    plan: &GenerationPlan,
    metadata: &CodeGenMetadata,
    runtime: Runtime,
) -> crate::error::Result<String> {
    // The project's own packages, taken straight from the plan's services — the
    // same set whose model modules `generate_models_mod` emits. Types in any other
    // package (google/gnostic/etc.) are not in our crate and must be skipped
    // (orphan rule + they have no in-crate path).
    let project_packages: BTreeSet<&str> =
        plan.services.iter().map(|s| s.package.as_str()).collect();

    let mut items: Vec<TokenStream> = Vec::new();

    // Enums first so message getters can reference the enum wrappers.
    let mut enum_names: Vec<&String> = metadata.enums.keys().collect();
    enum_names.sort();
    for name in enum_names {
        let Some(rust_path) = type_rust_path(name, &project_packages) else {
            continue;
        };
        let info = &metadata.enums[name];
        // An enum with no values has no representable wrapper; skip it.
        if info.values.is_empty() {
            continue;
        }
        items.push(enum_wrapper(name, info, &rust_path, runtime)?);
    }

    // Emit a wrapper for *every* message in the project's own packages, not just
    // resource-annotated ones: request/response and other non-resource messages
    // also cross the FFI boundary. Sort by name for deterministic output.
    let mut msg_names: Vec<&String> = metadata.messages.keys().collect();
    msg_names.sort();
    for name in msg_names {
        let Some(rust_path) = type_rust_path(name, &project_packages) else {
            continue;
        };
        let info = &metadata.messages[name];
        items.push(message_wrapper(name, info, &rust_path, runtime, metadata)?);
    }

    if items.is_empty() {
        return Ok(String::new());
    }

    // No file-level inner attributes (`#![..]`) or inner doc comments (`//!`):
    // this file is mounted via `#[cfg(feature = "python")] mod pyo3_impls;` in the
    // generated `mod.rs` *and* `include!`d directly in some setups; inner
    // attributes are illegal inside an `include!`d module body, so every allow is
    // applied as an outer attribute on the individual emitted items instead.
    let tokens = quote! {
        // PyO3 wrapper `#[pyclass]` types for the generated models.
        //
        // Each model message/enum gets a newtype wrapper exposing native, typed
        // getters/setters and a keyword constructor, plus `From`/`Into` bridges to
        // the bare model type. Mounted under the `python` feature; see the model
        // module's `mod.rs`.

        #(#items)*
    };

    format_tokens(tokens)
}

/// The `Py`-prefixed wrapper ident for a fully-qualified proto type name, using
/// the parent-qualified emitted name (collision-free for nested types).
fn wrapper_ident(fq_name: &str) -> proc_macro2::Ident {
    format_ident!("Py{}", extract_qualified_type_name(fq_name))
}

/// The Python-visible class name (no `Py` prefix) for a fully-qualified proto name.
fn python_class_name(fq_name: &str) -> String {
    extract_qualified_type_name(fq_name)
}

// ---------------------------------------------------------------------------
// Enum wrappers
// ---------------------------------------------------------------------------

/// Emit a `#[pyclass(eq, eq_int)]` enum mirroring a proto enum, plus `From`
/// conversions to/from the bare Rust enum.
///
/// The wrapper is an integer-valued Python enum (so `==` and `int()` work). The
/// boundary to the buffa/prost runtime is by proto value: each variant carries
/// its proto number, and `From`/`Into` map through the runtime enum's `i32` repr.
fn enum_wrapper(
    fq_name: &str,
    info: &EnumInfo,
    rust_path: &str,
    runtime: Runtime,
) -> crate::error::Result<TokenStream> {
    let wrapper = wrapper_ident(fq_name);
    let class_name = python_class_name(fq_name);
    let inner: syn::Path = parse_path(rust_path, fq_name)?;

    // Variant idents mirror the proto value names (UPPER_SNAKE), which are valid
    // Python identifiers and stay stable regardless of the runtime's own variant
    // renaming (prost PascalCases + strips the type prefix; buffa keeps the proto
    // name). We therefore never reference the *runtime* enum's variant idents —
    // conversions go through the proto `i32` value, which both runtimes expose.
    let variants: Vec<proc_macro2::Ident> = info
        .values
        .iter()
        .map(|v| format_ident!("{}", v.name))
        .collect();
    // pyo3's `#[pyclass(eq_int)]` enums require `isize` discriminants.
    let numbers: Vec<proc_macro2::Literal> = info
        .values
        .iter()
        .map(|v| proc_macro2::Literal::isize_suffixed(v.number as isize))
        .collect();

    // The wrapper -> i32 arms and i32 -> wrapper arms (shared by both runtimes).
    let to_i32_arms = info.values.iter().map(|v| {
        let id = format_ident!("{}", v.name);
        let n = proc_macro2::Literal::i32_suffixed(v.number);
        quote! { #wrapper::#id => #n }
    });
    let from_i32_arms = info.values.iter().map(|v| {
        let id = format_ident!("{}", v.name);
        let n = proc_macro2::Literal::i32_suffixed(v.number);
        quote! { #n => #wrapper::#id }
    });
    let fallback = &variants[0];

    // Runtime-specific bridges between the wrapper's `i32` and the bare model enum.
    // buffa exposes `Enumeration::{to_i32, from_i32}`; prost enums are
    // `TryFrom<i32>` + `as i32`.
    let (inner_to_i32, i32_to_inner): (TokenStream, TokenStream) = match runtime {
        Runtime::Buffa => (
            quote! { <#inner as ::buffa::Enumeration>::to_i32(&value) },
            quote! { <#inner as ::buffa::Enumeration>::from_i32(n).unwrap_or_default() },
        ),
        Runtime::Prost => (
            quote! { value as i32 },
            quote! { <#inner as ::core::convert::TryFrom<i32>>::try_from(n).unwrap_or_default() },
        ),
    };

    Ok(quote! {
        // Variant idents mirror the proto value names (UPPER_SNAKE), which trip the
        // camel-case lint; the conversions are intentionally exhaustive.
        #[allow(non_camel_case_types)]
        // `from_py_object`: `Clone` + pyo3 0.28's opt-in `FromPyObject` (see the message
        // wrapper emitter). Keep the derive explicit to preserve pre-0.28 behavior.
        #[::pyo3::pyclass(eq, eq_int, name = #class_name, from_py_object)]
        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
        pub enum #wrapper {
            #(#variants = #numbers,)*
        }

        impl #wrapper {
            fn __to_proto_i32(self) -> i32 {
                match self {
                    #(#to_i32_arms,)*
                }
            }
            fn __from_proto_i32(value: i32) -> Self {
                match value {
                    #(#from_i32_arms,)*
                    // Unknown values fall back to the first declared variant.
                    _ => #wrapper::#fallback,
                }
            }
        }

        impl ::core::convert::From<#inner> for #wrapper {
            fn from(value: #inner) -> Self {
                #wrapper::__from_proto_i32(#inner_to_i32)
            }
        }

        impl ::core::convert::From<#wrapper> for #inner {
            fn from(value: #wrapper) -> Self {
                let n = value.__to_proto_i32();
                #i32_to_inner
            }
        }
    })
}

// ---------------------------------------------------------------------------
// Message wrappers
// ---------------------------------------------------------------------------

/// Emit a newtype `#[pyclass]` wrapping a model message: keyword constructor,
/// native typed getters/setters per field, `__repr__`/`__eq__`, and the
/// `From`/`Into` bridges to the bare model type.
fn message_wrapper(
    fq_name: &str,
    info: &MessageInfo,
    rust_path: &str,
    runtime: Runtime,
    metadata: &CodeGenMetadata,
) -> crate::error::Result<TokenStream> {
    let wrapper = wrapper_ident(fq_name);
    let class_name = python_class_name(fq_name);
    let inner: syn::Path = parse_path(rust_path, fq_name)?;

    // Plain (non-oneof) fields get one `FieldAccessor` each; oneof fields are
    // handled separately by `OneofAccessor`, which flattens each oneof into one
    // optional keyword arg / per-variant setter+getter (see issue #99).
    let plain_fields: Vec<&MessageField> = info
        .fields
        .iter()
        .filter(|f| f.oneof_variants.is_none())
        .collect();
    let oneof_fields: Vec<&MessageField> = info
        .fields
        .iter()
        .filter(|f| f.oneof_variants.is_some())
        .collect();

    let packages = metadata_packages(metadata);
    let project_pkg_refs: BTreeSet<&str> = packages.iter().map(String::as_str).collect();
    let boxed = boxed_fields(metadata, runtime);
    let accessors: Vec<FieldAccessor> = plain_fields
        .iter()
        .map(|f| {
            let is_boxed = boxed.contains(&(fq_name.to_string(), f.name.clone()));
            FieldAccessor::new(f, runtime, &packages, &project_pkg_refs, is_boxed)
        })
        .collect();

    // Resolve each oneof into its variants. The oneof enum lives in the message's
    // parent module (buffa exposes it there via a natural-path re-export, prost
    // nests it directly); every variant payload is resolved to its Python-visible
    // wrapper type just like a plain field.
    let oneofs: Vec<OneofAccessor> = oneof_fields
        .iter()
        .map(|f| OneofAccessor::new(f, &inner, runtime, &packages))
        .collect();

    let getters = accessors.iter().map(FieldAccessor::getter);
    let setters = accessors.iter().map(FieldAccessor::setter);
    let oneof_getters = oneofs.iter().flat_map(OneofAccessor::variant_getters);
    let oneof_setters = oneofs.iter().flat_map(OneofAccessor::variant_setters);
    let ctor = constructor(&accessors, &oneofs, &inner);

    Ok(quote! {
        // `from_py_object`: these wrappers are `Clone`, and pyo3 0.28 made the auto
        // `FromPyObject` derive for `Clone` `#[pyclass]` types opt-in. Keep the pre-0.28
        // behavior (derive it) explicitly so Python callers can still pass a wrapper into
        // Rust-side functions and to silence the deprecation under `-D warnings`.
        #[::pyo3::pyclass(name = #class_name, from_py_object)]
        #[derive(Clone, Debug)]
        pub struct #wrapper(pub #inner);

        #[allow(clippy::too_many_arguments, clippy::useless_conversion)]
        #[::pyo3::pymethods]
        impl #wrapper {
            #ctor

            #(#getters)*
            #(#setters)*
            #(#oneof_getters)*
            #(#oneof_setters)*

            fn __repr__(&self) -> ::std::string::String {
                ::std::format!("{:?}", self.0)
            }

            fn __eq__(&self, other: &Self) -> bool {
                self.0 == other.0
            }
        }

        impl ::core::convert::From<#inner> for #wrapper {
            fn from(value: #inner) -> Self {
                Self(value)
            }
        }

        impl ::core::convert::From<#wrapper> for #inner {
            fn from(value: #wrapper) -> Self {
                value.0
            }
        }
    })
}

/// Project package set, recomputed lazily for `FieldAccessor` so it can decide
/// whether a referenced message/enum is in-project (gets a wrapper) or foreign.
fn metadata_packages(metadata: &CodeGenMetadata) -> BTreeSet<String> {
    metadata
        .services
        .values()
        .map(|s| s.package.clone())
        .collect()
}

/// The set of `(message_fq_name, field_name)` pairs that the prost model plugin
/// stores as `Option<Box<T>>` rather than `Option<T>`.
///
/// prost only boxes a singular message field when leaving it unboxed would make
/// the struct infinitely sized — i.e. the field's message type can transitively
/// reach back to the containing message through a chain of singular (non-repeated,
/// non-map) message fields. Repeated and map fields already introduce an
/// indirection (`Vec`/`HashMap`), so they break the cycle and are never boxed.
///
/// We replicate that rule here so the PyO3 read/write accessors deref/box exactly
/// the fields prost boxed. Returns an empty set for the buffa runtime, which uses
/// `MessageField<T>` uniformly and never boxes.
fn boxed_fields(metadata: &CodeGenMetadata, runtime: Runtime) -> BTreeSet<(String, String)> {
    let mut boxed = BTreeSet::new();
    if runtime != Runtime::Prost {
        return boxed;
    }
    for (msg_name, info) in &metadata.messages {
        for field in &info.fields {
            // Only singular message fields can be boxed; repeated/map fields carry
            // their own indirection, and scalars/enums are never boxed.
            if field.unified_type.is_repeated
                || matches!(field.unified_type.base_type, BaseType::Map(_, _))
            {
                continue;
            }
            let BaseType::Message(target) = &field.unified_type.base_type else {
                continue;
            };
            // Box iff the field's type can reach back to the containing message.
            if reaches(metadata, target, msg_name) {
                boxed.insert((msg_name.clone(), field.name.clone()));
            }
        }
    }
    boxed
}

/// Whether message `from` can transitively reach message `target` by following
/// singular (non-repeated, non-map) message fields. Used to detect the recursion
/// cycles that drive prost's automatic field boxing.
fn reaches(metadata: &CodeGenMetadata, from: &str, target: &str) -> bool {
    let mut stack = vec![from.to_string()];
    let mut seen = BTreeSet::new();
    while let Some(cur) = stack.pop() {
        if cur == target {
            return true;
        }
        if !seen.insert(cur.clone()) {
            continue;
        }
        let Some(info) = metadata.messages.get(&cur) else {
            continue;
        };
        for field in &info.fields {
            if field.unified_type.is_repeated
                || matches!(field.unified_type.base_type, BaseType::Map(_, _))
            {
                continue;
            }
            if let BaseType::Message(next) = &field.unified_type.base_type {
                stack.push(next.clone());
            }
        }
    }
    false
}

/// A single message field, resolved into the Rust expressions needed to expose it
/// across the PyO3 boundary as a native, typed Python attribute.
struct FieldAccessor {
    /// The Python/Rust-visible field identifier (snake_case, keyword-sanitized).
    ident: proc_macro2::Ident,
    /// The original field, for cardinality flags and base type.
    ty: UnifiedType,
    runtime: Runtime,
    /// Whether the referenced message/enum is in the project (gets a wrapper).
    in_project: bool,
    /// In-crate Rust path of a referenced message/enum (e.g. `super::catalog::v1::Color`),
    /// when in-project; used by enum/message read expressions. `None` otherwise.
    inner_rust_path: Option<TokenStream>,
    /// Whether the prost model stores this singular message field as
    /// `Option<Box<T>>` (it sits on a recursion cycle). Drives whether the read
    /// path derefs the box and the write path re-boxes. Always `false` for buffa.
    is_boxed: bool,
}

impl FieldAccessor {
    fn new(
        field: &MessageField,
        runtime: Runtime,
        packages: &BTreeSet<String>,
        project_pkg_refs: &BTreeSet<&str>,
        is_boxed: bool,
    ) -> Self {
        let ident = format_ident!("{}", super::sanitize_python_field_name(&field.name));
        let in_project = match &field.unified_type.base_type {
            BaseType::Message(n) | BaseType::Enum(n) => is_in_project(n, packages),
            _ => false,
        };
        let inner_rust_path = match &field.unified_type.base_type {
            BaseType::Message(n) | BaseType::Enum(n) if in_project => {
                type_rust_path(n, project_pkg_refs)
                    .and_then(|p| syn::parse_str::<syn::Path>(&p).ok())
                    .map(|p| quote! { #p })
            }
            _ => None,
        };
        Self {
            ident,
            ty: field.unified_type.clone(),
            runtime,
            in_project,
            inner_rust_path,
            is_boxed,
        }
    }

    /// The Python-visible Rust type for this field (the getter return / setter
    /// arg). Messages/enums map to their `Py`-prefixed wrapper; collections wrap
    /// in `Vec`/`HashMap`; optional non-collection fields wrap in `Option`.
    fn py_type(&self) -> TokenStream {
        let base = self.base_py_type();
        if self.ty.is_repeated {
            return quote! { ::std::vec::Vec<#base> };
        }
        if let BaseType::Map(_, v) = &self.ty.base_type {
            let val = py_type_for(v, self.in_project);
            return quote! { ::std::collections::HashMap<::std::string::String, #val> };
        }
        // Singular (non-repeated) message fields carry proto presence semantics, so
        // they are always Python-visible as `Optional[...]` — the read path returns
        // `Option<Wrapper>` for both runtimes (buffa `MessageField::into_option`,
        // prost `Option<T>` or `Option<Box<T>>` for recursion-boxed fields).
        if self.is_singular_message() {
            return quote! { ::core::option::Option<#base> };
        }
        // Explicit-presence scalars/enums (proto3 `optional`) are stored as
        // `Option<T>` by both the buffa and prost model plugins, so the wrapper
        // surfaces them as `Optional[...]` too.
        if self.is_optional_scalar() {
            return quote! { ::core::option::Option<#base> };
        }
        base
    }

    fn base_py_type(&self) -> TokenStream {
        py_type_for(&self.ty, self.in_project)
    }

    fn is_singular_message(&self) -> bool {
        !self.ty.is_repeated
            && matches!(self.ty.base_type, BaseType::Message(_) | BaseType::OneOf(_))
    }

    /// Whether [`Self::py_type`] is itself an `Option<..>` — i.e. the field is a
    /// singular message or an explicit-presence scalar/enum. Such fields must not be
    /// re-wrapped in the keyword constructor (would yield ambiguous `Option<Option<T>>`).
    fn py_type_is_optional(&self) -> bool {
        self.is_singular_message() || self.is_optional_scalar()
    }

    /// An explicit-presence scalar or enum (proto3 `optional`): stored as
    /// `Option<T>` (scalar) or `Option<EnumValue<E>>`/`Option<i32>` (enum) by the
    /// model plugins, as opposed to messages whose presence is intrinsic.
    fn is_optional_scalar(&self) -> bool {
        self.ty.is_optional
            && !self.ty.is_repeated
            && !matches!(
                self.ty.base_type,
                BaseType::Message(_) | BaseType::OneOf(_) | BaseType::Map(_, _)
            )
    }

    /// `#[getter]` returning the field as its Python-visible type.
    fn getter(&self) -> TokenStream {
        let ident = &self.ident;
        let ret = self.py_type();
        let body = self.read_expr();
        quote! {
            #[getter]
            fn #ident(&self) -> #ret {
                #body
            }
        }
    }

    /// `#[setter]` accepting the Python-visible type and storing into the inner.
    fn setter(&self) -> TokenStream {
        let ident = &self.ident;
        let setter_name = format_ident!("set_{}", self.ident);
        let arg = self.py_type();
        let store = self.write_expr();
        quote! {
            #[setter(#ident)]
            fn #setter_name(&mut self, value: #arg) {
                self.0.#ident = #store;
            }
        }
    }

    /// Expression that reads `self.0.<field>` and converts it to the Python type.
    fn read_expr(&self) -> TokenStream {
        let ident = &self.ident;
        let access = quote! { self.0.#ident };

        if self.ty.is_repeated {
            return self.read_repeated(&access);
        }
        if let BaseType::Map(_, v) = &self.ty.base_type {
            return read_map(&access, v, self.in_project);
        }
        if self.is_optional_scalar() {
            return self.read_optional_scalar(&access);
        }

        match &self.ty.base_type {
            BaseType::String => quote! { #access.clone() },
            BaseType::Bytes => quote! { #access.clone() },
            BaseType::Int32
            | BaseType::Int64
            | BaseType::Bool
            | BaseType::Float32
            | BaseType::Float64 => quote! { #access },
            BaseType::Enum(_) => self.read_enum(&access),
            BaseType::Message(_) | BaseType::OneOf(_) => self.read_message(&access),
            BaseType::Unit | BaseType::Map(_, _) => quote! { #access.clone() },
        }
    }

    fn read_repeated(&self, access: &TokenStream) -> TokenStream {
        let base = self.base_py_type();
        let inner = self.inner_rust_path.as_ref();
        match &self.ty.base_type {
            BaseType::Enum(_) => match self.runtime {
                // buffa repeated enum: Vec<EnumValue<E>>; keep known values only.
                Runtime::Buffa => quote! {
                    #access.iter().filter_map(|e| e.as_known().map(#base::from)).collect()
                },
                // prost repeated enum: Vec<i32>; map through the bare Rust enum.
                Runtime::Prost => quote! {
                    #access.iter().filter_map(|&v| <#inner as ::core::convert::TryFrom<i32>>::try_from(v).ok().map(#base::from)).collect()
                },
            },
            BaseType::Message(_) => quote! {
                #access.iter().cloned().map(#base::from).collect()
            },
            BaseType::String | BaseType::Bytes => quote! { #access.clone() },
            _ => quote! { #access.clone() },
        }
    }

    fn read_enum(&self, access: &TokenStream) -> TokenStream {
        let base = self.base_py_type();
        let inner = self.inner_rust_path.as_ref();
        match self.runtime {
            // buffa: EnumValue<E> -> Option<E> via as_known(); fall back to the inner
            // enum's Default (the zero/unspecified variant), then to the wrapper.
            Runtime::Buffa => quote! {
                #base::from(#access.as_known().unwrap_or_default())
            },
            // prost: i32 -> E via TryFrom, fall back to the inner enum's Default.
            Runtime::Prost => quote! {
                #base::from(
                    <#inner as ::core::convert::TryFrom<i32>>::try_from(#access)
                        .unwrap_or_default()
                )
            },
        }
    }

    fn read_message(&self, access: &TokenStream) -> TokenStream {
        let base = self.base_py_type();
        match self.runtime {
            // buffa: MessageField<T> -> Option<T>
            Runtime::Buffa => quote! {
                #access.clone().into_option().map(#base::from)
            },
            // prost recursion-boxed field: Option<Box<T>> — deref the box.
            Runtime::Prost if self.is_boxed => quote! {
                #access.clone().map(|b| #base::from(*b))
            },
            // prost plain singular message: Option<T>.
            Runtime::Prost => quote! {
                #access.clone().map(#base::from)
            },
        }
    }

    /// Read an explicit-presence (proto3 `optional`) scalar/enum field, whose
    /// stored type is `Option<..>` — surfaced to Python as `Option<base>`.
    fn read_optional_scalar(&self, access: &TokenStream) -> TokenStream {
        let base = self.base_py_type();
        let inner = self.inner_rust_path.as_ref();
        match &self.ty.base_type {
            // buffa: Option<EnumValue<E>>; prost: Option<i32>.
            BaseType::Enum(_) => match self.runtime {
                Runtime::Buffa => quote! {
                    #access.as_ref().and_then(|e| e.as_known()).map(#base::from)
                },
                Runtime::Prost => quote! {
                    #access.and_then(|v| <#inner as ::core::convert::TryFrom<i32>>::try_from(v).ok())
                        .map(#base::from)
                },
            },
            // Option<{int,bool,float}>: the inner scalar is `Copy`, so the `Option`
            // copies by value — `.clone()` here would trip `clippy::clone_on_copy`.
            BaseType::Int32
            | BaseType::Int64
            | BaseType::Bool
            | BaseType::Float32
            | BaseType::Float64 => quote! { #access },
            // Option<String>/Option<Vec<u8>>: non-Copy, clone through.
            _ => quote! { #access.clone() },
        }
    }

    /// Expression converting a Python-typed `value` back into the inner field
    /// representation for storage.
    fn write_expr(&self) -> TokenStream {
        if self.ty.is_repeated {
            return self.write_repeated();
        }
        if let BaseType::Map(_, _) = &self.ty.base_type {
            return quote! { value };
        }
        if self.is_optional_scalar() {
            return self.write_optional_scalar();
        }
        match &self.ty.base_type {
            BaseType::Enum(_) => self.write_enum(),
            BaseType::Message(_) | BaseType::OneOf(_) => self.write_message(),
            _ => quote! { value },
        }
    }

    /// Store an explicit-presence scalar/enum: `value` is `Option<base>`.
    fn write_optional_scalar(&self) -> TokenStream {
        let inner = self.inner_rust_path.as_ref();
        match &self.ty.base_type {
            // buffa: Option<EnumValue<E>>; prost: Option<i32>.
            BaseType::Enum(_) => match self.runtime {
                Runtime::Buffa => quote! {
                    value.map(|e| ::buffa::EnumValue::Known(<#inner as ::core::convert::From<_>>::from(e)))
                },
                Runtime::Prost => quote! {
                    value.map(|e| <#inner as ::core::convert::From<_>>::from(e) as i32)
                },
            },
            // Option<String> etc. store directly.
            _ => quote! { value },
        }
    }

    fn write_repeated(&self) -> TokenStream {
        let inner = self.inner_rust_path.as_ref();
        match &self.ty.base_type {
            BaseType::Enum(_) => match self.runtime {
                Runtime::Buffa => quote! {
                    value.into_iter()
                        .map(|e| ::buffa::EnumValue::Known(<#inner as ::core::convert::From<_>>::from(e)))
                        .collect()
                },
                Runtime::Prost => quote! {
                    value.into_iter()
                        .map(|e| <#inner as ::core::convert::From<_>>::from(e) as i32)
                        .collect()
                },
            },
            BaseType::Message(_) => quote! {
                value.into_iter().map(::core::convert::Into::into).collect()
            },
            _ => quote! { value },
        }
    }

    fn write_enum(&self) -> TokenStream {
        let inner = self.inner_rust_path.as_ref();
        match self.runtime {
            Runtime::Buffa => quote! {
                ::buffa::EnumValue::Known(<#inner as ::core::convert::From<_>>::from(value))
            },
            Runtime::Prost => quote! {
                <#inner as ::core::convert::From<_>>::from(value) as i32
            },
        }
    }

    /// Singular message write: `value` is always `Option<Wrapper>` (see
    /// [`Self::is_singular_message`]); store into the runtime's optional-message
    /// representation.
    fn write_message(&self) -> TokenStream {
        match self.runtime {
            // buffa: MessageField<T>
            Runtime::Buffa => quote! {
                value.map(|w| ::buffa::MessageField::some(w.into())).unwrap_or_default()
            },
            // prost recursion-boxed field: Option<Box<T>> — re-box on store.
            Runtime::Prost if self.is_boxed => quote! {
                value.map(|w| ::std::boxed::Box::new(w.into()))
            },
            // prost plain singular message: Option<T>.
            Runtime::Prost => quote! {
                value.map(|w| w.into())
            },
        }
    }
}

// ---------------------------------------------------------------------------
// Oneof accessors
// ---------------------------------------------------------------------------

/// A proto `oneof`, resolved into the tokens needed to expose it across the PyO3
/// boundary. Each oneof is *flattened*: one optional keyword arg + one
/// `set_<variant>` setter + one `<variant>` getter per member (issue #99).
///
/// The inner model stores a oneof as `Option<Enum>` where `Enum` has one tuple
/// variant per member. buffa reaches the enum through a natural-path re-export in
/// the message's snake_case module and boxes *every* message/group payload
/// (`Variant(Box<T>)`); prost nests the enum in the same module and stores message
/// payloads inline (`Variant(T)`), boxing only recursion-cycle payloads. The
/// message write/read paths branch on [`Runtime`] to add/strip that `Box`
/// (`Box::new`/`**` for buffa, direct/`*` for prost); scalar and enum payloads are
/// inline for both. Payloads cross the boundary via the wrapper's `From`/`Into`.
struct OneofAccessor {
    /// The oneof field ident on the inner struct (e.g. `provider`).
    field_ident: proc_macro2::Ident,
    /// In-crate path to the oneof enum (e.g. `super::catalog::v1::storage_config::Provider`).
    enum_path: TokenStream,
    runtime: Runtime,
    variants: Vec<OneofVariantAccessor>,
}

/// One member of a oneof, resolved to its Python-visible payload type and the
/// Rust variant it maps to.
struct OneofVariantAccessor {
    /// The Rust enum variant ident (PascalCase proto field name, e.g. `S3`).
    variant_ident: proc_macro2::Ident,
    /// The flattened keyword-arg / accessor ident (the proto field name, e.g. `s3`).
    param_ident: proc_macro2::Ident,
    /// The setter ident (`set_<param>`).
    setter_ident: proc_macro2::Ident,
    /// The Python-visible payload wrapper type (e.g. `PyS3Config`, `i64`).
    payload_ty: TokenStream,
    /// Whether the payload is an in-project message (needs `.into()`/`From` bridge)
    /// vs. a scalar (stored/read directly).
    is_message: bool,
    /// Whether the payload is an in-project enum (crosses via the enum wrapper's
    /// `From`, and is stored inline — never boxed).
    is_enum: bool,
    /// Documentation carried from the proto variant, for the getter.
    documentation: Option<String>,
}

impl OneofAccessor {
    fn new(
        field: &MessageField,
        inner: &syn::Path,
        runtime: Runtime,
        packages: &BTreeSet<String>,
    ) -> Self {
        let field_ident = format_ident!("{}", super::sanitize_python_field_name(&field.name));

        // The oneof enum's name in the IR is already `<msg_snake>::<OneofPascal>`
        // (built in `parsing/message.rs`); it lives in the message's parent module.
        // Splice it onto the message's own module path: drop the message leaf from
        // `inner` (e.g. `super::catalog::v1::StorageConfig`) and append the enum name.
        let BaseType::OneOf(enum_name) = &field.unified_type.base_type else {
            // Only ever constructed for oneof fields; fall back defensively.
            unreachable!("OneofAccessor::new called on a non-oneof field");
        };
        let enum_path = oneof_enum_path(inner, enum_name);

        let variants = field
            .oneof_variants
            .as_deref()
            .unwrap_or(&[])
            .iter()
            .map(|v| OneofVariantAccessor::new(v, packages))
            .collect();

        Self {
            field_ident,
            enum_path,
            runtime,
            variants,
        }
    }

    /// The flattened keyword-arg idents (proto field names), for the `#[pyo3(signature)]`.
    fn variant_param_idents(&self) -> Vec<String> {
        self.variants
            .iter()
            .map(|v| v.param_ident.to_string())
            .collect()
    }

    /// One `Option<PyPayload>` constructor param per variant.
    fn ctor_params(&self) -> Vec<TokenStream> {
        self.variants
            .iter()
            .map(|v| {
                let ident = &v.param_ident;
                let ty = &v.payload_ty;
                quote! { #ident: ::core::option::Option<#ty> }
            })
            .collect()
    }

    /// Constructor body: set the oneof from whichever variant kwarg is `Some`.
    /// Emitted in declaration order, so a later variant overrides an earlier one.
    fn ctor_assigns(&self) -> Vec<TokenStream> {
        let field_ident = &self.field_ident;
        self.variants
            .iter()
            .map(|v| {
                let param = &v.param_ident;
                let store = v.write_variant(&self.enum_path, self.runtime);
                quote! {
                    if let ::core::option::Option::Some(value) = #param {
                        inner.#field_ident = ::core::option::Option::Some(#store);
                    }
                }
            })
            .collect()
    }

    /// A `#[setter]` per variant: setting one variant to `Some` replaces the oneof;
    /// setting it to `None` clears the oneof only if that variant is currently active.
    fn variant_setters(&self) -> Vec<TokenStream> {
        let field_ident = &self.field_ident;
        self.variants
            .iter()
            .map(|v| {
                let setter = &v.setter_ident;
                let param = &v.param_ident;
                let ty = &v.payload_ty;
                let variant = &v.variant_ident;
                let enum_path = &self.enum_path;
                let store = v.write_variant(enum_path, self.runtime);
                quote! {
                    #[setter(#param)]
                    fn #setter(&mut self, value: ::core::option::Option<#ty>) {
                        match value {
                            ::core::option::Option::Some(value) => {
                                self.0.#field_ident = ::core::option::Option::Some(#store);
                            }
                            // Clearing this variant only clears the oneof when it is
                            // the active one; leave a different active variant intact.
                            ::core::option::Option::None => {
                                if ::core::matches!(
                                    self.0.#field_ident,
                                    ::core::option::Option::Some(#enum_path::#variant(_))
                                ) {
                                    self.0.#field_ident = ::core::option::Option::None;
                                }
                            }
                        }
                    }
                }
            })
            .collect()
    }

    /// A `#[getter]` per variant returning `Option<PyPayload>` — `Some` only when
    /// that variant is the active one.
    fn variant_getters(&self) -> Vec<TokenStream> {
        let field_ident = &self.field_ident;
        self.variants
            .iter()
            .map(|v| {
                let getter = &v.param_ident;
                let ty = &v.payload_ty;
                let variant = &v.variant_ident;
                let enum_path = &self.enum_path;
                let read = v.read_variant(self.runtime);
                let doc = v
                    .documentation
                    .as_deref()
                    .map(|d| quote! { #[doc = #d] })
                    .unwrap_or_default();
                quote! {
                    #doc
                    #[getter]
                    fn #getter(&self) -> ::core::option::Option<#ty> {
                        match &self.0.#field_ident {
                            ::core::option::Option::Some(#enum_path::#variant(value)) => {
                                ::core::option::Option::Some(#read)
                            }
                            _ => ::core::option::Option::None,
                        }
                    }
                }
            })
            .collect()
    }
}

impl OneofVariantAccessor {
    fn new(variant: &OneofVariant, packages: &BTreeSet<String>) -> Self {
        let param_ident =
            format_ident!("{}", super::sanitize_python_field_name(&variant.field_name));
        let setter_ident = format_ident!("set_{param_ident}");
        let variant_ident = format_ident!("{}", variant.variant_name);

        let (is_message, is_enum) = match &variant.field_type.base_type {
            BaseType::Message(n) => (is_in_project(n.as_str(), packages), false),
            BaseType::Enum(n) => (false, is_in_project(n.as_str(), packages)),
            _ => (false, false),
        };
        let in_project = is_message || is_enum;
        let payload_ty = py_type_for(&variant.field_type, in_project);

        Self {
            variant_ident,
            param_ident,
            setter_ident,
            payload_ty,
            is_message,
            is_enum,
            documentation: variant.documentation.clone(),
        }
    }

    /// Expression producing `<EnumPath>::<Variant>(payload)` from a bound `value`
    /// of the Python-visible payload type.
    fn write_variant(&self, enum_path: &TokenStream, runtime: Runtime) -> TokenStream {
        let variant = &self.variant_ident;
        if self.is_message {
            // Message payloads bridge via `From<PyWrapper>` for the bare model type.
            // buffa boxes *every* message variant; prost stores it inline (matching
            // the builder's `generate_oneof_variant_methods`). A prost oneof whose
            // variant is recursive would be boxed by prost and mismatch here — the
            // same untested corner the builder shares; no IR flag distinguishes it.
            match runtime {
                Runtime::Buffa => quote! {
                    #enum_path::#variant(::std::boxed::Box::new(value.into()))
                },
                Runtime::Prost => quote! {
                    #enum_path::#variant(value.into())
                },
            }
        } else if self.is_enum {
            // Enum payloads: the wrapper converts to the bare model enum via `From`.
            quote! {
                #enum_path::#variant(value.into())
            }
        } else {
            // Scalar payloads are stored directly.
            quote! {
                #enum_path::#variant(value)
            }
        }
    }

    /// Expression converting the matched variant payload — bound as `value` by ref
    /// in the getter's `match` arm — into the Python-visible type.
    fn read_variant(&self, runtime: Runtime) -> TokenStream {
        let ty = &self.payload_ty;
        if self.is_message {
            // buffa boxes message variants (`value: &Box<T>`), prost does not
            // (`value: &T`). Deref to `T` accordingly, clone, then bridge to the
            // wrapper via `From<T>`.
            match runtime {
                Runtime::Buffa => quote! { <#ty>::from((**value).clone()) },
                Runtime::Prost => quote! { <#ty>::from((*value).clone()) },
            }
        } else if self.is_enum {
            // `value: &BareEnum` (`Copy`); the wrapper bridges via `From<BareEnum>`.
            quote! { <#ty>::from(*value) }
        } else {
            // Scalar payloads: clone the referenced value out.
            quote! { ::core::clone::Clone::clone(value) }
        }
    }
}

/// Build the in-crate Rust path to a oneof enum, given the containing message's
/// path (`inner`) and the enum's IR name (`<msg_snake>::<OneofPascal>`).
///
/// The enum sits in the message's *parent* module — buffa via a natural-path
/// re-export, prost via direct nesting — so we drop the message's own leaf
/// segment from `inner` (e.g. `super::catalog::v1::StorageConfig` →
/// `super::catalog::v1`) and append the enum name (`storage_config::Provider`).
fn oneof_enum_path(inner: &syn::Path, enum_name: &str) -> TokenStream {
    let parent_segments = inner
        .segments
        .iter()
        .take(inner.segments.len().saturating_sub(1))
        .map(|s| s.ident.clone());
    let tail: syn::Path =
        syn::parse_str(enum_name).expect("oneof enum IR name is a valid `snake::Pascal` path");
    quote! { #(#parent_segments::)* #tail }
}

/// The Python-visible base type (no cardinality wrapping) for a unified type.
fn py_type_for(ty: &UnifiedType, in_project: bool) -> TokenStream {
    match &ty.base_type {
        BaseType::String => quote! { ::std::string::String },
        BaseType::Bytes => quote! { ::std::vec::Vec<u8> },
        BaseType::Int32 => quote! { i32 },
        BaseType::Int64 => quote! { i64 },
        BaseType::Bool => quote! { bool },
        BaseType::Float32 => quote! { f32 },
        BaseType::Float64 => quote! { f64 },
        BaseType::Unit => quote! { () },
        BaseType::Message(n) | BaseType::Enum(n) => {
            if in_project {
                let w = wrapper_ident(n);
                quote! { #w }
            } else {
                // Foreign type (no wrapper): fall back to the bare simple name.
                let id = format_ident!("{}", extract_simple_type_name(n));
                quote! { #id }
            }
        }
        BaseType::OneOf(n) => {
            let id = format_ident!("{}", extract_simple_type_name(n));
            quote! { #id }
        }
        BaseType::Map(_, v) => {
            let val = py_type_for(v, in_project);
            quote! { ::std::collections::HashMap<::std::string::String, #val> }
        }
    }
}

/// Read a `map<string, V>` field into a `HashMap`, converting message values to
/// their wrappers when in-project.
fn read_map(access: &TokenStream, value: &UnifiedType, in_project: bool) -> TokenStream {
    match &value.base_type {
        BaseType::Message(_) if in_project => {
            let w = py_type_for(value, true);
            quote! {
                #access.iter().map(|(k, v)| (k.clone(), #w::from(v.clone()))).collect()
            }
        }
        _ => quote! { #access.clone() },
    }
}

/// The keyword `#[new]` constructor: every plain field is an optional keyword
/// argument defaulting to `None`, and each oneof is *flattened* into one optional
/// keyword arg per variant (matching the hand-written constructors downstream
/// adopters used, see issue #99). Provided values are stored; omitted ones fall
/// back to the inner type's `Default`. If more than one variant of the same oneof
/// is supplied, the last one in proto declaration order wins.
fn constructor(
    accessors: &[FieldAccessor],
    oneofs: &[OneofAccessor],
    inner: &syn::Path,
) -> TokenStream {
    if accessors.is_empty() && oneofs.is_empty() {
        return quote! {
            #[new]
            fn new() -> Self {
                Self(::core::default::Default::default())
            }
        };
    }

    // Plain-field params: fields whose Python type is *already* `Option<..>`
    // (singular messages, explicit-presence scalars) must not be double-wrapped —
    // `Option<Option<T>>` makes pyo3's `#[new]` arg-coercion ambiguous. For those
    // the single `Option` already encodes the "omitted/None" keyword default.
    let field_params = accessors.iter().map(|a| {
        let ident = &a.ident;
        let ty = a.py_type();
        if a.py_type_is_optional() {
            quote! { #ident: #ty }
        } else {
            quote! { #ident: ::core::option::Option<#ty> }
        }
    });
    // One `Option<PyPayload>` param per oneof variant, flattened across all oneofs.
    let oneof_params = oneofs.iter().flat_map(OneofAccessor::ctor_params);
    let params = field_params.chain(oneof_params);

    // `<name> = None` for every plain field then every oneof variant, in order.
    let sig_parts = accessors
        .iter()
        .map(|a| a.ident.to_string())
        .chain(oneofs.iter().flat_map(OneofAccessor::variant_param_idents))
        .map(|ident| format!("{ident} = None"))
        .collect::<Vec<_>>()
        .join(", ");
    let sig: TokenStream = sig_parts.parse().expect("field idents are valid tokens");

    let assigns = accessors.iter().map(|a| {
        let ident = &a.ident;
        // Reuse the setter's write expression by binding `value`.
        let store = a.write_expr();
        if a.py_type_is_optional() {
            // `value` is the whole (already-`Option`) argument; store unconditionally
            // (an omitted kwarg arrives as `None`, the field's natural absent value).
            quote! {
                {
                    let value = #ident;
                    inner.#ident = #store;
                }
            }
        } else {
            quote! {
                if let ::core::option::Option::Some(value) = #ident {
                    inner.#ident = #store;
                }
            }
        }
    });
    let oneof_assigns = oneofs.iter().flat_map(OneofAccessor::ctor_assigns);

    quote! {
        #[new]
        #[pyo3(signature = (#sig))]
        fn new(#(#params,)*) -> Self {
            let mut inner = <#inner as ::core::default::Default>::default();
            #(#assigns)*
            #(#oneof_assigns)*
            Self(inner)
        }
    }
}

// ---------------------------------------------------------------------------
// Path helpers (shared with the former pythonize impl)
// ---------------------------------------------------------------------------

fn parse_path(rust_path: &str, fq_name: &str) -> crate::error::Result<syn::Path> {
    syn::parse_str(rust_path).map_err(|e| crate::error::Error::InvalidRustPath {
        path: rust_path.to_string(),
        message: fq_name.to_string(),
        source: e,
    })
}

/// Whether a fully-qualified type name belongs to one of the project's packages.
fn is_in_project(fq_name: &str, packages: &BTreeSet<String>) -> bool {
    let stripped = fq_name.strip_prefix('.').unwrap_or(fq_name);
    packages.iter().any(|pkg| {
        stripped == pkg
            || stripped
                .strip_prefix(pkg.as_str())
                .is_some_and(|rest| rest.starts_with('.'))
    })
}

/// Map a fully-qualified proto type name to its in-crate Rust path, as exposed by
/// the model module tree `generate_models_mod` emits.
///
/// `pyo3_impls.rs` is a sibling of the per-package model modules inside the models
/// subdir, so the path is `super::<svc_seg>::<ver_seg>::<...nested>::<Name>` where
/// `(svc_seg, ver_seg)` are the second-to-last and last segments of the owning
/// package — exactly the module nesting `generate_models_mod` produces.
///
/// Returns `None` for types outside the project's own packages (e.g. imported
/// google/gnostic types), which have no in-crate path and must be skipped.
fn type_rust_path(fq_name: &str, project_packages: &BTreeSet<&str>) -> Option<String> {
    let stripped = fq_name.strip_prefix('.').unwrap_or(fq_name);

    let package = project_packages
        .iter()
        .filter(|pkg| {
            stripped == **pkg
                || stripped
                    .strip_prefix(**pkg)
                    .is_some_and(|rest| rest.starts_with('.'))
        })
        .max_by_key(|pkg| pkg.len())?;

    let remainder = stripped.strip_prefix(package)?.trim_start_matches('.');
    if remainder.is_empty() {
        return None;
    }

    let pkg_parts: Vec<&str> = package.split('.').collect();
    let module_path = if pkg_parts.len() >= 2 {
        format!(
            "{}::{}",
            pkg_parts[pkg_parts.len() - 2],
            pkg_parts[pkg_parts.len() - 1]
        )
    } else {
        pkg_parts[0].to_string()
    };

    // `remainder` is the dot-joined type path within the package, e.g.
    // `GenerateTableCredentialsRequest.Operation` for a message-nested enum. Both
    // the prost and buffa model trees nest a type defined inside a message under a
    // *snake_case module* named after that parent message, with only the leaf type
    // keeping its proto (PascalCase) name. So snake_case every segment except the
    // last (`generate_table_credentials_request::Operation`), not a flat `::` join.
    let segments: Vec<&str> = remainder.split('.').collect();
    let (leaf, parents) = segments.split_last()?;
    let type_path = parents
        .iter()
        .map(|seg| seg.to_case(Case::Snake))
        .chain(std::iter::once((*leaf).to_string()))
        .collect::<Vec<_>>()
        .join("::");
    Some(format!("super::{module_path}::{type_path}"))
}

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

    fn pkgs(list: &[&'static str]) -> BTreeSet<&'static str> {
        list.iter().copied().collect()
    }

    #[test]
    fn oneof_enum_path_splices_enum_name_onto_message_parent_module() {
        // The oneof enum lives in the message's *parent* module: drop the message
        // leaf from `inner` and append the IR enum name (`<msg_snake>::<OneofPascal>`).
        let inner: syn::Path = syn::parse_str("super::catalog::v1::StorageConfig").unwrap();
        let path = oneof_enum_path(&inner, "storage_config::Provider");
        assert_eq!(
            path.to_string().replace(' ', ""),
            "super::catalog::v1::storage_config::Provider"
        );
    }

    #[test]
    fn oneof_enum_path_handles_top_level_message() {
        // A message at the crate root (single-segment `inner`) still resolves: the
        // parent module is empty, so the enum name is the whole path.
        let inner: syn::Path = syn::parse_str("Shape").unwrap();
        let path = oneof_enum_path(&inner, "shape::Kind");
        assert_eq!(path.to_string().replace(' ', ""), "shape::Kind");
    }

    #[test]
    fn three_segment_package_maps_to_service_version_module() {
        let p = pkgs(&["example.catalog.v1"]);
        assert_eq!(
            type_rust_path(".example.catalog.v1.Catalog", &p).as_deref(),
            Some("super::catalog::v1::Catalog")
        );
    }

    #[test]
    fn two_segment_package_keeps_first_segment_as_module() {
        let p = pkgs(&["demo.v1"]);
        assert_eq!(
            type_rust_path(".demo.v1.Widget", &p).as_deref(),
            Some("super::demo::v1::Widget")
        );
    }

    #[test]
    fn nested_type_lives_in_snake_cased_parent_module() {
        let p = pkgs(&["example.catalog.v1"]);
        // A type defined inside a message is nested under a snake_case module named
        // after the parent message; only the leaf keeps its proto name.
        assert_eq!(
            type_rust_path(".example.catalog.v1.Catalog.Nested", &p).as_deref(),
            Some("super::catalog::v1::catalog::Nested")
        );
    }

    #[test]
    fn deeply_nested_type_snake_cases_every_parent() {
        let p = pkgs(&["example.creds.v1"]);
        assert_eq!(
            type_rust_path(
                ".example.creds.v1.GenerateTableCredentialsRequest.Operation",
                &p
            )
            .as_deref(),
            Some("super::creds::v1::generate_table_credentials_request::Operation")
        );
    }

    #[test]
    fn foreign_package_is_skipped() {
        let p = pkgs(&["example.catalog.v1"]);
        assert_eq!(type_rust_path(".google.protobuf.Any", &p), None);
    }

    #[test]
    fn wrapper_ident_is_py_prefixed_qualified_name() {
        assert_eq!(
            wrapper_ident(".example.catalog.v1.Catalog").to_string(),
            "PyCatalog"
        );
        assert_eq!(
            wrapper_ident(".example.catalog.v1.Catalog.Nested").to_string(),
            "PyCatalogNested"
        );
    }

    // --- boxing detection -------------------------------------------------

    fn msg_field(name: &str, ty: UnifiedType) -> MessageField {
        MessageField {
            name: name.to_string(),
            unified_type: ty,
            documentation: None,
            oneof_variants: None,
            field_behavior: vec![],
            is_sensitive: false,
            resource_reference: None,
        }
    }

    fn singular_message(target: &str) -> UnifiedType {
        UnifiedType {
            base_type: BaseType::Message(target.to_string()),
            is_optional: true,
            is_repeated: false,
        }
    }

    fn repeated_message(target: &str) -> UnifiedType {
        UnifiedType {
            base_type: BaseType::Message(target.to_string()),
            is_optional: false,
            is_repeated: true,
        }
    }

    fn metadata_with(messages: Vec<(&str, Vec<MessageField>)>) -> CodeGenMetadata {
        let mut meta = CodeGenMetadata::default();
        for (name, fields) in messages {
            meta.messages.insert(
                name.to_string(),
                MessageInfo {
                    name: name.to_string(),
                    fields,
                    resource_descriptor: None,
                    documentation: None,
                },
            );
        }
        meta
    }

    #[test]
    fn non_recursive_singular_message_is_not_boxed() {
        // A.f: B, B has no message fields -> no cycle -> unboxed.
        let meta = metadata_with(vec![
            (".pkg.A", vec![msg_field("f", singular_message(".pkg.B"))]),
            (".pkg.B", vec![]),
        ]);
        assert!(boxed_fields(&meta, Runtime::Prost).is_empty());
    }

    #[test]
    fn direct_self_recursion_boxes_the_field() {
        // A.next: A -> cycle -> boxed.
        let meta = metadata_with(vec![(
            ".pkg.A",
            vec![msg_field("next", singular_message(".pkg.A"))],
        )]);
        let boxed = boxed_fields(&meta, Runtime::Prost);
        assert!(boxed.contains(&(".pkg.A".to_string(), "next".to_string())));
        assert_eq!(boxed.len(), 1);
    }

    #[test]
    fn mutual_recursion_boxes_both_back_edges() {
        // A.b: B and B.a: A -> A<->B cycle -> both boxed.
        let meta = metadata_with(vec![
            (".pkg.A", vec![msg_field("b", singular_message(".pkg.B"))]),
            (".pkg.B", vec![msg_field("a", singular_message(".pkg.A"))]),
        ]);
        let boxed = boxed_fields(&meta, Runtime::Prost);
        assert!(boxed.contains(&(".pkg.A".to_string(), "b".to_string())));
        assert!(boxed.contains(&(".pkg.B".to_string(), "a".to_string())));
    }

    #[test]
    fn repeated_field_breaks_the_cycle_and_is_not_boxed() {
        // A.items: repeated A -> Vec breaks the size cycle -> never boxed.
        let meta = metadata_with(vec![(
            ".pkg.A",
            vec![msg_field("items", repeated_message(".pkg.A"))],
        )]);
        assert!(boxed_fields(&meta, Runtime::Prost).is_empty());
    }

    #[test]
    fn buffa_runtime_never_boxes() {
        let meta = metadata_with(vec![(
            ".pkg.A",
            vec![msg_field("next", singular_message(".pkg.A"))],
        )]);
        assert!(boxed_fields(&meta, Runtime::Buffa).is_empty());
    }
}