crozier 0.0.126

Ultra-fast OpenAPI-to-SDK code generator that matches Fern's output, byte for byte.
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
//! Name transforms shared by the IR builder and the emitter.
//!
//! Byte-exact output depends on these matching Fern's choices: `snake_case` field
//! and module names, `PascalCase` class names, and appending `_` to a name that
//! collides with a Python keyword or a reserved builtin (Fern then preserves the
//! original wire name as an alias). The reserved set is deliberately explicit so
//! a future mismatch is a one-line change here.

/// Split an identifier into lowercase words, handling `camelCase`, `PascalCase`,
/// `snake_case`, `kebab-case`, and `ACRONYMCase` boundaries.
#[must_use]
pub fn split_words(input: &str) -> Vec<String> {
    let mut words: Vec<String> = Vec::new();
    let mut current = String::new();
    let chars: Vec<char> = input.chars().collect();

    for idx in 0..chars.len() {
        let c = chars[idx];
        // `/` and `+` separate words the way `_`, `-`, ` ` and `.` do, so a
        // media-type-shaped discriminant value (oSPARC maps `schema_class:
        // application/schema+json` onto a `oneOf` member) names the variant
        // class `ApplicationSchemaJson` rather than sanitizing the punctuation
        // into underscores. A `:` does too: OpenLink OSDB's namespaced body
        // property `osdb:output_type` hoists Fern's `ExecBodyOsdbOutputType`.
        if c == '_' || c == '-' || c == ' ' || c == '.' || c == '/' || c == '+' || c == ':' {
            if !current.is_empty() {
                words.push(std::mem::take(&mut current));
            }
            continue;
        }

        let prev = if idx > 0 { Some(chars[idx - 1]) } else { None };
        let next = chars.get(idx + 1).copied();

        // Boundary before an uppercase letter that begins a new word:
        //  - lower/digit -> Upper  (fooBar -> foo|Bar)
        //  - Upper -> Upper followed by lower  (HTTPServer -> HTTP|Server)
        let boundary = c.is_ascii_uppercase()
            && !current.is_empty()
            && (prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
                || (prev.is_some_and(|p| p.is_ascii_uppercase())
                    && next.is_some_and(|n| n.is_ascii_lowercase())));

        if boundary {
            words.push(std::mem::take(&mut current));
        }
        current.push(c.to_ascii_lowercase());
    }
    if !current.is_empty() {
        words.push(current);
    }
    words
}

/// `snake_case` of an identifier. A word that follows one ending in a digit *and*
/// containing a letter (`Cvc2`) is joined without an underscore, matching Fern's
/// module/method names (`CardGeneratedCvc2Create` → `card_generated_cvc2create`,
/// `GeneratedCvc2_for` → `generated_cvc2for`). This join is snake-only — the class
/// name (`to_pascal_case`) keeps `Cvc2Create`. A standalone digit word (`2`, from
/// `2Factor`) does not absorb the next word.
#[must_use]
pub fn to_snake_case(input: &str) -> String {
    let mut out = String::new();
    for word in split_words(input) {
        let after_digit_word = out.ends_with(|p: char| p.is_ascii_digit())
            && out.rsplit('_').next().is_some_and(|w| {
                w.ends_with(|p: char| p.is_ascii_digit())
                    && w.chars().any(|c| c.is_ascii_alphabetic())
            });
        // A word that *opens* with a digit and carries a letter (`2fa`) joins the
        // word before it the same way, so oSPARC's `login_2fa` operation becomes
        // `login2fa` and its `resend_2fa_code` becomes `resend2fa_code`. A
        // standalone digit word (`2`, from `2Factor`) is not one of these and
        // keeps its separator.
        let digit_led_word = word.starts_with(|p: char| p.is_ascii_digit())
            && word.chars().any(|c| c.is_ascii_alphabetic());
        if !out.is_empty() && !after_digit_word && !digit_led_word {
            out.push('_');
        }
        out.push_str(&word);
    }
    out
}

/// Convert free-form prose to a legal snake-case Python identifier. Unlike
/// [`to_snake_case`], this treats every punctuation run as a word boundary, so an
/// operation summary such as `The /content endpoint` becomes
/// `the_content_endpoint` rather than retaining the slash.
#[must_use]
pub fn prose_identifier(input: &str) -> String {
    let folded: String = input
        .chars()
        .filter_map(|c| match c {
            // Possessives are contractions, not word boundaries: Fern derives
            // `seller's feedback` as `sellers_feedback`.
            '\'' | '\u{2019}' => None,
            c if c.is_ascii_alphanumeric() => Some(c),
            _ => Some(' '),
        })
        .collect();
    sanitize_identifier(&collapse_digit_boundaries(&to_snake_case(&folded)))
}

/// The identifier Fern derives from an operation **summary**, which is
/// [`prose_identifier`] with full stops deleted rather than treated as word
/// boundaries. Sentence punctuation is not a word break on this path: corpus row
/// 123's `… CertificateOrKeyId e.g. revoke reason` names the method
/// `…_certificate_or_key_id_eg_revoke_reason`, not `…_e_g_revoke_reason`. Every
/// other separator still breaks — the same corpus derives `read/unread` as
/// `read_unread` and `re-enabled` as `re_enabled` — and the URL path Fern falls
/// back to when there is no summary keeps the full stop as a boundary
/// (`/_proxy/openapi.json` → `get_proxy_openapi_json`), which is why this is a
/// separate transform rather than a change to [`prose_identifier`].
///
/// Fern camel-cases the summary before snake-casing it, so consecutive
/// one-letter words after the first join as one capital run: MockServer's
/// `load a gRPC proto descriptor set` is `loadAGRpc…`, re-split as
/// `load_ag_rpc_…`, while `retrieve gRPC …` keeps `retrieve_g_rpc_…`.
#[must_use]
pub fn summary_identifier(input: &str) -> String {
    let snake = prose_identifier(&input.replace('.', ""));
    let is_letter = |word: &str| word.len() == 1 && word.chars().all(|c| c.is_ascii_alphabetic());
    let mut words: Vec<String> = Vec::new();
    let mut previous_letter = false;
    for (index, word) in snake.split('_').enumerate() {
        let letter = is_letter(word);
        match words.last_mut() {
            Some(last) if index > 1 && letter && previous_letter => last.push_str(word),
            _ => words.push(word.to_string()),
        }
        previous_letter = letter;
    }
    words.join("_")
}

/// `PascalCase` of an identifier.
#[must_use]
pub fn to_pascal_case(input: &str) -> String {
    split_words(input)
        .into_iter()
        .map(|w| {
            let mut out = String::with_capacity(w.len());
            let mut after_digit = false;
            for (index, c) in w.chars().enumerate() {
                if index == 0 || after_digit && c.is_ascii_alphabetic() {
                    out.push(c.to_ascii_uppercase());
                } else {
                    out.push(c);
                }
                after_digit = c.is_ascii_digit();
            }
            out
        })
        .collect()
}

/// The class name for a named schema.
#[must_use]
pub fn class_name(schema_key: &str) -> String {
    // Every character that cannot appear in an identifier breaks a word, the way
    // Fern's casing reads a name: NextGen's component
    // `{{baseUrl}}/persons/:personId-Request` is `BaseUrlPersonsPersonIdRequest`.
    let words: String = schema_key
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '_' {
                c
            } else {
                ' '
            }
        })
        .collect();
    let pascal =
        to_pascal_case(&numeric_enum_identifier(schema_key).unwrap_or_else(|| words.clone()));
    let expanded = pascal
        .chars()
        .next()
        .and_then(|digit| digit.to_digit(10))
        .map_or(pascal.clone(), |digit| {
            let word = [
                "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
            ][digit as usize];
            format!("{word}{}", &pascal[1..])
        });
    sanitize_identifier(&expanded)
}

/// The class segment a *parameter* name contributes to a hoisted type
/// (`{RequestCtx}{Param}`). Identical to [`class_name`] except that punctuation
/// leading the wire name is dropped rather than sanitized into an underscore:
/// Google's discovery-derived documents declare the query parameter `$.xgafv`,
/// and Fern names its hoisted enum `…RequestXgafv`, not `…Request_Xgafv`. The
/// dot is already a word separator; the `$` is the character this drops.
#[must_use]
pub fn param_class_name(param: &str) -> String {
    class_name(param.trim_start_matches(|c: char| !c.is_ascii_alphanumeric() && c != '_'))
}

/// Join a parent class name and a child segment the way Fern's namer does: the
/// concatenation is re-cased as one identifier, so a parent ending in a capital
/// absorbs a single-letter segment into one word — the `e` property of
/// `…EncPublicKeyE` names `…EncPublicKeyEe`, not `…EncPublicKeyEE`.
#[must_use]
pub fn child_class_name(parent: &str, segment: &str) -> String {
    to_pascal_case(&format!("{parent}{}", class_name(segment)))
}

/// The module (file stem) name for a generated type.
#[must_use]
pub fn module_name(class_name: &str) -> String {
    let name = to_snake_case(class_name);
    if name.starts_with(|c: char| c.is_ascii_digit()) {
        format!("_{name}")
    } else if is_reserved(&name) {
        format!("{name}_")
    } else {
        name
    }
}

/// The Python field identifier for a wire property name: `snake_case`, with a
/// trailing `_` appended when it would collide with a reserved word, or an `f_`
/// prefix when it would otherwise start with a digit (an illegal identifier).
/// Both transforms make [`crate::ir::Field::needs_alias`] fire, so the wire name
/// is preserved as a `FieldMetadata` alias — matching Fern (`2fa_enabled` →
/// `f_2fa_enabled`).
///
/// Property names that aren't valid identifiers — the bracketed JSON:API / Rails
/// / Stripe convention (`filter[name]`, `page[size]`) most of all — are folded
/// into the `snake_case` the same way Fern does: every non-alphanumeric run is a
/// word boundary, so `filter[name]` → `filter_name` (issue #74). The raw wire
/// name still rides along as the serialization key, since `needs_alias` fires.
#[must_use]
pub fn field_name(wire_name: &str) -> String {
    let snake = field_snake_case(wire_name);
    if snake.starts_with(|c: char| c.is_ascii_digit()) {
        format!("f_{snake}")
    } else if is_reserved(&snake) {
        format!("{snake}_")
    } else {
        snake
    }
}

/// Python argument name for an inlined request-body property. Fern prefixes a
/// digit-leading body argument with `_` (distinct from model fields' `f_`).
#[must_use]
pub fn request_field_name(wire_name: &str) -> String {
    let snake = field_snake_case(wire_name);
    if snake.starts_with(|c: char| c.is_ascii_digit()) {
        format!("_{snake}")
    } else {
        field_name(wire_name)
    }
}

/// The `snake_case` stem shared by [`field_name`] and [`request_field_name`].
///
/// A whitespace run is a *hard* word boundary in Fern's property casing: the
/// digit-boundary collapse below joins segments freely inside one whitespace-
/// delimited chunk (`user_fields[1]` → `user_fields1`, `PF 17,5%` → `pf_175`)
/// but never reaches across a space, so `EAN 1` stays `ean_1` and `PF 17% ALC`
/// stays `pf_17_alc`. Chunking first is what keeps the two apart; every name
/// without whitespace is a single chunk and folds exactly as before.
fn field_snake_case(wire_name: &str) -> String {
    wire_name
        .split_whitespace()
        .map(|chunk| collapse_field_digit_boundaries(&to_snake_case(&fold_non_identifier(chunk))))
        .filter(|chunk| !chunk.is_empty())
        .collect::<Vec<String>>()
        .join("_")
}

/// Fern joins numeric field-name segments to their neighbors (`day_0_end_time` →
/// `day0end_time`, `user_fields[1]` → `user_fields1`) but preserves a boundary
/// after an initial digit (`2Factor` → `2_factor`). Serialization still uses the
/// original wire name through field aliases.
fn collapse_field_digit_boundaries(name: &str) -> String {
    let chars: Vec<char> = name.chars().collect();
    chars
        .iter()
        .enumerate()
        .filter_map(|(index, &ch)| {
            if ch == '_'
                && (index.checked_sub(1).is_some_and(|i| {
                    chars[i].is_ascii_digit() && digit_suffix_absorbs_following(&chars, i)
                }) || chars.get(index + 1).is_some_and(char::is_ascii_digit))
            {
                None
            } else {
                Some(ch)
            }
        })
        .collect()
}

fn digit_suffix_absorbs_following(chars: &[char], digit_index: usize) -> bool {
    let mut digit_start = digit_index;
    while digit_start > 0 && chars[digit_start - 1].is_ascii_digit() {
        digit_start -= 1;
    }
    (digit_start > 0 && chars[digit_start - 1] == '_')
        || chars[..digit_start]
            .iter()
            .rev()
            .take_while(|&&candidate| candidate != '_')
            .any(|candidate| candidate.is_ascii_alphabetic())
}

fn collapse_digit_boundaries(name: &str) -> String {
    let chars: Vec<char> = name.chars().collect();
    chars
        .iter()
        .enumerate()
        .filter_map(|(index, &ch)| {
            if ch == '_'
                && (index
                    .checked_sub(1)
                    .is_some_and(|i| chars[i].is_ascii_digit())
                    || chars.get(index + 1).is_some_and(char::is_ascii_digit))
            {
                None
            } else {
                Some(ch)
            }
        })
        .collect()
}

/// Replace every character that can't appear in a Python identifier with a space
/// so [`split_words`] treats it as a word boundary. `_`, `-`, `.`, and space are
/// already boundaries there, so a name that was already identifier-legal folds to
/// the exact same words — this only changes names that would otherwise emit
/// illegal Python (`filter[name]` → `filter name`).
fn fold_non_identifier(name: &str) -> String {
    name.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' })
        .collect()
}

/// Coerce a derived name into a legal Python identifier: any character that is
/// not `[A-Za-z0-9_]` becomes `_`, and a leading digit is prefixed with `_`.
/// Applied to operationId-derived module/method names so a hyphen or space in an
/// `operationId` (`get-all-widgets`, `verify code`) yields valid Python rather
/// than source that fails to parse. Names already valid pass through unchanged,
/// so this never perturbs the byte-matched fixtures.
#[must_use]
pub fn sanitize_identifier(name: &str) -> String {
    let mut out: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if out.starts_with(|c: char| c.is_ascii_digit()) {
        out.insert(0, '_');
    }
    out
}

/// The English word for a bare single decimal digit. Fern's enum-name generator
/// spells out a one-character digit word so a leading digit becomes a legal
/// identifier (`0: Active` → `zero_active`); a multi-digit run (`01`) is left
/// alone (Fern rejects the result, crozier keeps it legal via the prefix in
/// [`finalize_enum_ident`]).
fn digit_word(word: &str) -> Option<&'static str> {
    let mut chars = word.chars();
    let (first, rest) = (chars.next()?, chars.next());
    if rest.is_some() {
        return None;
    }
    Some(match first {
        '0' => "zero",
        '1' => "one",
        '2' => "two",
        '3' => "three",
        '4' => "four",
        '5' => "five",
        '6' => "six",
        '7' => "seven",
        '8' => "eight",
        '9' => "nine",
        _ => return None,
    })
}

/// The words Fern's enum-name derivation (`WJe`) gives a value that is one of
/// its mapped symbols *whole*, or `None` for any other value.
fn whole_value_enum_words(value: &str) -> Option<&'static str> {
    Some(match value {
        "<" => "less_than",
        ">" => "greater_than",
        ">=" => "greater_than_or_equal_to",
        "<=" => "less_than_or_equal_to",
        "!=" => "not_equals",
        "=" | "==" => "equal_to",
        "*" => "all",
        "\"\"" => "empty_string",
        "-" => "hyphen",
        "|" => "pipe",
        "." => "dot",
        "/" => "slash",
        _ if value.eq_ignore_ascii_case("n/a") => "not_applicable",
        _ => return None,
    })
}

/// Smart-case an enum wire value into Fern's identifier: every non-alphanumeric
/// run separates, `camelCase`/`PascalCase` boundaries split, a leading canonical
/// number is spelled out (`1200 bps` → `one_thousand_two_hundred_bps`), and word
/// boundaries touching a numeric token collapse (`DB-25` → `db25`). UUID-shaped
/// values use Fern's separate quirk in [`uuid_enum_identifier`].
fn enum_words(value: &str) -> String {
    if value.is_empty() {
        return "empty".to_string();
    }
    // A value that is one of these symbols *whole* is spelled out, by the map in
    // Fern's enum-name derivation (`WJe`): Prisma Cloud's `UIFilterModel.operator`
    // holds the single value `=`, and Fern names its member `EQUAL_TO`; apideck's
    // `*` event type is `ALL`. Inside a longer value a symbol is a word boundary
    // like any other, so Tally's `image/*` is `IMAGE`.
    if let Some(words) = whole_value_enum_words(value) {
        return words.to_string();
    }
    // A value that is a number *whole* is spelled as that number, its leading
    // zeros read away: Adyen's `challengeIndicator` values `01`…`09` are `ONE` …
    // `NINE` in its golden. A zero-led run that only leads a longer value names a
    // member Fern refuses (see below).
    if value.len() > 1 && value.starts_with('0') && value.bytes().all(|byte| byte.is_ascii_digit())
    {
        let number = value.trim_start_matches('0');
        if let Some(words) = numeric_enum_identifier(if number.is_empty() { "0" } else { number }) {
            return words;
        }
    }
    let mut spaced = String::new();
    for c in value.chars() {
        if c == '\'' || c == '\u{2019}' {
            // An apostrophe is a contraction rather than a word boundary here,
            // exactly as in [`prose_identifier`]: DaniWeb's `"Don't Know"` names
            // the member `DONT_KNOW`, not `DON_T_KNOW`.
        } else if c.is_ascii_alphanumeric() {
            spaced.push(c);
        } else {
            spaced.push(' ');
        }
    }
    let mut words = split_words(&spaced);
    // Fern spells the value's own leading digit run (`VFt`): `parseFloat` reads
    // its leading zeros away, and past 9,999 its speller returns `undefined`,
    // which the template `${words}_${rest}` writes literally — People Data Labs'
    // `10001+` is the member `UNDEFINED`.
    let value_leads_with_digit = value.starts_with(|c: char| c.is_ascii_digit());
    // Whether the member *name* leads with a zero-led digit run: the value's
    // first word is one and the value does not start with it, so nothing below
    // spells it. Fern refuses such a name (`_01_00_AM` would lead with a digit),
    // and crozier's legal fallback keeps it as written. A run the value starts
    // with is spelled, so that name leads with a word: `01_00_AM` is `ONE00AM`.
    let leads_with_zero_led_digits = !value_leads_with_digit
        && value.contains('_')
        && words.first().is_some_and(|word| {
            word.len() > 1
                && word.starts_with('0')
                && word.bytes().all(|byte| byte.is_ascii_digit())
        });
    if let Some(first) = words.first_mut() {
        let digits = first.bytes().take_while(u8::is_ascii_digit).count();
        if digits > 0 {
            let suffix = first[digits..].to_string();
            let run = &first[..digits];
            let number = if value_leads_with_digit {
                let significant = run.trim_start_matches('0');
                numeric_enum_identifier(if significant.is_empty() {
                    "0"
                } else {
                    significant
                })
                .or_else(|| (value.len() > digits).then(|| "undefined".to_string()))
            } else {
                numeric_enum_identifier(run)
            };
            if let Some(number) = number {
                *first = if suffix.is_empty() {
                    number
                } else {
                    format!("{number}_{suffix}")
                };
            }
        }
    }
    // Consecutive single letters join: Fern names a member
    // `upperFirst(camelCase(value))` (`WJe`) and the IR re-splits that name with
    // lodash's `words`, which reads a run of capitals as one word — People Data
    // Labs' `u.s. virgin islands` is `USVirginIslands`, so `US_VIRGIN_ISLANDS`,
    // as `P+N+E` and `E/F` already were.
    let mut merged_words: Vec<String> = Vec::with_capacity(words.len());
    let mut single_letter_run = false;
    for word in words {
        let is_single_letter =
            word.len() == 1 && word.bytes().all(|byte| byte.is_ascii_alphabetic());
        if is_single_letter && single_letter_run {
            merged_words
                .last_mut()
                .expect("a single-letter run has a previous word")
                .push_str(&word);
        } else {
            merged_words.push(word);
        }
        single_letter_run = is_single_letter;
    }
    let mut words = merged_words;
    let mut index = 1usize;
    while index < words.len() {
        let previous = &words[index - 1];
        let current = &words[index];
        let current_is_short_letter_run =
            current.len() <= 2 && current.bytes().all(|byte| byte.is_ascii_alphabetic());
        let previous_is_numeric_letter =
            previous
                .as_bytes()
                .split_last()
                .is_some_and(|(last, prefix)| {
                    last.is_ascii_alphabetic()
                        && !prefix.is_empty()
                        && prefix.iter().all(u8::is_ascii_digit)
                });
        let previous_is_single_letter =
            previous.len() == 1 && previous.bytes().all(|byte| byte.is_ascii_alphabetic());
        let current_is_letter_digits =
            current
                .as_bytes()
                .split_first()
                .is_some_and(|(first, rest)| {
                    first.is_ascii_alphabetic()
                        && !rest.is_empty()
                        && rest.iter().all(u8::is_ascii_digit)
                });
        if current_is_short_letter_run && previous_is_numeric_letter
            || previous_is_single_letter && current_is_letter_digits
        {
            let current = words.remove(index);
            words[index - 1].push_str(&current);
        } else {
            index += 1;
        }
    }
    let identifier = words.join("_");
    if leads_with_zero_led_digits {
        identifier
    } else {
        // Anywhere later, a zero-led digit run collapses onto the word before
        // it like any other: Google Cloud Monitoring's `ALIGN_PERCENTILE_05` is
        // `ALIGN_PERCENTILE05` in Fern's golden, as `_99` is `ALIGN_PERCENTILE99`.
        collapse_digit_boundaries(&identifier)
    }
}

fn enum_identifier(value: &str) -> String {
    let value = &deburr(value);
    if is_uuid(value) {
        uuid_enum_identifier(value)
    } else {
        enum_words(value)
    }
}

/// Fold Latin accents to their base ASCII letters, the way Fern's enum-name
/// casing does. This is the half of Fern's naming asymmetry that *keeps* the
/// letter: the same accented word yields the member `SUBSTANCIA` from
/// `SUBSTÂNCIA` while the property path drops the accent as a separator
/// (`subst_ncia`), which is why only this path deburrs. Golden-confirmed for
/// `Â`, `Ã`, `Ç`, `Ê`, `É` and `Ó` (`med-anvisa-price`); the rest of the table
/// is the rest of Latin-1 Supplement and Latin Extended-A, folded consistently
/// so a neighbouring accent cannot behave differently from a measured one.
fn deburr(value: &str) -> String {
    let mut folded = String::with_capacity(value.len());
    for character in value.chars() {
        match deburr_letter(character) {
            Some(ascii) => folded.push_str(ascii),
            None => folded.push(character),
        }
    }
    folded
}

/// The ASCII spelling of one accented Latin letter, or `None` when the character
/// is outside the folded range.
fn deburr_letter(character: char) -> Option<&'static str> {
    DEBURRED_LATIN
        .binary_search_by(|(candidate, _)| candidate.cmp(&character))
        .ok()
        .map(|index| DEBURRED_LATIN[index].1)
}

/// Latin-1 Supplement and Latin Extended-A letters paired with the ASCII they
/// fold to, sorted by code point so [`deburr_letter`] can binary-search it.
/// `the_latin_folding_table_is_sorted_and_spans_both_blocks` pins both invariants.
const DEBURRED_LATIN: &[(char, &str)] = &[
    ('À', "A"),
    ('Á', "A"),
    ('Â', "A"),
    ('Ã', "A"),
    ('Ä', "A"),
    ('Å', "A"),
    ('Æ', "Ae"),
    ('Ç', "C"),
    ('È', "E"),
    ('É', "E"),
    ('Ê', "E"),
    ('Ë', "E"),
    ('Ì', "I"),
    ('Í', "I"),
    ('Î', "I"),
    ('Ï', "I"),
    ('Ð', "D"),
    ('Ñ', "N"),
    ('Ò', "O"),
    ('Ó', "O"),
    ('Ô', "O"),
    ('Õ', "O"),
    ('Ö', "O"),
    ('Ø', "O"),
    ('Ù', "U"),
    ('Ú', "U"),
    ('Û', "U"),
    ('Ü', "U"),
    ('Ý', "Y"),
    ('Þ', "Th"),
    ('ß', "ss"),
    ('à', "a"),
    ('á', "a"),
    ('â', "a"),
    ('ã', "a"),
    ('ä', "a"),
    ('å', "a"),
    ('æ', "ae"),
    ('ç', "c"),
    ('è', "e"),
    ('é', "e"),
    ('ê', "e"),
    ('ë', "e"),
    ('ì', "i"),
    ('í', "i"),
    ('î', "i"),
    ('ï', "i"),
    ('ð', "d"),
    ('ñ', "n"),
    ('ò', "o"),
    ('ó', "o"),
    ('ô', "o"),
    ('õ', "o"),
    ('ö', "o"),
    ('ø', "o"),
    ('ù', "u"),
    ('ú', "u"),
    ('û', "u"),
    ('ü', "u"),
    ('ý', "y"),
    ('þ', "th"),
    ('ÿ', "y"),
    ('Ā', "A"),
    ('ā', "a"),
    ('Ă', "A"),
    ('ă', "a"),
    ('Ą', "A"),
    ('ą', "a"),
    ('Ć', "C"),
    ('ć', "c"),
    ('Ĉ', "C"),
    ('ĉ', "c"),
    ('Ċ', "C"),
    ('ċ', "c"),
    ('Č', "C"),
    ('č', "c"),
    ('Ď', "D"),
    ('ď', "d"),
    ('Đ', "D"),
    ('đ', "d"),
    ('Ē', "E"),
    ('ē', "e"),
    ('Ĕ', "E"),
    ('ĕ', "e"),
    ('Ė', "E"),
    ('ė', "e"),
    ('Ę', "E"),
    ('ę', "e"),
    ('Ě', "E"),
    ('ě', "e"),
    ('Ĝ', "G"),
    ('ĝ', "g"),
    ('Ğ', "G"),
    ('ğ', "g"),
    ('Ġ', "G"),
    ('ġ', "g"),
    ('Ģ', "G"),
    ('ģ', "g"),
    ('Ĥ', "H"),
    ('ĥ', "h"),
    ('Ħ', "H"),
    ('ħ', "h"),
    ('Ĩ', "I"),
    ('ĩ', "i"),
    ('Ī', "I"),
    ('ī', "i"),
    ('Ĭ', "I"),
    ('ĭ', "i"),
    ('Į', "I"),
    ('į', "i"),
    ('İ', "I"),
    ('ı', "i"),
    ('IJ', "IJ"),
    ('ij', "ij"),
    ('Ĵ', "J"),
    ('ĵ', "j"),
    ('Ķ', "K"),
    ('ķ', "k"),
    ('ĸ', "k"),
    ('Ĺ', "L"),
    ('ĺ', "l"),
    ('Ļ', "L"),
    ('ļ', "l"),
    ('Ľ', "L"),
    ('ľ', "l"),
    ('Ŀ', "L"),
    ('ŀ', "l"),
    ('Ł', "L"),
    ('ł', "l"),
    ('Ń', "N"),
    ('ń', "n"),
    ('Ņ', "N"),
    ('ņ', "n"),
    ('Ň', "N"),
    ('ň', "n"),
    ('ʼn', "'n"),
    ('Ŋ', "N"),
    ('ŋ', "n"),
    ('Ō', "O"),
    ('ō', "o"),
    ('Ŏ', "O"),
    ('ŏ', "o"),
    ('Ő', "O"),
    ('ő', "o"),
    ('Œ', "Oe"),
    ('œ', "oe"),
    ('Ŕ', "R"),
    ('ŕ', "r"),
    ('Ŗ', "R"),
    ('ŗ', "r"),
    ('Ř', "R"),
    ('ř', "r"),
    ('Ś', "S"),
    ('ś', "s"),
    ('Ŝ', "S"),
    ('ŝ', "s"),
    ('Ş', "S"),
    ('ş', "s"),
    ('Š', "S"),
    ('š', "s"),
    ('Ţ', "T"),
    ('ţ', "t"),
    ('Ť', "T"),
    ('ť', "t"),
    ('Ŧ', "T"),
    ('ŧ', "t"),
    ('Ũ', "U"),
    ('ũ', "u"),
    ('Ū', "U"),
    ('ū', "u"),
    ('Ŭ', "U"),
    ('ŭ', "u"),
    ('Ů', "U"),
    ('ů', "u"),
    ('Ű', "U"),
    ('ű', "u"),
    ('Ų', "U"),
    ('ų', "u"),
    ('Ŵ', "W"),
    ('ŵ', "w"),
    ('Ŷ', "Y"),
    ('ŷ', "y"),
    ('Ÿ', "Y"),
    ('Ź', "Z"),
    ('ź', "z"),
    ('Ż', "Z"),
    ('ż', "z"),
    ('Ž', "Z"),
    ('ž', "z"),
    ('ſ', "s"),
];

/// Fern spells a canonical, entirely numeric enum value as English words. This
/// The same spelling is applied to a leading numeric run in an alphanumeric value
/// (`100base` → `one_hundred_base`).
fn numeric_enum_identifier(value: &str) -> Option<String> {
    if value.is_empty()
        || (value.len() > 1 && value.starts_with('0'))
        || !value.bytes().all(|byte| byte.is_ascii_digit())
    {
        return None;
    }
    let value: u16 = value.parse().ok()?;
    if value > 9_999 {
        return None;
    }

    const SMALL: [&str; 20] = [
        "zero",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen",
    ];
    const TENS: [&str; 10] = [
        "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
    ];

    fn below_hundred(value: u16) -> String {
        if value < 20 {
            return SMALL[usize::from(value)].to_string();
        }
        let mut words = TENS[usize::from(value / 10)].to_string();
        if !value.is_multiple_of(10) {
            words.push('_');
            words.push_str(SMALL[usize::from(value % 10)]);
        }
        words
    }

    fn below_thousand(value: u16) -> String {
        if value < 100 {
            return below_hundred(value);
        }
        let mut words = format!("{}_hundred", SMALL[usize::from(value / 100)]);
        if !value.is_multiple_of(100) {
            words.push('_');
            words.push_str(&below_hundred(value % 100));
        }
        words
    }

    if value < 1_000 {
        return Some(below_thousand(value));
    }
    let mut words = format!("{}_thousand", SMALL[usize::from(value / 1_000)]);
    if !value.is_multiple_of(1_000) {
        words.push('_');
        words.push_str(&below_thousand(value % 1_000));
    }
    Some(words)
}

fn is_uuid(value: &str) -> bool {
    let parts: Vec<&str> = value.split('-').collect();
    parts.len() == 5
        && parts.iter().zip([8, 4, 4, 4, 12]).all(|(part, len)| {
            part.len() == len && part.bytes().all(|byte| byte.is_ascii_hexdigit())
        })
}

/// Fern's smart-casing path handles UUID-shaped enum values differently from
/// ordinary digit-leading values: a leading digit is wordified, longer numeric
/// prefixes use its literal `undefined` fallback, and digit-adjacent separators
/// collapse. Keep this scoped to canonical UUIDs so Crozier's established legal
/// fallback for enums Fern rejects (`_01_00_AM`) remains intact.
fn uuid_enum_identifier(value: &str) -> String {
    let mut words = split_words(value);
    if let Some(first) = words.first_mut() {
        let digit_len = first.bytes().take_while(u8::is_ascii_digit).count();
        if digit_len > 0 {
            let suffix = first[digit_len..].to_string();
            let numeric = &first[..digit_len];
            *first = digit_word(numeric).unwrap_or("undefined").to_string();
            if !suffix.is_empty() {
                words.insert(1, suffix);
            }
        }
    }
    let collapsed = collapse_digit_boundaries(&words.join("_"));
    let chars: Vec<char> = collapsed.chars().collect();
    chars
        .iter()
        .enumerate()
        .filter_map(|(index, &ch)| {
            // Fern's smart casing also joins single-letter fragments bracketed by
            // numeric runs (`466d-b0` -> `466db0`) after digit-boundary folding.
            let numeric_single_letter_bridge = ch == '_'
                && index >= 2
                && index + 2 < chars.len()
                && chars[index - 2].is_ascii_digit()
                && chars[index - 1].is_ascii_alphabetic()
                && chars[index + 1].is_ascii_alphabetic()
                && chars[index + 2].is_ascii_digit();
            (!numeric_single_letter_bridge).then_some(ch)
        })
        .collect()
}

/// Coerce a cased enum identifier into a legal, non-empty Python name: a value
/// with no usable characters falls back to `_`, a leading digit (a multi-digit
/// token Fern would reject) is prefixed with `_`, and a reserved word gets the
/// trailing-`_` `safe_name` treatment Fern applies. Shared by the member and
/// `visit`-parameter derivations so both stay valid and mutually consistent.
fn finalize_enum_ident(mut name: String) -> String {
    if name.is_empty() {
        name.push('_');
    }
    if name.starts_with(|c: char| c.is_ascii_digit()) {
        name.insert(0, '_');
    }
    if is_reserved(&name) {
        name.push('_');
    }
    name
}

/// The `SCREAMING_SNAKE` member identifier for an enum wire value, sanitized to
/// a legal Python name (Fern's `screaming_snake_case.safe_name`): `global` →
/// `GLOBAL`, `0: Active` → `ZERO_ACTIVE`.
#[must_use]
pub fn enum_member_name(value: &str) -> String {
    finalize_enum_ident(enum_identifier(value).to_ascii_uppercase())
}

/// The `snake_case` `visit` callback parameter for an enum wire value, sanitized
/// to a legal Python name (Fern's `snake_case.safe_name`): `global` → `global_`
/// (keyword), `0: Active` → `zero_active`. The method receiver `self` is escaped
/// the same way (issue #57): the `visit(self, …)` signature would otherwise emit a
/// duplicate `self` argument — grammatically valid Python that passes `ruff format`
/// but fails at import — so a value sanitizing to `self` gets the trailing `_`
/// (`self` → `self_`). `cls` is deliberately *not* escaped: `visit` is an ordinary
/// instance method, so a `cls` parameter is legal and does not shadow the receiver
/// — Fern leaves it alone, and matching Fern is the contract. `kwargs` is escaped
/// too (`kwargs_`), as LangChain's agent-server `select` enum measures; Fern
/// leaves every other pydantic-model name (`json`, `copy`, `schema`, …) alone here.
#[must_use]
pub fn enum_visit_param(value: &str) -> String {
    let mut name = finalize_enum_ident(enum_identifier(value));
    if name == "self" || name == "kwargs" {
        name.push('_');
    }
    name
}

/// Names Fern suffixes with `_` (keeping the wire name as an alias): Python hard
/// keywords (syntactically un-usable as identifiers) plus the specific builtins
/// observed in Fern's output. `complex` is one: a `Complex` schema's module is
/// `complex_.py` and a `complex` property is `complex_`, while a measured
/// generation over some eighty other builtin and stdlib names (`str`, `range`,
/// `dict`, `type`, `id`, …) leaves every one of those modules unsuffixed. The
/// builtin set is deliberately evidence-based —
/// only names confirmed by a measured generation belong here, since over-munging a
/// name Fern leaves alone would break the byte-for-byte match. Expand it as new
/// measurements confirm more.
#[must_use]
pub fn is_reserved(name: &str) -> bool {
    // Builtins/module names Fern munges in *field/type* contexts.
    // Method names are narrower — see `is_reserved_method`.
    const RESERVED_BUILTINS: &[&str] = &[
        "all", "bool", "complex", "float", "int", "list", "long", "map", "set", "uuid",
    ];
    PYTHON_KEYWORDS.contains(&name) || RESERVED_BUILTINS.contains(&name)
}

/// A Python field identifier for a pydantic model. In addition to ordinary
/// Python collisions, Fern protects names exposed by pydantic's model API —
/// `copy` among them, which is `BaseModel.copy()`: SFTPGo's
/// `EventActionFilesystemConfig.copy` is `copy_` under an `alias="copy"` in its
/// golden, and embedpdf-cloudpdf's `PdfFieldActions.validate` (`BaseModel.validate()`)
/// is `validate_`, and MockServer's `json` bodies (`BaseModel.json()`) are
/// `json_`, and `construct` (`BaseModel.construct()`) is `construct_`, measured
/// on the authored probe `376-354-model-property-construct`. The protection
/// is *model-scoped*, so an enum visitor's `copy` argument (otoroshi's
/// `PatchItemOp`, komga's `BookImportBatchDtoCopyMode`) keeps its spelling.
#[must_use]
pub fn model_field_name(wire_name: &str) -> String {
    let name = field_name(wire_name);
    if matches!(
        name.as_str(),
        "construct" | "copy" | "json" | "kwargs" | "schema" | "self" | "validate"
    ) {
        format!("{name}_")
    } else {
        name
    }
}

/// Reserved-word check for *derived method* names, tagged or not. Fern safe-names
/// every name [`is_reserved`] holds except `list` and `set`: an operation `all`,
/// `bool`, `complex`, `float`, `int`, `long`, `map` or `uuid` is that name with a
/// trailing `_`, while appwrite's derived `list` stays `list` and an untagged
/// operation `set` stays `set`. Evidence-based against the golden corpus and
/// measured generations; widen only when a measured generation shows Fern
/// suffixing another method name.
#[must_use]
pub fn is_reserved_method(name: &str) -> bool {
    is_reserved(name) && !matches!(name, "list" | "set")
}

/// Apply Python's mandatory keyword escaping without treating ordinary builtins
/// as reserved. Method derivation uses this as a final validity boundary after
/// its context-specific Fern naming rules have run.
#[must_use]
pub fn escape_python_keyword(mut name: String) -> String {
    if PYTHON_KEYWORDS.contains(&name.as_str()) {
        name.push('_');
    }
    name
}

/// Whether `name` is a Python hard keyword, the part of [`is_reserved`] Fern
/// escapes even inside a prefixed collision name.
#[must_use]
pub fn is_python_keyword(name: &str) -> bool {
    PYTHON_KEYWORDS.contains(&name)
}

/// Python hard keywords — reserved in every naming context.
const PYTHON_KEYWORDS: &[&str] = &[
    "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
    "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
    "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
    "with", "yield",
];

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

    #[test]
    fn method_reserved_set_is_narrower_than_general() {
        // Fern safe-names `all` and keywords as method names (apideck's `all_`,
        // `import_`) but leaves `list` and `set` alone (appwrite's `list`).
        assert!(is_reserved_method("all"));
        assert!(is_reserved_method("import"));
        assert!(is_reserved_method("bool"));
        assert!(!is_reserved_method("list"));
        assert!(!is_reserved_method("set"));
        assert!(!is_reserved_method("dict"));
        // The general set still guards field/type names, so `list`/`bool`
        // stay reserved there.
        assert!(is_reserved("list"));
        assert!(is_reserved("bool"));
        assert!(is_reserved("all"));
    }

    #[test]
    fn complex_is_reserved_in_every_naming_context() {
        // Fern writes a `Complex` schema to `complex_.py`, a `complex` property
        // and argument as `complex_`, and an operation `complex` as `complex_`.
        assert_eq!(module_name("Complex"), "complex_");
        assert_eq!(field_name("complex"), "complex_");
        assert!(is_reserved_method("complex"));
        // The adjacent builtins Fern leaves alone stay unsuffixed.
        for name in ["str", "range", "dict", "type", "id", "object", "format"] {
            assert_eq!(module_name(&to_pascal_case(name)), name);
            assert_eq!(field_name(name), name);
            assert!(!is_reserved_method(name));
        }
    }

    #[test]
    fn method_keyword_escape_leaves_builtins_unchanged() {
        assert_eq!(escape_python_keyword("del".to_string()), "del_");
        assert_eq!(escape_python_keyword("list".to_string()), "list");
        assert_eq!(escape_python_keyword("all".to_string()), "all");
    }

    #[test]
    fn snake_case_variants() {
        assert_eq!(to_snake_case("ParcelNotice"), "parcel_notice");
        assert_eq!(to_snake_case("SearchResponse"), "search_response");
        assert_eq!(to_snake_case("name"), "name");
        assert_eq!(to_snake_case("customFields"), "custom_fields");
        assert_eq!(to_snake_case("custom_fields"), "custom_fields");
        assert_eq!(to_snake_case("HTTPServer"), "http_server");
        assert_eq!(to_snake_case("kebab-case-name"), "kebab_case_name");
    }

    #[test]
    fn pascal_case_is_idempotent_on_pascal() {
        assert_eq!(to_pascal_case("ParcelNotice"), "ParcelNotice");
        assert_eq!(to_pascal_case("parcel_notice"), "ParcelNotice");
        assert_eq!(to_pascal_case("search_response"), "SearchResponse");
    }

    #[test]
    fn module_name_snakes_class() {
        assert_eq!(module_name("ParcelNotice"), "parcel_notice");
        assert_eq!(module_name("Class"), "class_");
        assert_eq!(module_name("_5GmmCause"), "_5_gmm_cause");
    }

    #[test]
    fn a_colon_separates_the_words_of_a_class_name() {
        // OpenLink OSDB's namespaced body property, hoisted under `ExecBody`.
        assert_eq!(class_name("osdb:output_type"), "OsdbOutputType");
        assert_eq!(
            split_words("osdb:output_type"),
            vec!["osdb", "output", "type"]
        );
    }

    #[test]
    fn digit_leading_schema_names_get_legal_class_names() {
        assert_eq!(class_name("5GmmCause"), "FiveGmmCause");
        assert_eq!(class_name("Widget"), "Widget");
        assert_eq!(class_name("400"), "FourHundred");
        assert_eq!(class_name("422"), "FourHundredTwentyTwo");
    }

    #[test]
    fn reserved_fields_get_suffixed() {
        assert_eq!(field_name("list"), "list_");
        assert_eq!(field_name("bool"), "bool_");
        assert_eq!(field_name("uuid"), "uuid_");
        assert_eq!(field_name("name"), "name");
        assert_eq!(field_name("tags"), "tags");
        assert_eq!(model_field_name("self"), "self_");
        assert_eq!(model_field_name("construct"), "construct_");
        assert_eq!(field_name("construct"), "construct");
    }

    #[test]
    fn bracketed_property_names_fold_to_snake_identifiers() {
        // Issue #74: JSON:API / Rails / Stripe bracketed params aren't valid
        // Python identifiers; Fern folds them to snake_case and keeps the raw
        // name as the wire key (which `needs_alias` handles).
        assert_eq!(field_name("filter[name]"), "filter_name");
        assert_eq!(field_name("filter[color]"), "filter_color");
        assert_eq!(field_name("page[size]"), "page_size");
        assert_eq!(field_name("hours[day]"), "hours_day");
        // Deeper nesting collapses each bracket run to a single boundary; no
        // trailing underscore from the closing bracket.
        assert_eq!(field_name("filter[user][name]"), "filter_user_name");
        // A leading-digit result still gets the `f_` guard after folding.
        assert_eq!(field_name("[2fa]enabled"), "f_2fa_enabled");
    }

    #[test]
    fn digit_leading_fields_get_f_prefix() {
        // Fern renames a leading-digit property to `f_<name>` and aliases it.
        assert_eq!(field_name("2fa_enabled"), "f_2fa_enabled");
        assert_eq!(field_name("3d"), "f_3d");
        // Fern's default smart casing rejoins digit-adjacent fragments before
        // applying the leading-digit prefix.
        assert_eq!(field_name("2-factor"), "f_2_factor");
        // Non-digit-leading names are untouched.
        assert_eq!(field_name("v2"), "v2");
    }

    #[test]
    fn numeric_field_boundaries_match_fern_without_changing_adjacent_word_rules() {
        assert_eq!(field_name("address_line_1"), "address_line1");
        assert_eq!(field_name("Cvc2Create"), "cvc2create");
        assert_eq!(field_name("prop65_warning"), "prop65warning");
        assert_eq!(field_name("prop_65_warning"), "prop65warning");
        assert_eq!(field_name("2Factor"), "f_2_factor");
    }

    #[test]
    fn whitespace_is_a_hard_boundary_for_field_digit_collapse() {
        // Measured on `med-anvisa-price`: inside one whitespace-delimited chunk
        // the digit boundaries collapse exactly as they always have, but a space
        // between a word and a digit survives into the identifier.
        assert_eq!(field_name("EAN 1"), "ean_1");
        assert_eq!(field_name("PF 0%"), "pf_0");
        assert_eq!(field_name("CONFAZ 87"), "confaz_87");
        assert_eq!(field_name("PF 17% ALC"), "pf_17_alc");
        assert_eq!(field_name("PF 17,5%"), "pf_175");
        assert_eq!(field_name("PF 17,5% ALC"), "pf_175_alc");
        // A chunk of pure punctuation contributes no segment at all.
        assert_eq!(field_name("PF 17 % ALC"), "pf_17_alc");
        assert_eq!(field_name("   "), "");
        // Non-ASCII letters remain separators on this path — Fern does not fold
        // them here, unlike the enum path.
        assert_eq!(field_name("SUBSTÂNCIA"), "subst_ncia");
        assert_eq!(field_name("COMERCIALIZAÇÃO 2019"), "comercializa_o_2019");
        assert_eq!(
            field_name("LISTA DE CONCESSÃO DE CRÉDITO TRIBUTÁRIO (PIS/COFINS)"),
            "lista_de_concess_o_de_cr_dito_tribut_rio_pis_cofins"
        );
        // Chunking leaves every whitespace-free name exactly where it was.
        assert_eq!(field_name("day_0_end_time"), "day0end_time");
        assert_eq!(field_name("user_fields[1]"), "user_fields1");
        assert_eq!(request_field_name("user_fields[1]"), "user_fields1");
        assert_eq!(request_field_name("EAN 1"), "ean_1");
    }

    #[test]
    fn enum_member_names_fold_latin_accents_the_property_path_drops() {
        // The two halves of Fern's asymmetry over one `med-anvisa-price` word.
        assert_eq!(enum_member_name("SUBSTÂNCIA"), "SUBSTANCIA");
        assert_eq!(field_name("SUBSTÂNCIA"), "subst_ncia");
        assert_eq!(enum_member_name("LABORATÓRIO"), "LABORATORIO");
        assert_eq!(enum_member_name("CÓDIGO GGREM"), "CODIGO_GGREM");
        assert_eq!(enum_member_name("APRESENTAÇÃO"), "APRESENTACAO");
        assert_eq!(enum_member_name("CLASSE TERAPÊUTICA"), "CLASSE_TERAPEUTICA");
        assert_eq!(enum_member_name("REGIME DE PREÇO"), "REGIME_DE_PRECO");
        assert_eq!(
            enum_member_name("COMERCIALIZAÇÃO 2019"),
            "COMERCIALIZACAO2019"
        );
        assert_eq!(enum_visit_param("ANÁLISE RECURSAL"), "analise_recursal");
    }

    #[test]
    fn the_latin_folding_table_is_sorted_and_spans_both_blocks() {
        assert!(
            DEBURRED_LATIN.windows(2).all(|pair| pair[0].0 < pair[1].0),
            "DEBURRED_LATIN must stay sorted for the binary search in deburr_letter"
        );
        assert!(
            DEBURRED_LATIN
                .iter()
                .all(|(accented, ascii)| !accented.is_ascii() && ascii.is_ascii()),
            "every entry folds one non-ASCII letter to an ASCII spelling"
        );
        // Latin-1 Supplement and Latin Extended-A, including the multi-letter and
        // unmapped-neighbour cases.
        assert_eq!(deburr_letter('Ä'), Some("A"));
        assert_eq!(deburr_letter('ß'), Some("ss"));
        assert_eq!(deburr_letter('Æ'), Some("Ae"));
        assert_eq!(deburr_letter('ʼn'), Some("'n"));
        assert_eq!(deburr_letter('ž'), Some("z"));
        assert_eq!(deburr_letter('×'), None);
        assert_eq!(deburr_letter('a'), None);
        assert_eq!(deburr_letter('気'), None);
        // Unmapped characters ride through untouched, so a CJK enum value keeps
        // reaching the existing separator fold rather than silently changing.
        assert_eq!(deburr("Ærøskøbing 気温"), "Aeroskobing 気温");
        assert_eq!(enum_member_name("気温"), "_");
    }

    #[test]
    fn digit_leading_request_fields_get_underscore_prefix() {
        assert_eq!(request_field_name("5gMmCauseValue"), "_5g_mm_cause_value");
    }

    #[test]
    fn zero_led_digit_runs_collapse_unless_they_lead_the_name() {
        // Google Cloud Monitoring v1's aligners (corpus row 225's golden).
        assert_eq!(
            enum_member_name("ALIGN_PERCENTILE_05"),
            "ALIGN_PERCENTILE05"
        );
        assert_eq!(
            enum_member_name("ALIGN_PERCENTILE_99"),
            "ALIGN_PERCENTILE99"
        );
        assert_eq!(
            enum_visit_param("ALIGN_PERCENTILE_05"),
            "align_percentile05"
        );
        // Fern refuses a name led by one; crozier keeps it as written.
        assert_eq!(enum_member_name("_01_00_AM"), "_01_00_AM");
        // A value that *starts* with the run has it spelled, so nothing is left
        // leading and the rest collapses: Fern 5.20.0 named `01_00_AM`'s member
        // `ONE00AM` (the `enum-leading-zero-member-refused-control` probe,
        // not re-measured at the certified pair).
        assert_eq!(enum_member_name("01_00_AM"), "ONE00AM");
        assert_eq!(enum_visit_param("01_00_AM"), "one00am");
        // A zero-led value that is a number whole is spelled as that number
        // (Adyen's challenge indicators, corpus row 229's golden).
        assert_eq!(enum_member_name("01"), "ONE");
        assert_eq!(enum_visit_param("09"), "nine");
        assert_eq!(enum_member_name("00"), "ZERO");
        // Past Fern's speller's range the leading run is the literal
        // `undefined` (People Data Labs' company sizes, corpus row 230).
        assert_eq!(enum_member_name("10001+"), "UNDEFINED");
        assert_eq!(enum_visit_param("10001+"), "undefined");
        // Consecutive single letters join into one word.
        assert_eq!(enum_member_name("u.s. virgin islands"), "US_VIRGIN_ISLANDS");
    }

    #[test]
    fn enum_names_match_ferns_sanitized_identifiers() {
        // Keyword value: member is safe (upper-cased), the visit param is escaped.
        assert_eq!(enum_member_name("global"), "GLOBAL");
        assert_eq!(enum_visit_param("global"), "global_");
        assert_eq!(enum_member_name("practice"), "PRACTICE");
        assert_eq!(enum_visit_param("practice"), "practice");
        // Punctuation + a leading single digit: the digit is spelled out and the
        // `:`/space become word boundaries (Fern: `0: Active` → `ZERO_ACTIVE`).
        assert_eq!(enum_member_name("0: Active"), "ZERO_ACTIVE");
        assert_eq!(enum_visit_param("0: Active"), "zero_active");
        assert_eq!(enum_member_name("1: InActive"), "ONE_IN_ACTIVE");
        assert_eq!(enum_member_name("oauth2.0"), "OAUTH20");
        assert_eq!(enum_member_name("ID_CUSIP_8_CHR"), "ID_CUSIP8CHR");
        assert_eq!(enum_visit_param("ID_CUSIP_8_CHR"), "id_cusip8chr");
        assert_eq!(enum_member_name("SCHEDULE5MANUAL"), "SCHEDULE5MANUAL");
        assert_eq!(enum_visit_param("SCHEDULE5MANUAL"), "schedule5manual");
        assert_eq!(enum_member_name("200"), "TWO_HUNDRED");
        assert_eq!(enum_visit_param("201"), "two_hundred_one");
        assert_eq!(enum_member_name("1200 bps"), "ONE_THOUSAND_TWO_HUNDRED_BPS");
        assert_eq!(enum_member_name("19.2 kbps"), "NINETEEN2KBPS");
        assert_eq!(enum_member_name("DB-25"), "DB25");
        assert_eq!(enum_member_name("SFP+ (10GE)"), "SFP10GE");
        assert_eq!(enum_member_name("IEEE 802.11a"), "IEEE80211A");
        assert_eq!(enum_member_name("IEEE 802.11b/g"), "IEEE80211BG");
        assert_eq!(enum_member_name("10gbase-x-x2"), "TEN_GBASE_XX2");
        assert_eq!(enum_member_name("P+N+E 4H"), "PNE4H");
        assert_eq!(enum_member_name("2P+E 4H"), "TWO_PE4H");
        assert_eq!(
            enum_member_name("ITA Type E/F (CEE 7/7)"),
            "ITA_TYPE_EF_CEE77"
        );
        assert_eq!(enum_member_name("iec-60309-3p-n-e-4h"), "IEC603093PNE4H");
        assert_eq!(
            enum_member_name("100BASE-FX (10/100ME FIBER)"),
            "ONE_HUNDRED_BASE_FX10100ME_FIBER"
        );
        assert_eq!(
            enum_member_name("fbf35668-96a0-4baa-bcde-ab18d6b1b329"),
            "FBF3566896A04BAA_BCDE_AB18D6B1B329"
        );
        assert_eq!(
            enum_member_name("6a9dfcad-600b-46c8-9e08-ce6e5057921e"),
            "SIX_A9DFCAD600B46C89E08CE6E5057921E"
        );
        assert_eq!(
            enum_member_name("98777886-76d0-44c8-865e-bb40e669e934"),
            "UNDEFINED76D044C8865E_BB40E669E934"
        );
        assert_eq!(
            enum_member_name("ac5b9c1e-dc78-466d-b0b3-7cf712967a48"),
            "AC5B9C1E_DC78466DB0B37CF712967A48"
        );
        assert_eq!(
            enum_visit_param("ac5b9c1e-dc78-466d-b0b3-7cf712967a48"),
            "ac5b9c1e_dc78466db0b37cf712967a48"
        );
        assert_eq!(enum_member_name(""), "EMPTY");
        assert_eq!(enum_visit_param(""), "empty");
        assert_eq!(enum_visit_param("1: InActive"), "one_in_active");
    }

    #[test]
    fn enum_receiver_value_escapes_the_visit_param() {
        // Issue #57: a value that sanitizes to the `visit(self, …)` receiver name
        // `self` would emit a duplicate `self` argument (invalid at import though
        // `ruff` accepts it); the visit param is escaped like a keyword, while the
        // member upper-cases to `SELF` (never a receiver collision) and is untouched.
        assert_eq!(enum_member_name("self"), "SELF");
        assert_eq!(enum_visit_param("self"), "self_");
        // Casing that sanitizes to `self` is escaped too.
        assert_eq!(enum_visit_param("Self"), "self_");
        // `cls` is NOT escaped: `visit` is an instance method, so a `cls` parameter
        // is legal and does not shadow the receiver — Fern leaves it alone.
        assert_eq!(enum_member_name("cls"), "CLS");
        assert_eq!(enum_visit_param("cls"), "cls");
        // `kwargs` is escaped, the other pydantic-model names are not.
        assert_eq!(enum_member_name("kwargs"), "KWARGS");
        assert_eq!(enum_visit_param("kwargs"), "kwargs_");
        assert_eq!(enum_visit_param("json"), "json");
        assert_eq!(enum_visit_param("copy"), "copy");
    }

    #[test]
    fn spelled_number_tables_cover_every_digit_and_stop_at_five_figures() {
        // `digit_word` and `numeric_enum_identifier` are lookup tables: a wrong
        // entry changes an enum member silently, so pin every branch of both.
        for (digit, word) in [
            ("0", "zero"),
            ("1", "one"),
            ("2", "two"),
            ("3", "three"),
            ("4", "four"),
            ("5", "five"),
            ("6", "six"),
            ("7", "seven"),
            ("8", "eight"),
            ("9", "nine"),
        ] {
            assert_eq!(digit_word(digit), Some(word));
        }
        assert_eq!(digit_word("12"), None);
        assert_eq!(digit_word("x"), None);
        assert_eq!(digit_word(""), None);
        // Tens with and without a trailing unit, and the hundreds/thousands join.
        assert_eq!(enum_member_name("40"), "FORTY");
        assert_eq!(enum_member_name("45"), "FORTY_FIVE");
        assert_eq!(enum_member_name("19"), "NINETEEN");
        assert_eq!(enum_member_name("999"), "NINE_HUNDRED_NINETY_NINE");
        assert_eq!(
            enum_member_name("9999"),
            "NINE_THOUSAND_NINE_HUNDRED_NINETY_NINE"
        );
        // Past four figures Fern stops spelling; Crozier keeps the name legal.
        assert_eq!(enum_member_name("10000"), "_10000");
        // A value that is one of Fern's mapped symbols *whole* is spelled out;
        // inside a longer value the same symbol is only a separator.
        assert_eq!(enum_member_name("*"), "ALL");
        assert_eq!(enum_visit_param("*"), "all_");
        assert_eq!(enum_member_name("image/*"), "IMAGE");
        for (value, name) in [
            ("<", "LESS_THAN"),
            (">", "GREATER_THAN"),
            (">=", "GREATER_THAN_OR_EQUAL_TO"),
            ("<=", "LESS_THAN_OR_EQUAL_TO"),
            ("!=", "NOT_EQUALS"),
            ("=", "EQUAL_TO"),
            ("==", "EQUAL_TO"),
            ("\"\"", "EMPTY_STRING"),
            ("-", "HYPHEN"),
            ("|", "PIPE"),
            (".", "DOT"),
            ("/", "SLASH"),
            ("n/a", "NOT_APPLICABLE"),
            ("N/A", "NOT_APPLICABLE"),
        ] {
            assert_eq!(enum_member_name(value), name, "{value}");
        }
        assert_eq!(enum_visit_param("/"), "slash");
    }

    #[test]
    fn enum_names_stay_legal_where_fern_would_error() {
        // A leading-zero token retains Crozier's legal-identifier guard where
        // Fern would reject the enum name.
        assert_eq!(enum_member_name("_01_00_AM"), "_01_00_AM");
        assert_eq!(enum_visit_param("_01_00_AM"), "_01_00_am");
        assert_eq!(enum_member_name("2fa"), "TWO_FA");
        assert_eq!(enum_visit_param("2fa"), "two_fa");
        // A value with no identifier characters still yields a legal name.
        assert_eq!(enum_member_name("!!!"), "_");
        assert_eq!(enum_visit_param("!!!"), "_");
        // A bare `=` is the one operator Fern spells out.
        assert_eq!(enum_member_name("="), "EQUAL_TO");
        assert_eq!(enum_visit_param("="), "equal_to");
    }

    #[test]
    fn class_names_break_words_on_non_identifier_characters() {
        assert_eq!(
            class_name("{{baseUrl}}/persons/:personId-Request"),
            "BaseUrlPersonsPersonIdRequest"
        );
        assert_eq!(class_name("snake_case.Name"), "SnakeCaseName");
    }

    #[test]
    fn sanitize_identifier_coerces_illegal_chars() {
        assert_eq!(sanitize_identifier("get-all-widgets"), "get_all_widgets");
        assert_eq!(sanitize_identifier("verify code"), "verify_code");
        assert_eq!(sanitize_identifier("2fa"), "_2fa");
        assert_eq!(to_pascal_case("ipam_l2vpns_list"), "IpamL2VpnsList");
        // Already-legal identifiers pass through unchanged.
        assert_eq!(
            sanitize_identifier("dispatchwithoutbadge"),
            "dispatchwithoutbadge"
        );
        assert_eq!(
            prose_identifier("The /content endpoint"),
            "the_content_endpoint"
        );
        assert_eq!(
            prose_identifier("Get seller's feedback"),
            "get_sellers_feedback"
        );
        assert_eq!(
            prose_identifier("Returns 200 on success or 422 on failure"),
            "returns200on_success_or422on_failure"
        );
        assert_eq!(
            sanitize_identifier("handling_manifest"),
            "handling_manifest"
        );
    }

    #[test]
    fn summary_identifier_joins_one_letter_words_the_way_camel_casing_does() {
        assert_eq!(
            summary_identifier("load a gRPC proto descriptor set"),
            "load_ag_rpc_proto_descriptor_set"
        );
        assert_eq!(
            summary_identifier("retrieve gRPC health serving statuses"),
            "retrieve_g_rpc_health_serving_statuses"
        );
        assert_eq!(summary_identifier("a b c"), "a_bc");
    }

    #[test]
    fn summary_identifier_deletes_full_stops_but_keeps_other_separators() {
        // Sentence punctuation inside a summary is deleted, not broken on.
        assert_eq!(
            summary_identifier("Update a software statement certificate with the given CertificateOrKeyId e.g. revoke reason"),
            "update_a_software_statement_certificate_with_the_given_certificate_or_key_id_eg_revoke_reason"
        );
        // Every other separator still breaks a word, and a trailing stop is a no-op.
        assert_eq!(
            summary_identifier("Mark a conversation read/unread"),
            "mark_a_conversation_read_unread"
        );
        assert_eq!(
            summary_identifier("Disable vacation mode. All listings will be re-enabled."),
            "disable_vacation_mode_all_listings_will_be_re_enabled"
        );
        // The URL fallback keeps the full stop as a boundary, so the two differ.
        assert_eq!(
            prose_identifier("_proxy_openapi.json"),
            "proxy_openapi_json"
        );
    }
}