openapi-to-rust 0.6.0

Generate strongly-typed Rust structs, HTTP clients, and SSE streaming clients from OpenAPI 3.1 specifications
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
//! Centralized OpenAPI type → Rust type mapping.
//!
//! [`TypeMapper`] is the single chokepoint for every `(openapi_type,
//! format)` → Rust-type decision. Q2.0 introduced the chokepoint with
//! pass-through behavior; Q2 (quq) flips the defaults so common string
//! formats (`date-time`, `uuid`, `uri`, …) become typed Rust scalars
//! out of the box.
//!
//! # Design
//! - Per-format **strategy enums** (e.g. [`DateStrategy`]) drive the
//!   mapping. Defaults are opt-out: typed by default, set the
//!   strategy to `String` to recover plain `String`.
//! - [`MappedType`] carries the Rust type **plus** an optional
//!   `#[serde(with = "...")]` codec hint. Codec hints flow through
//!   [`SchemaType::Primitive`](crate::analysis::SchemaType::Primitive)
//!   to the field-emission site in `generator.rs`, which wraps them
//!   in a `#[serde(with = …)]` attribute.
//! - [`UsedFeatures`] tracks which optional crates the mapper
//!   actually emitted references to. Q2.8 will read this after
//!   generation and write a `REQUIRED_DEPS.toml`.
//!
//! # Conservative mode
//! Pass `TypeMappingConfig::conservative()` (CLI: `--types-conservative`)
//! to recover pre-Q2 behavior — every format renders as `String`. Useful
//! for bisecting regressions caused by typed-scalar adoption.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use crate::openapi::{SchemaDetails, SchemaType as OpenApiSchemaType};

/// Result of mapping an OpenAPI `(type, format)` pair to a Rust type.
#[derive(Debug, Clone)]
pub struct MappedType {
    /// The Rust type as a string, e.g. `"String"`,
    /// `"chrono::DateTime<chrono::Utc>"`.
    pub rust_type: String,
    /// Optional `#[serde(with = "...")]` codec path. The generator
    /// wraps this in a `with = "<value>"` field attribute.
    pub serde_with: Option<String>,
    /// Optional crate this mapping introduced. Tracked in
    /// [`UsedFeatures`] for the dep advisory (Q2.8).
    pub feature: Option<TypeFeature>,
}

impl MappedType {
    /// Construct a plain mapping with no codec and no external crate.
    pub fn plain(rust_type: impl Into<String>) -> Self {
        Self {
            rust_type: rust_type.into(),
            serde_with: None,
            feature: None,
        }
    }

    /// Plain mapping that records a feature crate (e.g. for types like
    /// `std::net::Ipv4Addr` we don't need a codec but we don't need a
    /// crate either — this helper is for crates that derive `serde`
    /// directly on the type).
    pub fn with_feature(rust_type: impl Into<String>, feature: TypeFeature) -> Self {
        Self {
            rust_type: rust_type.into(),
            serde_with: None,
            feature: Some(feature),
        }
    }

    /// Mapping that requires a `#[serde(with = ...)]` codec.
    pub fn with_codec(
        rust_type: impl Into<String>,
        codec_path: impl Into<String>,
        feature: TypeFeature,
    ) -> Self {
        Self {
            rust_type: rust_type.into(),
            serde_with: Some(codec_path.into()),
            feature: Some(feature),
        }
    }
}

/// Identifies an optional crate a mapping introduced.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TypeFeature {
    Chrono,
    Time,
    /// `time::Date` via the generated `time_date_format` codec.
    /// Tracked separately from [`TypeFeature::Time`] so the
    /// generator only emits the `time::serde::format_description!`
    /// helper when a `format: date` field actually exists.
    TimeDate,
    /// `time::Time` via the generated `time_time_format` codec.
    TimeTime,
    Iso8601,
    Uuid,
    Bytes,
    Base64,
    Url,
    EmailAddress,
}

impl TypeFeature {
    /// Canonical dependency line for this feature. Q2.8 uses this to
    /// emit `REQUIRED_DEPS.toml` next to the generated code so users
    /// know exactly which crates to add to their Cargo.toml.
    pub fn dep_requirement(self) -> DepRequirement {
        match self {
            Self::Chrono => DepRequirement::new("chrono", "0.4").with_features(&["serde"]),
            // `serde` alone doesn't enable `time::serde::rfc3339`;
            // the codec modules are gated on formatting/parsing.
            Self::Time => DepRequirement::new("time", "0.3").with_features(&[
                "serde",
                "formatting",
                "parsing",
            ]),
            // `macros` on top: Date/Time have no built-in serde
            // codec, so the generated code declares one via
            // `time::serde::format_description!`.
            Self::TimeDate | Self::TimeTime => DepRequirement::new("time", "0.3").with_features(&[
                "serde",
                "formatting",
                "parsing",
                "macros",
            ]),
            Self::Iso8601 => DepRequirement::new("iso8601", "0.6"),
            Self::Uuid => DepRequirement::new("uuid", "1").with_features(&["serde", "v4"]),
            Self::Bytes => DepRequirement::new("bytes", "1").with_features(&["serde"]),
            Self::Base64 => DepRequirement::new("base64", "0.22"),
            Self::Url => DepRequirement::new("url", "2").with_features(&["serde"]),
            Self::EmailAddress => DepRequirement::new("email_address", "0.2"),
        }
    }
}

/// One crate the generated code needs in its `Cargo.toml`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DepRequirement {
    pub crate_name: &'static str,
    pub version: &'static str,
    pub features: Vec<&'static str>,
}

impl DepRequirement {
    pub fn new(crate_name: &'static str, version: &'static str) -> Self {
        Self {
            crate_name,
            version,
            features: Vec::new(),
        }
    }

    pub fn with_features(mut self, features: &[&'static str]) -> Self {
        self.features = features.to_vec();
        self
    }

    /// Render as a single TOML `[dependencies]` line. Picks the
    /// most compact form that still expresses the required features.
    pub fn to_toml_line(&self) -> String {
        if self.features.is_empty() {
            format!("{} = \"{}\"", self.crate_name, self.version)
        } else {
            let feats = self
                .features
                .iter()
                .map(|f| format!("\"{f}\""))
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "{} = {{ version = \"{}\", features = [{}] }}",
                self.crate_name, self.version, feats
            )
        }
    }
}

/// Render `REQUIRED_DEPS.toml` content from a sorted set of
/// requirements. Returns `None` when the input is empty so the
/// caller can skip writing the file (no clutter when no optional
/// crates were used).
pub fn render_required_deps_toml(deps: &[DepRequirement]) -> Option<String> {
    if deps.is_empty() {
        return None;
    }
    let mut out = String::new();
    out.push_str(
        "# Generated by openapi-to-rust.\n\
         # These crates are required by the typed-scalar formats used\n\
         # in your OpenAPI spec. Copy these lines into the [dependencies]\n\
         # section of your consuming crate's Cargo.toml.\n\
         #\n\
         # To opt out of typed scalars (and avoid these deps), set\n\
         # the relevant strategies to \"string\" in [generator.types],\n\
         # or pass --types-conservative on the CLI.\n\
         \n\
         [dependencies]\n",
    );
    for dep in deps {
        out.push_str(&dep.to_toml_line());
        out.push('\n');
    }
    Some(out)
}

/// Snapshot a `UsedFeatures` set as a sorted, de-duplicated list of
/// `DepRequirement`s. Sorting by crate name keeps the emitted file
/// deterministic so it can be checked in or diffed.
pub fn collect_dep_requirements(used: &UsedFeatures) -> Vec<DepRequirement> {
    let mut deps: Vec<DepRequirement> = used.iter().map(|f| f.dep_requirement()).collect();
    deps.sort_by_key(|d| d.crate_name);
    // Several features can point at the same crate with different
    // feature lists (e.g. Time vs TimeDate both need `time`); union
    // the features so the single emitted line satisfies all of them.
    let mut merged: Vec<DepRequirement> = Vec::new();
    for dep in deps {
        match merged.last_mut() {
            Some(last) if last.crate_name == dep.crate_name => {
                for feat in dep.features {
                    if !last.features.contains(&feat) {
                        last.features.push(feat);
                    }
                }
            }
            _ => merged.push(dep),
        }
    }
    merged
}

/// Tracks which optional crates the generator emitted code for.
#[derive(Debug, Default, Clone)]
pub struct UsedFeatures {
    set: BTreeSet<TypeFeature>,
}

impl UsedFeatures {
    pub fn insert(&mut self, feature: TypeFeature) {
        self.set.insert(feature);
    }

    pub fn contains(&self, feature: TypeFeature) -> bool {
        self.set.contains(&feature)
    }

    pub fn iter(&self) -> impl Iterator<Item = &TypeFeature> {
        self.set.iter()
    }

    pub fn is_empty(&self) -> bool {
        self.set.is_empty()
    }
}

// =====================================================================
// Strategy enums
// =====================================================================

/// Strategy for `format: date-time | date | time`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DateStrategy {
    /// Plain `String`. Pre-Q2 behavior; pick this to opt out.
    String,
    /// `chrono::DateTime<Utc>` / `NaiveDate` / `NaiveTime` (default).
    #[default]
    Chrono,
    /// `time::OffsetDateTime` / `Date` / `Time`.
    Time,
}

/// Strategy for `format: duration` (ISO 8601 durations).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DurationStrategy {
    // Off by default — `format: duration` is ISO 8601 (e.g.
    // "PT1H30M") but `chrono::Duration`'s native serde encodes
    // seconds. Round-tripping requires a custom parser that we'll
    // land in a follow-up; for now `duration` stays String so
    // default-on doesn't break specs that emit ISO 8601 strings
    // the chrono codec couldn't decode.
    #[default]
    String,
    /// `chrono::Duration`. Round-trips ISO 8601 durations via a
    /// small custom serde module emitted into the generated crate.
    Chrono,
    /// `iso8601::Duration` from the `iso8601` crate.
    Iso8601,
}

/// Strategy for `format: uuid` (or normalized aliases).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum UuidStrategy {
    String,
    /// `uuid::Uuid` (default).
    #[default]
    Uuid,
}

/// Strategy for `format: byte` (base64-encoded binary on the wire).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ByteStrategy {
    String,
    /// `Vec<u8>` round-tripped via an inlined `base64_serde` module
    /// (default).
    #[default]
    Base64,
    /// `Vec<u8>` with no codec (caller responsible for encoding).
    VecU8,
}

/// Strategy for `format: binary` (raw octets).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BinaryStrategy {
    String,
    /// `bytes::Bytes` (default).
    #[default]
    Bytes,
    VecU8,
}

/// Strategy for `format: ipv4 | ipv6`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum IpStrategy {
    String,
    /// `std::net::Ipv4Addr` / `Ipv6Addr` (default; pure std, no deps).
    #[default]
    Std,
}

/// Strategy for `format: uri | url`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum UriStrategy {
    String,
    /// `url::Url` (default).
    #[default]
    Url,
}

/// Strategy for `format: email`.
///
/// Email is **off by default** — the `email_address` crate is more
/// opinionated than the wire ever guarantees, and most APIs treat
/// emails as opaque strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EmailStrategy {
    #[default]
    String,
    EmailAddress,
}

// =====================================================================
// Top-level config
// =====================================================================

/// Configuration for [`TypeMapper`]. Mirrors the `[generator.types]`
/// TOML section. Defaults flip on every common typed scalar; opt out
/// per format by setting the strategy to `string` in TOML.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, rename_all = "snake_case")]
pub struct TypeMappingConfig {
    pub date_time: DateStrategy,
    pub date: DateStrategy,
    pub time: DateStrategy,
    pub duration: DurationStrategy,
    pub uuid: UuidStrategy,
    pub byte: ByteStrategy,
    pub binary: BinaryStrategy,
    pub ipv4: IpStrategy,
    pub ipv6: IpStrategy,
    pub uri: UriStrategy,
    pub email: EmailStrategy,

    /// Q2.1: honor `format: uint32` / `uint64` integer formats and
    /// map them to `u32` / `u64` respectively. Default `true` (cheap,
    /// no extra crate). Set `false` to revert to the pre-Q2.1
    /// behavior where unsigned formats degraded to `i64`.
    #[serde(default = "default_true")]
    pub unsigned: bool,

    /// Q2.2: user-extensible format aliases applied before standard
    /// format dispatch (e.g. `"uuid4" -> "uuid"`,
    /// `"unix-time" -> "int64"`). Built-in defaults are merged with
    /// user-supplied entries; user entries win on collision.
    #[serde(default)]
    pub format_aliases: BTreeMap<String, String>,

    /// Object/array shape toggles. Filled in by Q2.3, Q2.5, Q2.7.
    pub shape: Option<TypeShapeConfig>,

    /// Constraint annotation mode. Filled in by Q2.4.
    pub constraints: Option<TypeConstraintsConfig>,

    /// Vendor-extension toggles for enums. Filled in by Q2.6.
    pub enums: Option<TypeEnumsConfig>,
}

fn default_true() -> bool {
    true
}

impl Default for TypeMappingConfig {
    fn default() -> Self {
        Self {
            date_time: DateStrategy::default(),
            date: DateStrategy::default(),
            time: DateStrategy::default(),
            duration: DurationStrategy::default(),
            uuid: UuidStrategy::default(),
            byte: ByteStrategy::default(),
            binary: BinaryStrategy::default(),
            ipv4: IpStrategy::default(),
            ipv6: IpStrategy::default(),
            uri: UriStrategy::default(),
            email: EmailStrategy::default(),
            unsigned: true,
            format_aliases: BTreeMap::new(),
            shape: None,
            constraints: None,
            enums: None,
        }
    }
}

/// Built-in format aliases applied before user-supplied
/// [`TypeMappingConfig::format_aliases`]. These normalize common
/// vendor-isms found in real-world specs so the standard format
/// dispatch in [`TypeMapper::string_format`] /
/// [`TypeMapper::integer_format`] sees canonical names.
fn builtin_format_aliases() -> &'static [(&'static str, &'static str)] {
    &[
        ("uuid4", "uuid"),
        ("uuid_v4", "uuid"),
        ("UUID", "uuid"),
        ("unix-time", "int64"),
        ("unix_time", "int64"),
        ("unixtime", "int64"),
        ("timestamp", "int64"),
    ]
}

impl TypeMappingConfig {
    /// Q2.4: constraint-doc emission mode. Defaults to
    /// [`ConstraintMode::Doc`] when the
    /// `[generator.types.constraints]` block is absent or its
    /// `mode` field is unset.
    pub fn constraint_mode(&self) -> ConstraintMode {
        self.constraints
            .as_ref()
            .and_then(|c| c.mode)
            .unwrap_or_default()
    }

    /// Q2.6: should `x-enum-varnames` override the heuristic
    /// PascalCase variant naming? Default true.
    pub fn x_enum_varnames_enabled(&self) -> bool {
        self.enums
            .as_ref()
            .and_then(|e| e.x_enum_varnames)
            .unwrap_or(true)
    }

    /// Q2.6: should `x-enum-descriptions` emit per-variant doc
    /// comments? Default true.
    pub fn x_enum_descriptions_enabled(&self) -> bool {
        self.enums
            .as_ref()
            .and_then(|e| e.x_enum_descriptions)
            .unwrap_or(true)
    }

    /// Pre-Q2 behavior — every format renders as `String` and
    /// integer formats degrade to `i64`. Users opt in via
    /// `--types-conservative` when bisecting regressions introduced
    /// by typed-scalar adoption.
    pub fn conservative() -> Self {
        Self {
            date_time: DateStrategy::String,
            date: DateStrategy::String,
            time: DateStrategy::String,
            duration: DurationStrategy::String,
            uuid: UuidStrategy::String,
            byte: ByteStrategy::String,
            binary: BinaryStrategy::String,
            ipv4: IpStrategy::String,
            ipv6: IpStrategy::String,
            uri: UriStrategy::String,
            email: EmailStrategy::String,
            unsigned: false,
            format_aliases: BTreeMap::new(),
            shape: None,
            constraints: None,
            enums: None,
        }
    }
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, rename_all = "snake_case")]
pub struct TypeShapeConfig {
    pub additional_properties_typed: Option<bool>,
    pub unique_items_to_set: Option<bool>,
    pub primitive_unions: Option<bool>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, rename_all = "snake_case")]
pub struct TypeConstraintsConfig {
    /// Q2.4 constraint annotation mode. Defaults to `Doc` when the
    /// `[generator.types.constraints]` block is absent (see
    /// [`TypeMapper::config_constraint_mode`]).
    pub mode: Option<ConstraintMode>,
}

/// Q2.4 — what to emit for OpenAPI constraint keywords
/// (`minimum`/`maximum`/`minLength`/`maxLength`/`pattern`/etc.).
///
/// **No client-side validation.** Constraints belong to the wire
/// contract; the server is the source of truth. The generator
/// surfaces them only as doc-comments so callers see the rules
/// without the SDK duplicating server logic and going brittle
/// when the rules drift.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ConstraintMode {
    /// Drop constraints entirely (pre-Q2.4 behavior).
    Off,
    /// Emit `/// Constraint: ...` doc comments on each field.
    /// Cheap, no extra crate dependency. Default.
    #[default]
    Doc,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, rename_all = "snake_case")]
pub struct TypeEnumsConfig {
    pub x_enum_varnames: Option<bool>,
    pub x_enum_descriptions: Option<bool>,
}

// =====================================================================
// TypeMapper
// =====================================================================

pub struct TypeMapper {
    config: TypeMappingConfig,
    used: RefCell<UsedFeatures>,
}

impl Default for TypeMapper {
    fn default() -> Self {
        Self::new(TypeMappingConfig::default())
    }
}

impl TypeMapper {
    pub fn new(config: TypeMappingConfig) -> Self {
        Self {
            config,
            used: RefCell::new(UsedFeatures::default()),
        }
    }

    /// Snapshot of crates this mapper has emitted references to.
    /// Read after generation by Q2.8 to write `REQUIRED_DEPS.toml`.
    pub fn used_features(&self) -> UsedFeatures {
        self.used.borrow().clone()
    }

    /// Borrow the underlying type-mapping config — useful for
    /// non-format-mapping toggles (`shape`, `enums`, `constraints`)
    /// that other modules need to inspect.
    pub fn config(&self) -> &TypeMappingConfig {
        &self.config
    }

    /// Q2.7 helper: should `anyOf` of primitives become an untagged
    /// enum with primitive variant types directly (true), or fall
    /// back to the pre-Q2.7 type-alias-per-variant shape (false)?
    /// Default: true.
    pub fn config_shape_primitive_unions(&self) -> Option<bool> {
        self.config.shape.as_ref().and_then(|s| s.primitive_unions)
    }

    /// Q2.3 helper: should `additionalProperties: <schema>` produce
    /// `BTreeMap<String, T>` (true) or degrade to `BTreeMap<String,
    /// serde_json::Value>` (false)? Default: true.
    pub fn config_shape_additional_properties_typed(&self) -> Option<bool> {
        self.config
            .shape
            .as_ref()
            .and_then(|s| s.additional_properties_typed)
    }

    /// Q2.4 helper: which constraint-annotation mode is active?
    /// Defaults to [`ConstraintMode::Doc`] when the
    /// `[generator.types.constraints]` block is absent or its `mode`
    /// field is unset.
    pub fn config_constraint_mode(&self) -> ConstraintMode {
        self.config
            .constraints
            .as_ref()
            .and_then(|c| c.mode)
            .unwrap_or_default()
    }

    fn record(&self, feature: TypeFeature) {
        self.used.borrow_mut().insert(feature);
    }

    /// Map `string` + optional `format` → typed Rust scalar.
    ///
    /// Routing:
    /// 1. Apply user-provided + built-in `format_aliases`.
    /// 2. Dispatch on the normalized format.
    /// 3. Honor each format's strategy in `self.config`.
    /// 4. Record any introduced crate in `used_features`.
    pub fn string_format(&self, format: Option<&str>) -> MappedType {
        let normalized = self.normalize_format(format);
        match normalized.as_deref() {
            Some("date-time") => self.map_date_time(self.config.date_time),
            Some("date") => self.map_date(self.config.date),
            Some("time") => self.map_time(self.config.time),
            Some("duration") => self.map_duration(self.config.duration),
            Some("uuid") => self.map_uuid(self.config.uuid),
            Some("byte") => self.map_byte(self.config.byte),
            Some("binary") => self.map_binary(self.config.binary),
            Some("ipv4") => self.map_ipv4(self.config.ipv4),
            Some("ipv6") => self.map_ipv6(self.config.ipv6),
            Some("uri") | Some("url") => self.map_uri(self.config.uri),
            Some("email") => self.map_email(self.config.email),
            // Unknown formats (hostname, password, idn-email, etc.)
            // and the no-format case fall through to plain String.
            _ => MappedType::plain("String"),
        }
    }

    /// Apply user + built-in format aliases (in that order — user
    /// entries win on collision). Built-ins normalize common
    /// vendor-isms like `uuid4` → `uuid` and `unix-time` → `int64`
    /// so the standard format dispatch below sees canonical names.
    fn normalize_format(&self, format: Option<&str>) -> Option<String> {
        let raw = format?;
        if let Some(target) = self.config.format_aliases.get(raw) {
            return Some(target.clone());
        }
        for (from, to) in builtin_format_aliases() {
            if *from == raw {
                return Some((*to).to_string());
            }
        }
        Some(raw.to_string())
    }

    fn map_date_time(&self, strat: DateStrategy) -> MappedType {
        match strat {
            DateStrategy::String => MappedType::plain("String"),
            DateStrategy::Chrono => {
                self.record(TypeFeature::Chrono);
                // chrono::DateTime<Utc> with the `serde` feature
                // serializes as RFC 3339 by default and parses both
                // `Z` and `+HH:MM` offsets on input. No `with`
                // attribute required.
                MappedType::with_feature("chrono::DateTime<chrono::Utc>", TypeFeature::Chrono)
            }
            DateStrategy::Time => {
                self.record(TypeFeature::Time);
                MappedType::with_codec(
                    "time::OffsetDateTime",
                    "time::serde::rfc3339",
                    TypeFeature::Time,
                )
            }
        }
    }

    fn map_date(&self, strat: DateStrategy) -> MappedType {
        match strat {
            DateStrategy::String => MappedType::plain("String"),
            DateStrategy::Chrono => {
                self.record(TypeFeature::Chrono);
                // chrono derives serde via the `serde` feature; no
                // codec needed for NaiveDate (ISO 8601 by default).
                MappedType::with_feature("chrono::NaiveDate", TypeFeature::Chrono)
            }
            DateStrategy::Time => {
                self.record(TypeFeature::TimeDate);
                // `time::serde::iso8601` only supports
                // OffsetDateTime; `time_date_format` is a codec
                // module the generator emits into the file via
                // `time::serde::format_description!` (GH #25).
                MappedType::with_codec("time::Date", "time_date_format", TypeFeature::TimeDate)
            }
        }
    }

    fn map_time(&self, strat: DateStrategy) -> MappedType {
        match strat {
            DateStrategy::String => MappedType::plain("String"),
            DateStrategy::Chrono => {
                self.record(TypeFeature::Chrono);
                MappedType::with_feature("chrono::NaiveTime", TypeFeature::Chrono)
            }
            DateStrategy::Time => {
                self.record(TypeFeature::TimeTime);
                // Same story as `time::Date`: no built-in codec, so
                // the generator emits `time_time_format`.
                MappedType::with_codec("time::Time", "time_time_format", TypeFeature::TimeTime)
            }
        }
    }

    fn map_duration(&self, strat: DurationStrategy) -> MappedType {
        match strat {
            DurationStrategy::String => MappedType::plain("String"),
            DurationStrategy::Chrono => {
                // Placeholder: chrono::Duration's native serde
                // encodes seconds (not ISO 8601). A follow-up will
                // emit an iso8601_duration_serde helper module and
                // wire it via with_codec; for now downgrade to the
                // String mapping so this strategy is safe to enable
                // even before the helper exists.
                MappedType::plain("String")
            }
            DurationStrategy::Iso8601 => {
                self.record(TypeFeature::Iso8601);
                MappedType::with_feature("iso8601::Duration", TypeFeature::Iso8601)
            }
        }
    }

    fn map_uuid(&self, strat: UuidStrategy) -> MappedType {
        match strat {
            UuidStrategy::String => MappedType::plain("String"),
            UuidStrategy::Uuid => {
                self.record(TypeFeature::Uuid);
                MappedType::with_feature("uuid::Uuid", TypeFeature::Uuid)
            }
        }
    }

    fn map_byte(&self, strat: ByteStrategy) -> MappedType {
        match strat {
            ByteStrategy::String => MappedType::plain("String"),
            ByteStrategy::VecU8 => MappedType::plain("Vec<u8>"),
            ByteStrategy::Base64 => {
                self.record(TypeFeature::Base64);
                // Path is resolved relative to the generated
                // module; the helper module is emitted as
                // `base64_serde` at the top of `types.rs`.
                MappedType::with_codec("Vec<u8>", "base64_serde", TypeFeature::Base64)
            }
        }
    }

    fn map_binary(&self, strat: BinaryStrategy) -> MappedType {
        match strat {
            BinaryStrategy::String => MappedType::plain("String"),
            BinaryStrategy::VecU8 => MappedType::plain("Vec<u8>"),
            BinaryStrategy::Bytes => {
                self.record(TypeFeature::Bytes);
                MappedType::with_feature("bytes::Bytes", TypeFeature::Bytes)
            }
        }
    }

    fn map_ipv4(&self, strat: IpStrategy) -> MappedType {
        match strat {
            IpStrategy::String => MappedType::plain("String"),
            IpStrategy::Std => MappedType::plain("std::net::Ipv4Addr"),
        }
    }

    fn map_ipv6(&self, strat: IpStrategy) -> MappedType {
        match strat {
            IpStrategy::String => MappedType::plain("String"),
            IpStrategy::Std => MappedType::plain("std::net::Ipv6Addr"),
        }
    }

    fn map_uri(&self, strat: UriStrategy) -> MappedType {
        match strat {
            UriStrategy::String => MappedType::plain("String"),
            UriStrategy::Url => {
                self.record(TypeFeature::Url);
                MappedType::with_feature("url::Url", TypeFeature::Url)
            }
        }
    }

    fn map_email(&self, strat: EmailStrategy) -> MappedType {
        match strat {
            EmailStrategy::String => MappedType::plain("String"),
            EmailStrategy::EmailAddress => {
                self.record(TypeFeature::EmailAddress);
                MappedType::with_feature("email_address::EmailAddress", TypeFeature::EmailAddress)
            }
        }
    }

    /// Map `integer` + optional `format` → Rust type.
    ///
    /// Q2.1: honors `uint32` / `uint64` (and a few vendor variants
    /// like `uint`) when `config.unsigned` is true (default).
    /// Setting `unsigned = false` reverts to the pre-Q2.1 behavior
    /// where unsigned formats degrade to `i64`.
    pub fn integer_format(&self, format: Option<&str>) -> MappedType {
        let normalized = self.normalize_format(format);
        match normalized.as_deref() {
            Some("int32") => MappedType::plain("i32"),
            Some("int64") => MappedType::plain("i64"),
            Some("uint32") if self.config.unsigned => MappedType::plain("u32"),
            Some("uint64") if self.config.unsigned => MappedType::plain("u64"),
            // OAS-adjacent specs sometimes use bare `uint` — treat
            // it as 64-bit unsigned to match the broadest intended
            // domain.
            Some("uint") if self.config.unsigned => MappedType::plain("u64"),
            _ => MappedType::plain("i64"),
        }
    }

    pub fn number_format(&self, format: Option<&str>) -> MappedType {
        let normalized = self.normalize_format(format);
        match normalized.as_deref() {
            Some("float") => MappedType::plain("f32"),
            Some("double") => MappedType::plain("f64"),
            _ => MappedType::plain("f64"),
        }
    }

    pub fn boolean(&self) -> MappedType {
        MappedType::plain("bool")
    }

    pub fn untyped_array(&self) -> MappedType {
        MappedType::plain("Vec<serde_json::Value>")
    }

    pub fn dynamic_json(&self) -> MappedType {
        MappedType::plain("serde_json::Value")
    }

    pub fn null_unit(&self) -> MappedType {
        MappedType::plain("()")
    }

    /// One-shot dispatch from `(OpenApiSchemaType, &SchemaDetails)`.
    pub fn map(&self, ty: OpenApiSchemaType, details: &SchemaDetails) -> MappedType {
        let format = details.format.as_deref();
        match ty {
            OpenApiSchemaType::String => self.string_format(format),
            OpenApiSchemaType::Integer => self.integer_format(format),
            OpenApiSchemaType::Number => self.number_format(format),
            OpenApiSchemaType::Boolean => self.boolean(),
            OpenApiSchemaType::Array => self.untyped_array(),
            OpenApiSchemaType::Object => self.dynamic_json(),
            OpenApiSchemaType::Null => self.null_unit(),
        }
    }
}

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

    fn details_with_format(format: Option<&str>) -> SchemaDetails {
        SchemaDetails {
            format: format.map(str::to_string),
            ..Default::default()
        }
    }

    #[test]
    fn default_mapper_emits_typed_scalars_for_common_formats() {
        let m = TypeMapper::default();
        assert_eq!(
            m.string_format(Some("date-time")).rust_type,
            "chrono::DateTime<chrono::Utc>"
        );
        assert_eq!(m.string_format(Some("date")).rust_type, "chrono::NaiveDate");
        assert_eq!(m.string_format(Some("uuid")).rust_type, "uuid::Uuid");
        assert_eq!(m.string_format(Some("uri")).rust_type, "url::Url");
        assert_eq!(
            m.string_format(Some("ipv4")).rust_type,
            "std::net::Ipv4Addr"
        );
        assert_eq!(m.string_format(Some("byte")).rust_type, "Vec<u8>");
        assert_eq!(m.string_format(Some("binary")).rust_type, "bytes::Bytes");
    }

    #[test]
    fn date_time_uses_default_chrono_serde() {
        // chrono::DateTime<Utc> with the `serde` feature serializes
        // as RFC 3339 by default — no `with = ...` codec required.
        let m = TypeMapper::default();
        let mt = m.string_format(Some("date-time"));
        assert_eq!(mt.rust_type, "chrono::DateTime<chrono::Utc>");
        assert!(mt.serde_with.is_none());
        assert_eq!(mt.feature, Some(TypeFeature::Chrono));
    }

    #[test]
    fn byte_emits_base64_codec() {
        let m = TypeMapper::default();
        let mt = m.string_format(Some("byte"));
        assert_eq!(mt.rust_type, "Vec<u8>");
        assert_eq!(mt.serde_with.as_deref(), Some("base64_serde"));
        assert_eq!(mt.feature, Some(TypeFeature::Base64));
    }

    #[test]
    fn conservative_config_collapses_everything_to_string() {
        let m = TypeMapper::new(TypeMappingConfig::conservative());
        for fmt in [
            Some("date-time"),
            Some("uuid"),
            Some("uri"),
            Some("byte"),
            Some("binary"),
            Some("ipv4"),
            Some("ipv6"),
            Some("date"),
            None,
        ] {
            let mt = m.string_format(fmt);
            assert_eq!(mt.rust_type, "String", "format = {fmt:?}");
            assert!(mt.serde_with.is_none(), "format = {fmt:?}");
        }
    }

    #[test]
    fn unknown_formats_fall_through_to_string() {
        let m = TypeMapper::default();
        for fmt in [Some("hostname"), Some("password"), Some("idn-email")] {
            assert_eq!(m.string_format(fmt).rust_type, "String");
        }
    }

    #[test]
    fn integer_formats_match_pre_refactor_behavior() {
        let m = TypeMapper::default();
        assert_eq!(m.integer_format(Some("int32")).rust_type, "i32");
        assert_eq!(m.integer_format(Some("int64")).rust_type, "i64");
        assert_eq!(m.integer_format(None).rust_type, "i64");
    }

    #[test]
    fn integer_formats_default_handles_unsigned_q21() {
        let m = TypeMapper::default();
        assert_eq!(m.integer_format(Some("uint32")).rust_type, "u32");
        assert_eq!(m.integer_format(Some("uint64")).rust_type, "u64");
        // Non-standard `uint` falls into the broader uint64 bucket.
        assert_eq!(m.integer_format(Some("uint")).rust_type, "u64");
    }

    #[test]
    fn unsigned_off_degrades_uint_to_i64() {
        let mut cfg = TypeMappingConfig::default();
        cfg.unsigned = false;
        let m = TypeMapper::new(cfg);
        assert_eq!(m.integer_format(Some("uint32")).rust_type, "i64");
        assert_eq!(m.integer_format(Some("uint64")).rust_type, "i64");
    }

    #[test]
    fn conservative_disables_unsigned() {
        let m = TypeMapper::new(TypeMappingConfig::conservative());
        assert_eq!(m.integer_format(Some("uint64")).rust_type, "i64");
    }

    #[test]
    fn builtin_aliases_normalize_uuid_variants_to_uuid() {
        let m = TypeMapper::default();
        for fmt in ["uuid4", "uuid_v4", "UUID"] {
            let mt = m.string_format(Some(fmt));
            assert_eq!(mt.rust_type, "uuid::Uuid", "format = {fmt}");
        }
    }

    #[test]
    fn builtin_aliases_normalize_unix_time_to_int64() {
        let m = TypeMapper::default();
        for fmt in ["unix-time", "unix_time", "unixtime", "timestamp"] {
            let mt = m.integer_format(Some(fmt));
            assert_eq!(mt.rust_type, "i64", "format = {fmt}");
        }
    }

    #[test]
    fn user_alias_overrides_builtin() {
        let mut cfg = TypeMappingConfig::default();
        // User wants `uuid4` to mean plain string instead of uuid.
        cfg.format_aliases
            .insert("uuid4".to_string(), "hostname".to_string());
        let m = TypeMapper::new(cfg);
        // hostname is unmapped → falls through to String.
        assert_eq!(m.string_format(Some("uuid4")).rust_type, "String");
    }

    #[test]
    fn used_features_records_referenced_crates() {
        let m = TypeMapper::default();
        let _ = m.string_format(Some("date-time"));
        let _ = m.string_format(Some("uuid"));
        let used = m.used_features();
        assert!(used.contains(TypeFeature::Chrono));
        assert!(used.contains(TypeFeature::Uuid));
        assert!(!used.contains(TypeFeature::Bytes));
    }

    #[test]
    fn format_alias_normalizes_before_dispatch() {
        let mut cfg = TypeMappingConfig::default();
        cfg.format_aliases
            .insert("uuid4".to_string(), "uuid".to_string());
        let m = TypeMapper::new(cfg);
        assert_eq!(m.string_format(Some("uuid4")).rust_type, "uuid::Uuid");
    }

    #[test]
    fn conservative_helper_round_trips() {
        let cfg = TypeMappingConfig::conservative();
        assert!(matches!(cfg.date_time, DateStrategy::String));
        assert!(matches!(cfg.uuid, UuidStrategy::String));
    }

    #[test]
    fn dep_requirement_renders_features_list() {
        let dep = TypeFeature::Chrono.dep_requirement();
        assert_eq!(dep.crate_name, "chrono");
        assert_eq!(dep.features, vec!["serde"]);
        assert_eq!(
            dep.to_toml_line(),
            r#"chrono = { version = "0.4", features = ["serde"] }"#
        );
    }

    #[test]
    fn dep_requirement_omits_features_when_none() {
        let dep = TypeFeature::Base64.dep_requirement();
        assert_eq!(dep.to_toml_line(), r#"base64 = "0.22""#);
    }

    #[test]
    fn collect_dep_requirements_is_sorted_and_unique() {
        let mut used = UsedFeatures::default();
        used.insert(TypeFeature::Url);
        used.insert(TypeFeature::Chrono);
        used.insert(TypeFeature::Chrono); // duplicate
        used.insert(TypeFeature::Uuid);
        let deps = collect_dep_requirements(&used);
        assert_eq!(
            deps.iter().map(|d| d.crate_name).collect::<Vec<_>>(),
            vec!["chrono", "url", "uuid"]
        );
    }

    #[test]
    fn render_required_deps_toml_is_none_when_empty() {
        let deps: Vec<DepRequirement> = Vec::new();
        assert!(render_required_deps_toml(&deps).is_none());
    }

    #[test]
    fn render_required_deps_toml_includes_dependencies_block() {
        let deps = vec![
            TypeFeature::Chrono.dep_requirement(),
            TypeFeature::Uuid.dep_requirement(),
        ];
        let toml = render_required_deps_toml(&deps).expect("non-empty");
        assert!(toml.contains("[dependencies]"));
        assert!(toml.contains("chrono = "));
        assert!(toml.contains("uuid = "));
        assert!(toml.contains("# Generated by openapi-to-rust"));
    }

    #[test]
    fn map_dispatches_through_helpers() {
        let m = TypeMapper::default();
        assert_eq!(
            m.map(
                OpenApiSchemaType::String,
                &details_with_format(Some("uuid"))
            )
            .rust_type,
            "uuid::Uuid"
        );
        assert_eq!(
            m.map(
                OpenApiSchemaType::Integer,
                &details_with_format(Some("int32"))
            )
            .rust_type,
            "i32"
        );
    }
}