oxiproto-codegen 0.1.2

Pure Rust protobuf code generator from FileDescriptorSet to Rust structs/enums
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
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
use prost_types::field_descriptor_proto::{Label, Type};
use prost_types::{
    DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto,
    FileDescriptorProto, FileDescriptorSet,
};
use std::collections::BTreeMap;

fn make_field(name: &str, number: i32, r#type: Type, label: Label) -> FieldDescriptorProto {
    FieldDescriptorProto {
        name: Some(name.to_string()),
        number: Some(number),
        label: Some(label as i32),
        r#type: Some(r#type as i32),
        ..Default::default()
    }
}

fn build_test_fds() -> FileDescriptorSet {
    // Message: TestMessage { string name = 1; int64 count = 2; repeated string tags = 3; }
    let msg = DescriptorProto {
        name: Some("TestMessage".to_string()),
        field: vec![
            make_field("name", 1, Type::String, Label::Optional),
            make_field("count", 2, Type::Int64, Label::Optional),
            make_field("tags", 3, Type::String, Label::Repeated),
        ],
        ..Default::default()
    };

    // Enum: Status { UNKNOWN = 0; ACTIVE = 1; INACTIVE = 2; }
    let en = EnumDescriptorProto {
        name: Some("Status".to_string()),
        value: vec![
            EnumValueDescriptorProto {
                name: Some("UNKNOWN".to_string()),
                number: Some(0),
                ..Default::default()
            },
            EnumValueDescriptorProto {
                name: Some("ACTIVE".to_string()),
                number: Some(1),
                ..Default::default()
            },
            EnumValueDescriptorProto {
                name: Some("INACTIVE".to_string()),
                number: Some(2),
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("test.proto".to_string()),
        package: Some("test".to_string()),
        message_type: vec![msg],
        enum_type: vec![en],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn emit_generates_valid_rust() {
    let fds = build_test_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate should succeed");

    // 1. The output parses as valid Rust with syn
    let syntax: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Generated code failed to parse: {e}\n\nCode:\n{code}"));

    // 2. Contains the struct name TestMessage
    let has_struct = syntax.items.iter().any(|item| {
        if let syn::Item::Struct(s) = item {
            s.ident == "TestMessage"
        } else {
            false
        }
    });
    assert!(has_struct, "Expected struct TestMessage in:\n{code}");

    // 3. TestMessage has 3 fields: name (String), count (i64), tags (Vec<String>)
    let test_struct = syntax
        .items
        .iter()
        .find_map(|item| {
            if let syn::Item::Struct(s) = item {
                if s.ident == "TestMessage" {
                    Some(s)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("TestMessage struct");

    let fields: Vec<_> = if let syn::Fields::Named(f) = &test_struct.fields {
        f.named.iter().collect()
    } else {
        panic!("Expected named fields")
    };
    assert_eq!(fields.len(), 3, "Expected 3 fields, got {}", fields.len());

    // 4. Contains the enum Status with 3 variants
    let has_enum = syntax.items.iter().any(|item| {
        if let syn::Item::Enum(e) = item {
            e.ident == "Status"
        } else {
            false
        }
    });
    assert!(has_enum, "Expected enum Status in:\n{code}");

    let status_enum = syntax
        .items
        .iter()
        .find_map(|item| {
            if let syn::Item::Enum(e) = item {
                if e.ident == "Status" {
                    Some(e)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("Status enum");
    assert_eq!(status_enum.variants.len(), 3, "Expected 3 enum variants");

    // 5. Variants have explicit discriminants
    let unknown = status_enum
        .variants
        .iter()
        .find(|v| v.ident == "Unknown")
        .expect("Unknown variant");
    assert!(
        unknown.discriminant.is_some(),
        "Expected explicit discriminant on Unknown"
    );
}

#[test]
fn write_to_file() {
    let fds = build_test_fds();
    let path = std::env::temp_dir().join("oxiproto_codegen_test.rs");
    oxiproto_codegen::generate_to_file(&fds, &path).expect("write_to_file should succeed");
    let content = std::fs::read_to_string(&path).expect("read generated file");
    assert!(
        content.contains("TestMessage"),
        "File should contain TestMessage"
    );
}

/// Build an FDS exercising map fields. The map field references a synthetic
/// nested map entry message named `LabelsEntry` with `map_entry` option set.
fn build_map_fds() -> FileDescriptorSet {
    let map_entry = DescriptorProto {
        name: Some("LabelsEntry".to_string()),
        field: vec![
            make_field("key", 1, Type::String, Label::Optional),
            make_field("value", 2, Type::Int32, Label::Optional),
        ],
        options: Some(prost_types::MessageOptions {
            map_entry: Some(true),
            ..Default::default()
        }),
        ..Default::default()
    };

    let mut map_field = make_field("labels", 1, Type::Message, Label::Repeated);
    map_field.type_name = Some(".test.Container.LabelsEntry".to_string());

    let container = DescriptorProto {
        name: Some("Container".to_string()),
        field: vec![map_field],
        nested_type: vec![map_entry],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("map.proto".to_string()),
        package: Some("test".to_string()),
        message_type: vec![container],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn map_field_generates_hashmap() {
    let fds = build_map_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");

    // Output must parse as valid Rust
    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Generated code failed to parse: {e}\n\nCode:\n{code}"));

    assert!(
        code.contains("HashMap<String, i32>"),
        "expected map<string,int32> -> HashMap<String, i32> in:\n{code}"
    );
    // The synthetic LabelsEntry must NOT be emitted as a struct
    assert!(
        !code.contains("struct Container_LabelsEntry"),
        "map entry type should be inlined, not emitted as a struct:\n{code}"
    );
}

#[test]
fn map_field_with_btree_option() {
    let fds = build_map_fds();
    let options = oxiproto_codegen::CodegenOptions {
        use_btree_map: true,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");
    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("BTreeMap code failed to parse: {e}\n\nCode:\n{code}"));
    assert!(
        code.contains("BTreeMap<String, i32>"),
        "expected BTreeMap with btree option in:\n{code}"
    );
}

/// Build an FDS exercising a oneof group.
fn build_oneof_fds() -> FileDescriptorSet {
    let mut text_field = make_field("text", 1, Type::String, Label::Optional);
    text_field.oneof_index = Some(0);
    let mut number_field = make_field("number", 2, Type::Int32, Label::Optional);
    number_field.oneof_index = Some(0);

    let msg = DescriptorProto {
        name: Some("Payload".to_string()),
        field: vec![text_field, number_field],
        oneof_decl: vec![prost_types::OneofDescriptorProto {
            name: Some("content".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("oneof.proto".to_string()),
        package: Some("test".to_string()),
        message_type: vec![msg],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn oneof_generates_enum() {
    let fds = build_oneof_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");

    let syntax: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("oneof code failed to parse: {e}\n\nCode:\n{code}"));

    // A oneof enum named Payload_Content must exist with 2 variants
    let oneof_enum = syntax.items.iter().find_map(|item| {
        if let syn::Item::Enum(e) = item {
            if e.ident == "Payload_Content" {
                return Some(e);
            }
        }
        None
    });
    let oneof_enum =
        oneof_enum.unwrap_or_else(|| panic!("expected Payload_Content enum in:\n{code}"));
    assert_eq!(oneof_enum.variants.len(), 2, "oneof should have 2 variants");

    // The Payload struct must have a `content: Option<Payload_Content>` field
    assert!(
        code.contains("content: Option<Payload_Content>"),
        "expected oneof field in struct:\n{code}"
    );
}

#[test]
fn enum_has_default_impl() {
    let fds = build_test_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");
    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("code failed to parse: {e}\n\nCode:\n{code}"));

    // Default impl: first variant (Unknown) is the default
    assert!(
        code.contains("impl Default for Status"),
        "expected Default impl for Status enum:\n{code}"
    );
    // from_i32 helper
    assert!(
        code.contains("pub fn from_i32"),
        "expected from_i32 helper:\n{code}"
    );
}

/// With `generate_docs` enabled and `source_code_info` populated, the emitted
/// doc comments must be correctly indented so the output still parses as
/// valid Rust (top-level items have no indent; members get 4 spaces).
#[test]
fn doc_comments_produce_valid_rust() {
    use prost_types::source_code_info::Location;
    use prost_types::SourceCodeInfo;

    let mut fds = build_test_fds();

    // Attach source code info: comment on the top-level message (path [4, 0]),
    // on its first field (path [4, 0, 2, 0]), on the top-level enum (path
    // [5, 0]) and the first enum value (path [5, 0, 2, 0]).
    let file = &mut fds.file[0];
    file.source_code_info = Some(SourceCodeInfo {
        location: vec![
            Location {
                path: vec![4, 0],
                leading_comments: Some(" The primary test message.".to_string()),
                ..Default::default()
            },
            Location {
                path: vec![4, 0, 2, 0],
                leading_comments: Some(" The name of the greeting.".to_string()),
                ..Default::default()
            },
            Location {
                path: vec![5, 0],
                leading_comments: Some(" Lifecycle status.".to_string()),
                ..Default::default()
            },
            Location {
                path: vec![5, 0, 2, 0],
                leading_comments: Some(" Unset / unknown.".to_string()),
                ..Default::default()
            },
        ],
    });

    let options = oxiproto_codegen::CodegenOptions {
        generate_docs: true,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");

    // The whole point of the indent fix: this must still parse.
    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("doc-commented code failed to parse: {e}\n\nCode:\n{code}"));

    // Top-level message comment must be column 0 (no leading spaces).
    assert!(
        code.contains("/// The primary test message."),
        "expected message doc comment:\n{code}"
    );
    // Field comment must be indented 4 spaces inside the struct body.
    assert!(
        code.contains("    /// The name of the greeting."),
        "expected indented field doc comment:\n{code}"
    );
}

// ── New CG-1 tests ────────────────────────────────────────────────────────────

/// Build a 3-level nested FDS for nested-message codegen tests.
fn build_nested_fds() -> FileDescriptorSet {
    let level3 = DescriptorProto {
        name: Some("Level3".to_string()),
        field: vec![make_field("flag", 1, Type::Bool, Label::Optional)],
        ..Default::default()
    };

    let mut level3_field = make_field("inner", 2, Type::Message, Label::Optional);
    level3_field.type_name = Some(".nested.Level1.Level2.Level3".to_string());

    let level2 = DescriptorProto {
        name: Some("Level2".to_string()),
        field: vec![
            make_field("name", 1, Type::String, Label::Optional),
            level3_field,
        ],
        nested_type: vec![level3],
        ..Default::default()
    };

    let mut level2_field = make_field("child", 2, Type::Message, Label::Optional);
    level2_field.type_name = Some(".nested.Level1.Level2".to_string());

    let level1 = DescriptorProto {
        name: Some("Level1".to_string()),
        field: vec![
            make_field("id", 1, Type::Int32, Label::Optional),
            level2_field,
        ],
        nested_type: vec![level2],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("nested.proto".to_string()),
        package: Some("nested".to_string()),
        message_type: vec![level1],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn nested_messages_codegen() {
    let fds = build_nested_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");

    let syntax: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Nested code failed to parse: {e}\n\nCode:\n{code}"));

    // Level1 should exist
    let has_level1 = syntax.items.iter().any(|item| {
        if let syn::Item::Struct(s) = item {
            s.ident == "Level1"
        } else {
            false
        }
    });
    assert!(has_level1, "Expected Level1 struct in:\n{code}");

    // Level1_Level2 should exist (nested struct with prefix)
    let has_level1_level2 = syntax.items.iter().any(|item| {
        if let syn::Item::Struct(s) = item {
            s.ident == "Level1_Level2"
        } else {
            false
        }
    });
    assert!(
        has_level1_level2,
        "Expected Level1_Level2 struct in:\n{code}"
    );

    // Level1_Level2_Level3 should exist
    let has_l3 = syntax.items.iter().any(|item| {
        if let syn::Item::Struct(s) = item {
            s.ident == "Level1_Level2_Level3"
        } else {
            false
        }
    });
    assert!(has_l3, "Expected Level1_Level2_Level3 struct in:\n{code}");
}

/// Build a service FDS with all streaming variants.
fn build_service_fds() -> FileDescriptorSet {
    let req = DescriptorProto {
        name: Some("Req".to_string()),
        field: vec![make_field("text", 1, Type::String, Label::Optional)],
        ..Default::default()
    };
    let resp = DescriptorProto {
        name: Some("Resp".to_string()),
        field: vec![make_field("code", 1, Type::Int32, Label::Optional)],
        ..Default::default()
    };

    let make_method =
        |name: &str, client_stream: bool, server_stream: bool| prost_types::MethodDescriptorProto {
            name: Some(name.to_string()),
            input_type: Some(".svc.Req".to_string()),
            output_type: Some(".svc.Resp".to_string()),
            client_streaming: Some(client_stream),
            server_streaming: Some(server_stream),
            ..Default::default()
        };

    let svc = prost_types::ServiceDescriptorProto {
        name: Some("Echo".to_string()),
        method: vec![
            make_method("Unary", false, false),
            make_method("ServerStream", false, true),
            make_method("ClientStream", true, false),
            make_method("Bidi", true, true),
        ],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("services.proto".to_string()),
        package: Some("svc".to_string()),
        message_type: vec![req, resp],
        service: vec![svc],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn service_trait_codegen() {
    let fds = build_service_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");

    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Service code failed to parse: {e}\n\nCode:\n{code}"));

    // Echo trait should be present
    assert!(
        code.contains("pub trait Echo"),
        "Expected Echo trait in:\n{code}"
    );
    // All four methods
    assert!(
        code.contains("fn unary("),
        "Expected unary method in:\n{code}"
    );
    assert!(
        code.contains("fn server_stream("),
        "Expected server_stream method in:\n{code}"
    );
    assert!(
        code.contains("fn client_stream("),
        "Expected client_stream method in:\n{code}"
    );
    assert!(
        code.contains("fn bidi("),
        "Expected bidi method in:\n{code}"
    );
    // Streaming types
    assert!(
        code.contains("Vec<Resp>"),
        "Expected Vec<Resp> for server streaming in:\n{code}"
    );
    assert!(
        code.contains("Vec<Req>"),
        "Expected Vec<Req> for client streaming in:\n{code}"
    );
}

/// Build an FDS with a google.protobuf.Timestamp field to test WKT mapping.
fn build_wkt_fds() -> FileDescriptorSet {
    let mut ts_field = make_field("created_at", 1, Type::Message, Label::Optional);
    ts_field.type_name = Some(".google.protobuf.Timestamp".to_string());

    let msg = DescriptorProto {
        name: Some("Event".to_string()),
        field: vec![ts_field],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("event.proto".to_string()),
        package: Some("events".to_string()),
        message_type: vec![msg],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn wkt_timestamp_field_mapping() {
    let fds = build_wkt_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");

    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("WKT code failed to parse: {e}\n\nCode:\n{code}"));

    // Should use the WKT path, not Option<Box<Timestamp>>
    assert!(
        code.contains("::oxiproto_wkt::Timestamp"),
        "Expected WKT Timestamp type in:\n{code}"
    );
    assert!(
        !code.contains("Option<Box<Timestamp>>"),
        "WKT field should not be Option<Box<Timestamp>>:\n{code}"
    );
}

/// Test package namespacing: foo.bar package → pub mod foo { pub mod bar { ... } }
#[test]
fn package_namespacing_generates_modules() {
    let fds = build_test_fds(); // package = "test"
    let options = oxiproto_codegen::CodegenOptions {
        package_namespacing: true,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");

    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Namespaced code failed to parse: {e}\n\nCode:\n{code}"));

    assert!(
        code.contains("pub mod test {"),
        "Expected pub mod test in:\n{code}"
    );
}

/// Test that reserved fields are not emitted as struct fields.
/// We construct a descriptor where a field has the same number as a reserved
/// range entry — the codegen must skip it and emit a comment instead.
fn build_reserved_fds() -> FileDescriptorSet {
    use prost_types::descriptor_proto::ReservedRange;

    // Field 2 appears in the reserved_range [2,4), so codegen should skip it
    // and emit "// reserved field 2" instead.
    let msg = DescriptorProto {
        name: Some("WithReserved".to_string()),
        field: vec![
            make_field("active_field", 1, Type::String, Label::Optional),
            // This field has number 2 which falls in the reserved range [2,4)
            make_field("legacy_field", 2, Type::Int32, Label::Optional),
            // This field has the reserved name "old_name"
            make_field("old_name", 5, Type::Bool, Label::Optional),
        ],
        reserved_range: vec![ReservedRange {
            start: Some(2),
            end: Some(4),
        }],
        reserved_name: vec!["old_name".to_string()],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("reserved.proto".to_string()),
        package: Some("test".to_string()),
        message_type: vec![msg],
        ..Default::default()
    };

    FileDescriptorSet { file: vec![file] }
}

#[test]
fn reserved_fields_skipped() {
    let fds = build_reserved_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");

    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Reserved code failed to parse: {e}\n\nCode:\n{code}"));

    // active_field should be present
    assert!(
        code.contains("active_field"),
        "Expected active_field in:\n{code}"
    );
    // The reserved-number field must be replaced by a comment
    assert!(
        !code.contains("pub legacy_field"),
        "legacy_field (reserved number) must not appear as a pub field:\n{code}"
    );
    // The reserved-name field must be replaced by a comment
    assert!(
        !code.contains("pub old_name"),
        "old_name (reserved name) must not appear as a pub field:\n{code}"
    );
    // Reserved comment should appear
    assert!(
        code.contains("// reserved field"),
        "Expected reserved field comment in:\n{code}"
    );
}

/// Test custom type attribute injection.
#[test]
fn custom_type_attribute_injection() {
    let fds = build_test_fds();
    let mut type_attributes = BTreeMap::new();
    type_attributes.insert(
        "test.TestMessage".to_string(),
        vec!["#[derive(serde::Serialize)]".to_string()],
    );
    let options = oxiproto_codegen::CodegenOptions {
        type_attributes,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");

    assert!(
        code.contains("#[derive(serde::Serialize)]"),
        "Expected custom attribute in:\n{code}"
    );
    // Must appear before the struct
    let attr_pos = code
        .find("#[derive(serde::Serialize)]")
        .unwrap_or(usize::MAX);
    let struct_pos = code.find("pub struct TestMessage").unwrap_or(usize::MAX);
    assert!(
        attr_pos < struct_pos,
        "Custom attribute must precede the struct declaration:\n{code}"
    );
}

/// Test custom field attribute injection.
#[test]
fn custom_field_attribute_injection() {
    let fds = build_test_fds();
    let mut field_attributes = BTreeMap::new();
    field_attributes.insert(
        "test.TestMessage.name".to_string(),
        vec!["#[serde(rename = \"n\")]".to_string()],
    );
    let options = oxiproto_codegen::CodegenOptions {
        field_attributes,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");

    assert!(
        code.contains("#[serde(rename = \"n\")]"),
        "Expected custom field attribute in:\n{code}"
    );
}

/// Test deterministic output: same FDS produces identical output on two runs.
#[test]
fn deterministic_output() {
    let fds = build_test_fds();
    let code1 = oxiproto_codegen::generate(&fds).expect("generate 1");
    let code2 = oxiproto_codegen::generate(&fds).expect("generate 2");
    assert_eq!(code1, code2, "Code generation must be deterministic");
}

/// Test that oneof fields work with services in the same FDS.
#[test]
fn oneof_and_service_combined() {
    let fds = build_service_fds();
    let code = oxiproto_codegen::generate(&fds).expect("generate");
    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("Combined code failed to parse: {e}\n\nCode:\n{code}"));
    assert!(code.contains("pub struct Req"), "Expected Req struct");
    assert!(code.contains("pub struct Resp"), "Expected Resp struct");
    assert!(code.contains("pub trait Echo"), "Expected Echo trait");
}

// ── emit_services toggle tests ────────────────────────────────────────────────

/// With `emit_services: true` (default), the service FDS must produce a
/// `pub trait Echo` in the output.
#[test]
fn test_emit_services_default_true() {
    let fds = build_service_fds();
    let options = oxiproto_codegen::CodegenOptions {
        emit_services: true,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");

    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("code failed to parse: {e}\n\nCode:\n{code}"));

    assert!(
        code.contains("pub trait Echo"),
        "emit_services=true must include the Echo service trait in:\n{code}"
    );
}

/// With `emit_services: false`, the service FDS must NOT produce any `pub trait`
/// definition, while message structs remain present.
#[test]
fn test_emit_services_false_suppresses_services() {
    let fds = build_service_fds();
    let options = oxiproto_codegen::CodegenOptions {
        emit_services: false,
        ..Default::default()
    };
    let code = oxiproto_codegen::generate_with_options(&fds, &options).expect("generate");

    let _: syn::File = syn::parse_str(&code)
        .unwrap_or_else(|e| panic!("code failed to parse: {e}\n\nCode:\n{code}"));

    assert!(
        !code.contains("pub trait"),
        "emit_services=false must suppress all service traits in:\n{code}"
    );
    // Message structs must still be present.
    assert!(
        code.contains("pub struct Req"),
        "Req struct must still appear when emit_services=false:\n{code}"
    );
    assert!(
        code.contains("pub struct Resp"),
        "Resp struct must still appear when emit_services=false:\n{code}"
    );
}

// ── TypeRegistry unit tests (via codegenerated output checking) ───────────────

fn assert_valid_rust(code: &str) {
    let _: syn::File = syn::parse_str(code)
        .unwrap_or_else(|e| panic!("code failed to parse: {e}\n\nCode:\n{code}"));
}

fn gen_namespaced(fds: &FileDescriptorSet) -> String {
    let mut opts = oxiproto_codegen::CodegenOptions::new();
    opts.package_namespacing = true;
    opts.emit_json = false;
    oxiproto_codegen::generate_with_options(fds, &opts).expect("codegen should succeed")
}

fn gen_namespaced_json(fds: &FileDescriptorSet) -> String {
    let mut opts = oxiproto_codegen::CodegenOptions::new();
    opts.package_namespacing = true;
    opts.emit_json = true;
    oxiproto_codegen::generate_with_options(fds, &opts).expect("codegen should succeed")
}

fn make_msg_with_field(
    msg_name: &str,
    field_name: &str,
    field_number: i32,
    ftype: Type,
    type_name: Option<&str>,
) -> DescriptorProto {
    DescriptorProto {
        name: Some(msg_name.to_string()),
        field: vec![FieldDescriptorProto {
            name: Some(field_name.to_string()),
            number: Some(field_number),
            label: Some(Label::Optional as i32),
            r#type: Some(ftype as i32),
            type_name: type_name.map(|s| s.to_string()),
            json_name: Some(field_name.to_string()),
            ..Default::default()
        }],
        ..Default::default()
    }
}

/// Namespaced cross-package struct field: message in "foo" with field of type ".bar.B".
/// The generated field type must contain the relative path "super::bar::B".
#[test]
fn namespaced_struct_field_cross_package() {
    // Package "bar" has message B
    let bar_msg = DescriptorProto {
        name: Some("B".to_string()),
        ..Default::default()
    };
    // Package "foo" has message A with a field of type ".bar.B"
    let foo_msg = make_msg_with_field("A", "b_field", 1, Type::Message, Some(".bar.B"));

    let fds = FileDescriptorSet {
        file: vec![
            FileDescriptorProto {
                name: Some("bar.proto".to_string()),
                package: Some("bar".to_string()),
                message_type: vec![bar_msg],
                ..Default::default()
            },
            FileDescriptorProto {
                name: Some("foo.proto".to_string()),
                package: Some("foo".to_string()),
                message_type: vec![foo_msg],
                ..Default::default()
            },
        ],
    };

    let code = gen_namespaced(&fds);
    assert_valid_rust(&code);
    // The field type must use the relative module path, not the bare "B"
    assert!(
        code.contains("super::bar::B"),
        "Expected 'super::bar::B' in generated code:\n{code}"
    );
}

/// Namespaced cross-package enum field: message in "foo" with field of type ".bar.Color".
/// The generated field type must contain the relative path "super::bar::Color".
#[test]
fn namespaced_struct_field_cross_package_enum() {
    let color_enum = EnumDescriptorProto {
        name: Some("Color".to_string()),
        value: vec![EnumValueDescriptorProto {
            name: Some("RED".to_string()),
            number: Some(0),
            ..Default::default()
        }],
        ..Default::default()
    };
    let foo_msg = make_msg_with_field("A", "color", 1, Type::Enum, Some(".bar.Color"));

    let fds = FileDescriptorSet {
        file: vec![
            FileDescriptorProto {
                name: Some("bar.proto".to_string()),
                package: Some("bar".to_string()),
                enum_type: vec![color_enum],
                ..Default::default()
            },
            FileDescriptorProto {
                name: Some("foo.proto".to_string()),
                package: Some("foo".to_string()),
                message_type: vec![foo_msg],
                ..Default::default()
            },
        ],
    };

    let code = gen_namespaced(&fds);
    assert_valid_rust(&code);
    assert!(
        code.contains("super::bar::Color"),
        "Expected 'super::bar::Color' in generated code:\n{code}"
    );
}

/// Same-package struct field reference: no super:: prefix expected.
#[test]
fn namespaced_struct_field_same_package() {
    let b_msg = DescriptorProto {
        name: Some("B".to_string()),
        ..Default::default()
    };
    let a_msg = make_msg_with_field("A", "b_field", 1, Type::Message, Some(".foo.B"));

    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("foo.proto".to_string()),
            package: Some("foo".to_string()),
            message_type: vec![a_msg, b_msg],
            ..Default::default()
        }],
    };

    let code = gen_namespaced(&fds);
    assert_valid_rust(&code);
    // Same package: must NOT have super::foo::B, just B
    assert!(
        code.contains("Option<Box<B>>"),
        "Expected 'Option<Box<B>>' (no super::) in generated code:\n{code}"
    );
}

/// JSON codegen with cross-package type references under package_namespacing.
#[test]
fn namespaced_json_cross_package() {
    // Package "bar" has message B
    let bar_msg = DescriptorProto {
        name: Some("B".to_string()),
        ..Default::default()
    };
    // Package "foo" has message A with a field of type ".bar.B"
    let foo_msg = make_msg_with_field("A", "b_field", 1, Type::Message, Some(".bar.B"));

    let fds = FileDescriptorSet {
        file: vec![
            FileDescriptorProto {
                name: Some("bar.proto".to_string()),
                package: Some("bar".to_string()),
                message_type: vec![bar_msg],
                ..Default::default()
            },
            FileDescriptorProto {
                name: Some("foo.proto".to_string()),
                package: Some("foo".to_string()),
                message_type: vec![foo_msg],
                ..Default::default()
            },
        ],
    };

    let code = gen_namespaced_json(&fds);
    assert_valid_rust(&code);
    // The JSON impl (from_json) must use the relative path
    assert!(
        code.contains("super::bar::B"),
        "Expected 'super::bar::B' in generated JSON code:\n{code}"
    );
    // JSON prelude must be inside the module, not at root
    assert!(
        code.contains("pub mod foo"),
        "Expected 'pub mod foo' in:\n{code}"
    );
    assert!(
        code.contains("pub fn to_json"),
        "Expected 'to_json' in generated code:\n{code}"
    );
    assert!(
        code.contains("pub fn from_json"),
        "Expected 'from_json' in generated code:\n{code}"
    );
}

/// JSON prelude (JsonError) must appear in each package module under namespacing.
#[test]
fn namespaced_json_prelude_per_module() {
    let a_msg = DescriptorProto {
        name: Some("A".to_string()),
        ..Default::default()
    };
    let b_msg = DescriptorProto {
        name: Some("B".to_string()),
        ..Default::default()
    };

    let fds = FileDescriptorSet {
        file: vec![
            FileDescriptorProto {
                name: Some("foo.proto".to_string()),
                package: Some("foo".to_string()),
                message_type: vec![a_msg],
                ..Default::default()
            },
            FileDescriptorProto {
                name: Some("bar.proto".to_string()),
                package: Some("bar".to_string()),
                message_type: vec![b_msg],
                ..Default::default()
            },
        ],
    };

    let code = gen_namespaced_json(&fds);
    assert_valid_rust(&code);
    // Each module should have its own JsonError
    let count = code.matches("pub enum JsonError").count();
    assert!(
        count >= 2,
        "Expected JsonError defined in each package module, found only {count} occurrence(s):\n{code}"
    );
}

/// Flat layout JSON codegen regression guard: flat output still works correctly.
#[test]
fn flat_layout_json_unchanged() {
    let msg = DescriptorProto {
        name: Some("Item".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("name".to_string()),
            number: Some(1),
            label: Some(Label::Optional as i32),
            r#type: Some(Type::String as i32),
            json_name: Some("name".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };

    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("flat.proto".to_string()),
            package: Some("".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let mut opts = oxiproto_codegen::CodegenOptions::new();
    opts.emit_json = true;
    opts.package_namespacing = false;
    let code =
        oxiproto_codegen::generate_with_options(&fds, &opts).expect("codegen should succeed");

    assert_valid_rust(&code);
    // Flat layout must still produce to_json, from_json, and JsonError at root level
    assert!(
        code.contains("pub fn to_json"),
        "Expected 'to_json' in flat layout:\n{code}"
    );
    assert!(
        code.contains("pub fn from_json"),
        "Expected 'from_json' in flat layout:\n{code}"
    );
    assert!(
        code.contains("pub enum JsonError"),
        "Expected 'JsonError' in flat layout:\n{code}"
    );
    // No module wrapping
    assert!(
        !code.contains("pub mod"),
        "Expected no pub mod in flat layout:\n{code}"
    );
}

mod module_tree_tests {
    use super::*;

    fn simple_fds(pkg: &str, msg_name: &str) -> FileDescriptorSet {
        FileDescriptorSet {
            file: vec![FileDescriptorProto {
                name: Some(format!("{}.proto", msg_name.to_lowercase())),
                package: if pkg.is_empty() {
                    None
                } else {
                    Some(pkg.to_string())
                },
                syntax: Some("proto3".to_string()),
                message_type: vec![DescriptorProto {
                    name: Some(msg_name.to_string()),
                    field: vec![FieldDescriptorProto {
                        name: Some("value".to_string()),
                        number: Some(1),
                        r#type: Some(Type::Int32 as i32),
                        label: Some(Label::Optional as i32),
                        json_name: Some("value".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                }],
                ..Default::default()
            }],
        }
    }

    #[test]
    fn generate_module_flat_layout() {
        // Single file, no package → root node with items, no children
        let fds = simple_fds("", "FlatMsg");
        let tree =
            oxiproto_codegen::generate_module(&fds, &oxiproto_codegen::CodegenOptions::new())
                .expect("generate_module must succeed");
        assert!(tree.name.is_empty(), "root must have empty name");
        assert!(!tree.items.is_empty(), "root must have items");
        assert!(tree.children.is_empty(), "no children for no-package");
    }

    #[test]
    fn generate_module_single_package() {
        // package "foo" → root has one child named "foo"
        let fds = simple_fds("foo", "FooMsg");
        let tree =
            oxiproto_codegen::generate_module(&fds, &oxiproto_codegen::CodegenOptions::new())
                .expect("generate_module");
        assert_eq!(tree.children.len(), 1);
        assert_eq!(tree.children[0].name, "foo");
        assert!(!tree.children[0].items.is_empty());
    }

    #[test]
    fn generate_module_nested_package() {
        // package "foo.bar" → root→foo→bar
        let fds = simple_fds("foo.bar", "BarMsg");
        let tree =
            oxiproto_codegen::generate_module(&fds, &oxiproto_codegen::CodegenOptions::new())
                .expect("generate_module");
        assert_eq!(tree.children.len(), 1, "root has one child: foo");
        assert_eq!(tree.children[0].name, "foo");
        assert_eq!(tree.children[0].children.len(), 1, "foo has one child: bar");
        assert_eq!(tree.children[0].children[0].name, "bar");
        assert!(!tree.children[0].children[0].items.is_empty());
    }

    #[test]
    fn generate_module_sibling_packages() {
        // Two files in "foo" and "bar" → root has two children
        let fds = FileDescriptorSet {
            file: vec![
                FileDescriptorProto {
                    name: Some("foo.proto".to_string()),
                    package: Some("foo".to_string()),
                    syntax: Some("proto3".to_string()),
                    message_type: vec![DescriptorProto {
                        name: Some("FooMsg".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                FileDescriptorProto {
                    name: Some("bar.proto".to_string()),
                    package: Some("bar".to_string()),
                    syntax: Some("proto3".to_string()),
                    message_type: vec![DescriptorProto {
                        name: Some("BarMsg".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
            ],
        };
        let tree =
            oxiproto_codegen::generate_module(&fds, &oxiproto_codegen::CodegenOptions::new())
                .expect("generate_module");
        let child_names: Vec<&str> = tree.children.iter().map(|c| c.name.as_str()).collect();
        assert!(child_names.contains(&"foo"), "must have foo child");
        assert!(child_names.contains(&"bar"), "must have bar child");
    }

    #[test]
    fn generate_module_multi_file_same_package() {
        // Two files in same package "pkg" → items kept as separate entries
        let fds = FileDescriptorSet {
            file: vec![
                FileDescriptorProto {
                    name: Some("a.proto".to_string()),
                    package: Some("pkg".to_string()),
                    syntax: Some("proto3".to_string()),
                    message_type: vec![DescriptorProto {
                        name: Some("MsgA".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                FileDescriptorProto {
                    name: Some("b.proto".to_string()),
                    package: Some("pkg".to_string()),
                    syntax: Some("proto3".to_string()),
                    message_type: vec![DescriptorProto {
                        name: Some("MsgB".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
            ],
        };
        let tree =
            oxiproto_codegen::generate_module(&fds, &oxiproto_codegen::CodegenOptions::new())
                .expect("generate_module");
        let pkg_node = tree
            .children
            .iter()
            .find(|c| c.name == "pkg")
            .expect("pkg node");
        assert_eq!(pkg_node.items.len(), 2, "two files → two items in pkg node");
    }

    #[test]
    fn generate_module_render_valid_rust() {
        // render() must produce syn-parseable Rust
        let fds = simple_fds("mypkg", "MyMsg");
        let tree =
            oxiproto_codegen::generate_module(&fds, &oxiproto_codegen::CodegenOptions::new())
                .expect("generate_module");
        let code = tree.render();
        assert_valid_rust(&code);
    }

    #[test]
    fn generate_module_is_additive() {
        // generate_with_options still works correctly after adding generate_module
        let fds = simple_fds("mypkg", "AnotherMsg");
        let opts = oxiproto_codegen::CodegenOptions::new();
        let code = oxiproto_codegen::generate_with_options(&fds, &opts)
            .expect("generate_with_options must still work");
        assert!(
            code.contains("AnotherMsg"),
            "generate_with_options regression: {code}"
        );
    }
}

// ─── Builder-pattern generation tests ─────────────────────────────────────────

mod builder_tests {
    use prost_types::field_descriptor_proto::{Label, Type};
    use prost_types::{
        DescriptorProto, FieldDescriptorProto, FileDescriptorProto, FileDescriptorSet,
    };

    fn make_field(name: &str, number: i32, r#type: Type, label: Label) -> FieldDescriptorProto {
        FieldDescriptorProto {
            name: Some(name.to_string()),
            number: Some(number),
            label: Some(label as i32),
            r#type: Some(r#type as i32),
            ..Default::default()
        }
    }

    /// Build an FDS for `Foo` with scalar, repeated, singular-message and map fields.
    ///
    /// ```proto
    /// message Foo {
    ///     int32 count       = 1;
    ///     string label      = 2;
    ///     repeated int32 tags = 3;
    ///     // map<string, int32> attrs = 4  (synthetic nested map entry)
    ///     // (singular message field omitted intentionally — syn-checks are syntax-only)
    /// }
    /// ```
    fn build_builder_fds() -> FileDescriptorSet {
        // Synthetic map entry for attrs: map<string, int32>
        let map_entry = DescriptorProto {
            name: Some("AttrsEntry".to_string()),
            field: vec![
                make_field("key", 1, Type::String, Label::Optional),
                make_field("value", 2, Type::Int32, Label::Optional),
            ],
            options: Some(prost_types::MessageOptions {
                map_entry: Some(true),
                ..Default::default()
            }),
            ..Default::default()
        };

        let mut map_field = make_field("attrs", 4, Type::Message, Label::Repeated);
        map_field.type_name = Some(".test.Foo.AttrsEntry".to_string());

        let msg = DescriptorProto {
            name: Some("Foo".to_string()),
            field: vec![
                make_field("count", 1, Type::Int32, Label::Optional),
                make_field("label", 2, Type::String, Label::Optional),
                make_field("tags", 3, Type::Int32, Label::Repeated),
                map_field,
            ],
            nested_type: vec![map_entry],
            ..Default::default()
        };

        let file = FileDescriptorProto {
            name: Some("builder.proto".to_string()),
            package: Some("test".to_string()),
            message_type: vec![msg],
            ..Default::default()
        };

        FileDescriptorSet { file: vec![file] }
    }

    fn builder_options() -> oxiproto_codegen::CodegenOptions {
        oxiproto_codegen::CodegenOptions {
            emit_builder: true,
            ..Default::default()
        }
    }

    /// `FooBuilder` struct and `impl FooBuilder` must appear in the output.
    #[test]
    fn builder_generates_struct() {
        let fds = build_builder_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &builder_options())
            .expect("generate_with_options");
        assert!(
            code.contains("FooBuilder"),
            "expected FooBuilder in output:\n{code}"
        );
        assert!(
            code.contains("impl FooBuilder"),
            "expected impl FooBuilder in output:\n{code}"
        );
    }

    /// The `build()` method must be present and return `Foo`.
    #[test]
    fn builder_has_build_method() {
        let fds = build_builder_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &builder_options())
            .expect("generate_with_options");
        assert!(
            code.contains("pub fn build(self) -> Foo"),
            "expected build() -> Foo in output:\n{code}"
        );
    }

    /// A scalar setter for `count` must appear.
    #[test]
    fn builder_has_scalar_setter() {
        let fds = build_builder_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &builder_options())
            .expect("generate_with_options");
        assert!(
            code.contains("pub fn count"),
            "expected scalar setter 'count' in output:\n{code}"
        );
    }

    /// With default options, `FooBuilder` must NOT appear.
    #[test]
    fn builder_disabled_by_default() {
        let fds = build_builder_fds();
        let code = oxiproto_codegen::generate(&fds).expect("generate");
        assert!(
            !code.contains("FooBuilder"),
            "FooBuilder should not appear when emit_builder is false:\n{code}"
        );
    }

    /// The generated code (struct + builder) must be syntactically valid Rust.
    #[test]
    fn builder_output_compiles() {
        let fds = build_builder_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &builder_options())
            .expect("generate_with_options");

        // Wrap in a module so the generated use-std import and HashMap are in scope.
        let wrapped = format!("use std::collections::HashMap;\n{code}");
        let _: syn::File = syn::parse_str(&wrapped)
            .unwrap_or_else(|e| panic!("Builder code failed to parse: {e}\n\nCode:\n{wrapped}"));
    }
}

// ─── Text-format generation tests ─────────────────────────────────────────────

mod text_format_tests {
    use oxiproto_codegen::CodegenOptions;
    use prost_types::field_descriptor_proto::{Label, Type};
    use prost_types::{
        DescriptorProto, FieldDescriptorProto, FileDescriptorProto, FileDescriptorSet,
    };

    fn make_field(name: &str, number: i32, r#type: Type, label: Label) -> FieldDescriptorProto {
        FieldDescriptorProto {
            name: Some(name.to_string()),
            number: Some(number),
            label: Some(label as i32),
            r#type: Some(r#type as i32),
            ..Default::default()
        }
    }

    /// Build an FDS with a simple message that has a string field and an int field.
    fn build_simple_fds() -> FileDescriptorSet {
        let msg = DescriptorProto {
            name: Some("Greet".to_string()),
            field: vec![
                make_field("name", 1, Type::String, Label::Optional),
                make_field("value", 2, Type::Int32, Label::Optional),
            ],
            ..Default::default()
        };
        FileDescriptorSet {
            file: vec![FileDescriptorProto {
                name: Some("greet.proto".to_string()),
                package: Some("test".to_string()),
                message_type: vec![msg],
                ..Default::default()
            }],
        }
    }

    /// Build options with emit_text_format = true.
    fn text_format_options() -> CodegenOptions {
        CodegenOptions {
            emit_text_format: true,
            ..CodegenOptions::new()
        }
    }

    /// With `emit_text_format = true`, the output contains `pub fn to_text_format`.
    #[test]
    fn text_format_generates_method() {
        let fds = build_simple_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &text_format_options())
            .expect("generate_with_options");
        assert!(
            code.contains("pub fn to_text_format"),
            "Expected 'pub fn to_text_format' in generated code:\n{code}"
        );
    }

    /// Without the flag (default false), the output must NOT contain `to_text_format`.
    #[test]
    fn text_format_disabled_by_default() {
        let fds = build_simple_fds();
        let code = oxiproto_codegen::generate(&fds).expect("generate");
        assert!(
            !code.contains("to_text_format"),
            "to_text_format must not appear when emit_text_format is false:\n{code}"
        );
    }

    /// A string field (`name`) should produce a pattern referencing the field name.
    #[test]
    fn text_format_has_string_field() {
        let fds = build_simple_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &text_format_options())
            .expect("generate_with_options");
        // The emitter guards on !self.name.is_empty() and uses "name:" literal
        assert!(
            code.contains("self.name"),
            "Expected reference to 'self.name' in text_format impl:\n{code}"
        );
        // The field name literal must appear in the format string
        assert!(
            code.contains("\"name:"),
            "Expected 'name:' literal in text_format impl:\n{code}"
        );
    }

    /// A message field generates an inner `to_text_format()` call.
    #[test]
    fn text_format_nested_message_field() {
        // Build: message Inner {} message Outer { Inner inner = 1; }
        let inner_msg = DescriptorProto {
            name: Some("Inner".to_string()),
            ..Default::default()
        };
        let mut msg_field = make_field("inner", 1, Type::Message, Label::Optional);
        msg_field.type_name = Some(".test.Inner".to_string());
        let outer_msg = DescriptorProto {
            name: Some("Outer".to_string()),
            field: vec![msg_field],
            ..Default::default()
        };
        let fds = FileDescriptorSet {
            file: vec![FileDescriptorProto {
                name: Some("nested.proto".to_string()),
                package: Some("test".to_string()),
                message_type: vec![inner_msg, outer_msg],
                ..Default::default()
            }],
        };
        let code = oxiproto_codegen::generate_with_options(&fds, &text_format_options())
            .expect("generate_with_options");
        // The outer message impl should call inner.to_text_format()
        assert!(
            code.contains("to_text_format"),
            "Expected 'to_text_format' in nested message impl:\n{code}"
        );
        assert!(
            code.contains("_inner"),
            "Expected '_inner' variable in nested message impl:\n{code}"
        );
    }

    /// The generated code (struct + to_text_format impl) must be syntactically valid Rust.
    #[test]
    fn text_format_output_compiles() {
        let fds = build_simple_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &text_format_options())
            .expect("generate_with_options");
        let _: syn::File = syn::parse_str(&code)
            .unwrap_or_else(|e| panic!("text_format code failed to parse: {e}\n\nCode:\n{code}"));
    }

    /// Build an FDS exercising oneof, map, enum, repeated, and bool fields to
    /// validate that all emitter branches produce syntactically valid Rust.
    fn build_complex_fds() -> FileDescriptorSet {
        // Synthetic enum to be used as a field type
        let status_enum = prost_types::EnumDescriptorProto {
            name: Some("Status".to_string()),
            value: vec![
                prost_types::EnumValueDescriptorProto {
                    name: Some("UNKNOWN".to_string()),
                    number: Some(0),
                    ..Default::default()
                },
                prost_types::EnumValueDescriptorProto {
                    name: Some("ACTIVE".to_string()),
                    number: Some(1),
                    ..Default::default()
                },
            ],
            ..Default::default()
        };

        // Synthetic map entry: map<string, int32>
        let map_entry = DescriptorProto {
            name: Some("TagsEntry".to_string()),
            field: vec![
                make_field("key", 1, Type::String, Label::Optional),
                make_field("value", 2, Type::Int32, Label::Optional),
            ],
            options: Some(prost_types::MessageOptions {
                map_entry: Some(true),
                ..Default::default()
            }),
            ..Default::default()
        };

        let mut map_field = make_field("tags", 5, Type::Message, Label::Repeated);
        map_field.type_name = Some(".test.Complex.TagsEntry".to_string());

        // Oneof fields
        let mut oneof_str = make_field("text", 1, Type::String, Label::Optional);
        oneof_str.oneof_index = Some(0);
        let mut oneof_num = make_field("number", 2, Type::Int32, Label::Optional);
        oneof_num.oneof_index = Some(0);

        // Enum field (singular)
        let mut enum_field = make_field("status", 3, Type::Enum, Label::Optional);
        enum_field.type_name = Some(".test.Status".to_string());

        // Repeated scalar
        let repeated_field = make_field("scores", 4, Type::Int64, Label::Repeated);

        // Bool field
        let bool_field = make_field("active", 6, Type::Bool, Label::Optional);

        // Repeated bool
        let repeated_bool = make_field("flags", 7, Type::Bool, Label::Repeated);

        let msg = DescriptorProto {
            name: Some("Complex".to_string()),
            field: vec![
                oneof_str,
                oneof_num,
                enum_field,
                repeated_field,
                map_field,
                bool_field,
                repeated_bool,
            ],
            oneof_decl: vec![prost_types::OneofDescriptorProto {
                name: Some("payload".to_string()),
                ..Default::default()
            }],
            nested_type: vec![map_entry],
            ..Default::default()
        };

        FileDescriptorSet {
            file: vec![FileDescriptorProto {
                name: Some("complex.proto".to_string()),
                package: Some("test".to_string()),
                message_type: vec![msg],
                enum_type: vec![status_enum],
                ..Default::default()
            }],
        }
    }

    /// The generated code for a message with oneof, map, enum, repeated, and
    /// bool fields must be syntactically valid Rust.
    #[test]
    fn text_format_complex_message_compiles() {
        let fds = build_complex_fds();
        let code = oxiproto_codegen::generate_with_options(&fds, &text_format_options())
            .expect("generate_with_options");
        // Wrap with the map import that the generated code needs.
        let wrapped = format!("use std::collections::HashMap;\n{code}");
        let _: syn::File = syn::parse_str(&wrapped).unwrap_or_else(|e| {
            panic!("Complex text_format code failed to parse: {e}\n\nCode:\n{wrapped}")
        });
        assert!(
            code.contains("pub fn to_text_format"),
            "Complex message must have to_text_format:\n{code}"
        );
        // Oneof match arm must reference the generated enum
        assert!(
            code.contains("Complex_Payload"),
            "Expected 'Complex_Payload' oneof enum reference:\n{code}"
        );
        // Map must iterate sorted keys
        assert!(
            code.contains("_keys.sort()"),
            "Expected sorted map iteration:\n{code}"
        );
    }
}