Skip to main content

openapi_nexus/generators/python/httpx/
emit_models.rs

1//! Model emission for IR schemas (Python dataclasses/enums/aliases).
2//!
3//! Uses sigil-stitch high-level APIs (TypeSpec, FieldSpec, FunSpec, TypeName,
4//! sigil_quote!) for structured code generation with automatic import tracking.
5//! Each schema produces one `.py` file via `FileSpec`.
6
7use crate::codegen::traits::file_writer::FileInfo;
8use crate::ir::types::{
9    IrEnum, IrEnumValueType, IrIntersection, IrObject, IrPrimitive, IrProperty, IrSchema,
10    IrSchemaKind, IrSpec, IrTaggedUnion, IrTaggedVariant, IrTypeExpr, IrUnion, TaggingStyle,
11};
12use heck::{ToPascalCase, ToSnakeCase};
13use sigil_stitch::code_block::CodeBlock;
14use sigil_stitch::lang::python::Python;
15use sigil_stitch::prelude::*;
16
17/// Generate every model file from the IR.
18pub fn generate_model_files(ir: &IrSpec, header: &str) -> Result<Vec<FileInfo>, String> {
19    let mut files = Vec::new();
20    for (_name, schema) in &ir.schemas {
21        let body = emit_model_body(schema, ir).ok_or_else(|| {
22            format!(
23                "unsupported schema kind for {}: {:?}",
24                schema.name, schema.kind
25            )
26        })?;
27        let stem = schema.name.to_snake_case();
28        let filename = format!("{stem}.py");
29        let mut content = String::with_capacity(header.len() + body.len());
30        content.push_str(header);
31        content.push_str(&body);
32        files.push(FileInfo::model(filename, content));
33    }
34    Ok(files)
35}
36
37fn emit_model_body(schema: &IrSchema, ir: &IrSpec) -> Option<String> {
38    let file_spec = match &schema.kind {
39        IrSchemaKind::Object(obj) => emit_object(schema, obj, ir),
40        IrSchemaKind::Enum(en) => emit_enum(schema, en),
41        IrSchemaKind::Alias(expr) => emit_alias(schema, expr),
42        IrSchemaKind::Union(u) => emit_union(schema, u),
43        IrSchemaKind::Intersection(i) => emit_intersection(schema, i, ir),
44        IrSchemaKind::TaggedUnion(tu) => emit_tagged_union(schema, tu, ir),
45    }?;
46    file_spec.render(100).ok()
47}
48
49pub fn future_annotations_header() -> CodeBlock {
50    CodeBlock::of("from __future__ import annotations", ()).expect("static header")
51}
52
53// ---------------------------------------------------------------------------
54// Object -> @dataclass
55// ---------------------------------------------------------------------------
56
57fn emit_object(schema: &IrSchema, obj: &IrObject, ir: &IrSpec) -> Option<FileSpec> {
58    let name = schema.name.to_pascal_case();
59
60    let mut file =
61        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
62
63    if needs_typing_literal_in_props(&obj.properties) {
64        file = file.add_import(ImportSpec::named("typing", "Literal"));
65    }
66
67    let dataclass_tn = TypeName::importable("dataclasses", "dataclass");
68    let mut cls = TypeSpec::builder(&name, TypeKind::Class)
69        .annotate(AnnotationSpec::importable(dataclass_tn));
70
71    if let Some(doc) = &schema.description {
72        cls = cls.doc(&format!("{}.", escape_docstring(doc)));
73    }
74
75    let mut required: Vec<(&String, &IrProperty)> = Vec::new();
76    let mut optional: Vec<(&String, &IrProperty)> = Vec::new();
77    for (json_name, prop) in &obj.properties {
78        if prop.required && !prop.nullable {
79            required.push((json_name, prop));
80        } else {
81            optional.push((json_name, prop));
82        }
83    }
84
85    let all_fields: Vec<(&String, &IrProperty)> =
86        required.iter().chain(optional.iter()).copied().collect();
87
88    if all_fields.is_empty() {
89        cls = cls.extra_member(CodeBlock::of("pass", ()).expect("pass"));
90    } else {
91        for (_json_name, prop) in &required {
92            let field_name = python_field_name(&prop.name);
93            let type_name = python_type_name(&prop.type_expr);
94            cls = cls.add_field(
95                FieldSpec::builder(&field_name, type_name)
96                    .build()
97                    .expect("required field"),
98            );
99        }
100        for (_json_name, prop) in &optional {
101            let field_name = python_field_name(&prop.name);
102            let type_name = python_type_name(&prop.type_expr);
103            cls = cls.add_field(
104                FieldSpec::builder(&field_name, TypeName::optional(type_name))
105                    .initializer(CodeBlock::of("None", ()).expect("None init"))
106                    .build()
107                    .expect("optional field"),
108            );
109        }
110
111        cls = cls.add_method(build_to_dict_method(&all_fields, ir, &obj.properties));
112        cls = cls.add_method(build_from_dict_method(
113            &name,
114            &all_fields,
115            ir,
116            &obj.properties,
117        ));
118    }
119
120    file = file.add_type(cls.build().ok()?);
121    file.build().ok()
122}
123
124fn build_to_dict_method(
125    all_fields: &[(&String, &IrProperty)],
126    ir: &IrSpec,
127    properties: &indexmap::IndexMap<String, IrProperty>,
128) -> FunSpec {
129    let self_param = ParameterSpec::of("self", TypeName::primitive(""));
130    let return_type = TypeName::generic(
131        TypeName::primitive("dict"),
132        vec![TypeName::primitive("str"), TypeName::primitive("object")],
133    );
134
135    let mut body = CodeBlock::builder();
136    body.add_statement("result: dict[str, object] = {}", ());
137    for (json_name, prop) in all_fields {
138        let field_name = python_field_name(&prop.name);
139        let to_expr = render_to_dict_expr(&format!("self.{field_name}"), json_name, ir, properties);
140        if prop.required && !prop.nullable {
141            body.add_statement(&format!("result[\"{json_name}\"] = {to_expr}"), ());
142        } else {
143            body.add_statement(&format!("if self.{field_name} is not None:%>"), ());
144            body.add_statement(&format!("result[\"{json_name}\"] = {to_expr}%<"), ());
145        }
146    }
147    body.add_statement("return result", ());
148
149    FunSpec::builder("to_dict")
150        .add_param(self_param)
151        .returns(return_type)
152        .body(body.build().expect("to_dict body"))
153        .build()
154        .expect("to_dict method")
155}
156
157fn build_from_dict_method(
158    class_name: &str,
159    all_fields: &[(&String, &IrProperty)],
160    ir: &IrSpec,
161    properties: &indexmap::IndexMap<String, IrProperty>,
162) -> FunSpec {
163    let cls_param = ParameterSpec::of("cls", TypeName::primitive(""));
164    let data_param = ParameterSpec::of(
165        "data",
166        TypeName::generic(
167            TypeName::primitive("dict"),
168            vec![TypeName::primitive("str"), TypeName::primitive("object")],
169        ),
170    );
171
172    let mut body = CodeBlock::builder();
173    body.add_statement("return cls(%>", ());
174    for (json_name, prop) in all_fields {
175        let field_name = python_field_name(&prop.name);
176        let is_required = prop.required && !prop.nullable;
177        let expr = if is_required {
178            render_from_dict_expr(json_name, ir, properties)
179        } else {
180            render_from_dict_optional_expr(json_name, ir, properties)
181        };
182        if let Some(comment_start) = expr.find("  #") {
183            let (value_part, comment_part) = expr.split_at(comment_start);
184            body.add_statement(&format!("{field_name}={value_part},{comment_part}"), ());
185        } else {
186            body.add_statement(&format!("{field_name}={expr},"), ());
187        }
188    }
189    body.add("%<", ());
190    body.add_statement(")", ());
191
192    FunSpec::builder("from_dict")
193        .annotation(CodeBlock::of("@classmethod", ()).expect("classmethod"))
194        .add_param(cls_param)
195        .add_param(data_param)
196        .returns(TypeName::primitive(class_name))
197        .body(body.build().expect("from_dict body"))
198        .build()
199        .expect("from_dict method")
200}
201
202// ---------------------------------------------------------------------------
203// Enum -> class(str, Enum) or class(int, Enum)
204// ---------------------------------------------------------------------------
205
206fn emit_enum(schema: &IrSchema, en: &IrEnum) -> Option<FileSpec> {
207    if en.value_type == IrEnumValueType::Mixed {
208        return emit_type_alias_raw(schema, "object");
209    }
210
211    let name = schema.name.to_pascal_case();
212    let base = match en.value_type {
213        IrEnumValueType::String => TypeName::primitive("str"),
214        IrEnumValueType::Integer | IrEnumValueType::Number => TypeName::primitive("int"),
215        IrEnumValueType::Mixed => unreachable!(),
216    };
217
218    let mut ts = TypeSpec::builder(&name, TypeKind::Enum)
219        .extends(base)
220        .extends(TypeName::importable("enum", "Enum"));
221
222    if let Some(doc) = &schema.description {
223        ts = ts.doc(&format!("{}.", escape_docstring(doc)));
224    }
225
226    for v in &en.values {
227        let (member_name, value_code) = match en.value_type {
228            IrEnumValueType::String => {
229                let s = v.value.as_str()?;
230                (
231                    python_enum_member_name(s),
232                    format!("\"{}\"", escape_python_string(s)),
233                )
234            }
235            IrEnumValueType::Integer | IrEnumValueType::Number => {
236                let n = v
237                    .value
238                    .as_i64()
239                    .or_else(|| v.value.as_f64().map(|f| f as i64))?;
240                (format!("N{n}").replace('-', "NEG"), format!("{n}"))
241            }
242            IrEnumValueType::Mixed => unreachable!(),
243        };
244        ts = ts.add_variant(
245            EnumVariantSpec::builder(&member_name)
246                .value(CodeBlock::of(&value_code, ()).expect("enum value"))
247                .build()
248                .expect("enum variant"),
249        );
250    }
251
252    let file = FileSpec::builder_with("model.py", Python::new())
253        .header(future_annotations_header())
254        .add_type(ts.build().ok()?);
255    file.build().ok()
256}
257
258// ---------------------------------------------------------------------------
259// Alias -> type X = Y (PEP 695)
260// ---------------------------------------------------------------------------
261
262fn emit_alias(schema: &IrSchema, expr: &IrTypeExpr) -> Option<FileSpec> {
263    let name = schema.name.to_pascal_case();
264    let rhs_type = python_type_name(expr);
265
266    let type_alias = sigil_quote!(Python {
267        type $N(name.as_str()) = $T(rhs_type);
268    })
269    .ok()?;
270
271    let mut file =
272        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
273    if needs_typing_literal(expr) {
274        file = file.add_import(ImportSpec::named("typing", "Literal"));
275    }
276    if let Some(doc) = &schema.description {
277        file = file.add_raw(&format!("# {}\n", escape_docstring(doc)));
278    }
279    file = file.add_code(type_alias);
280    file.build().ok()
281}
282
283fn emit_type_alias_raw(schema: &IrSchema, rhs: &str) -> Option<FileSpec> {
284    let name = schema.name.to_pascal_case();
285
286    let type_alias = sigil_quote!(Python {
287        type $N(name.as_str()) = $L(rhs);
288    })
289    .ok()?;
290
291    let mut file =
292        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
293    if let Some(doc) = &schema.description {
294        file = file.add_raw(&format!("# {}\n", escape_docstring(doc)));
295    }
296    file = file.add_code(type_alias);
297    file.build().ok()
298}
299
300// ---------------------------------------------------------------------------
301// Union -> type X = A | B | C
302// ---------------------------------------------------------------------------
303
304fn emit_union(schema: &IrSchema, u: &IrUnion) -> Option<FileSpec> {
305    let name = schema.name.to_pascal_case();
306
307    let mut members: Vec<TypeName> = u.members.iter().map(python_type_name).collect();
308    if u.nullable {
309        members.push(TypeName::primitive("None"));
310    }
311    let union_ty = if members.is_empty() {
312        TypeName::importable("typing", "Any")
313    } else {
314        TypeName::union(members)
315    };
316
317    let type_alias = sigil_quote!(Python {
318        type $N(name.as_str()) = $T(union_ty);
319    })
320    .ok()?;
321
322    let mut file =
323        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
324    if needs_typing_literal_in_exprs(&u.members) {
325        file = file.add_import(ImportSpec::named("typing", "Literal"));
326    }
327    if let Some(doc) = &schema.description {
328        file = file.add_raw(&format!("# {}\n", escape_docstring(doc)));
329    }
330    file = file.add_code(type_alias);
331    file.build().ok()
332}
333
334// ---------------------------------------------------------------------------
335// Intersection -> merged @dataclass
336// ---------------------------------------------------------------------------
337
338fn emit_intersection(schema: &IrSchema, inter: &IrIntersection, ir: &IrSpec) -> Option<FileSpec> {
339    let mut all_props: indexmap::IndexMap<String, IrProperty> = indexmap::IndexMap::new();
340    for member in &inter.members {
341        if let IrTypeExpr::Named(ref_name) = member
342            && let Some(s) = ir.schemas.get(ref_name.as_str())
343            && let IrSchemaKind::Object(obj) = &s.kind
344        {
345            for (k, v) in &obj.properties {
346                all_props.entry(k.clone()).or_insert_with(|| v.clone());
347            }
348        }
349    }
350
351    if all_props.is_empty() {
352        return emit_intersection_as_alias(schema, inter);
353    }
354
355    emit_intersection_as_dataclass(schema, &all_props)
356}
357
358fn emit_intersection_as_alias(schema: &IrSchema, inter: &IrIntersection) -> Option<FileSpec> {
359    let name = schema.name.to_pascal_case();
360    let members: Vec<TypeName> = inter.members.iter().map(python_type_name).collect();
361    let union_ty = if members.is_empty() {
362        TypeName::importable("typing", "Any")
363    } else {
364        TypeName::union(members)
365    };
366
367    let type_alias = sigil_quote!(Python {
368        type $N(name.as_str()) = $T(union_ty);
369    })
370    .ok()?;
371
372    let mut file =
373        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
374    if needs_typing_literal_in_exprs(&inter.members) {
375        file = file.add_import(ImportSpec::named("typing", "Literal"));
376    }
377    file = file.add_code(type_alias);
378    file.build().ok()
379}
380
381fn emit_intersection_as_dataclass(
382    schema: &IrSchema,
383    all_props: &indexmap::IndexMap<String, IrProperty>,
384) -> Option<FileSpec> {
385    let name = schema.name.to_pascal_case();
386
387    let mut file =
388        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
389
390    if needs_typing_literal_in_props(all_props) {
391        file = file.add_import(ImportSpec::named("typing", "Literal"));
392    }
393
394    let dataclass_tn = TypeName::importable("dataclasses", "dataclass");
395    let mut cls = TypeSpec::builder(&name, TypeKind::Class)
396        .annotate(AnnotationSpec::importable(dataclass_tn));
397
398    if let Some(doc) = &schema.description {
399        cls = cls.doc(&format!("{}.", escape_docstring(doc)));
400    }
401
402    let mut required: Vec<(&String, &IrProperty)> = Vec::new();
403    let mut optional: Vec<(&String, &IrProperty)> = Vec::new();
404    for (json_name, prop) in all_props {
405        if prop.required && !prop.nullable {
406            required.push((json_name, prop));
407        } else {
408            optional.push((json_name, prop));
409        }
410    }
411
412    if required.is_empty() && optional.is_empty() {
413        cls = cls.extra_member(CodeBlock::of("pass", ()).expect("pass"));
414    } else {
415        for (_json_name, prop) in &required {
416            let field_name = python_field_name(&prop.name);
417            let type_name = python_type_name(&prop.type_expr);
418            cls = cls.add_field(
419                FieldSpec::builder(&field_name, type_name)
420                    .build()
421                    .expect("required field"),
422            );
423        }
424        for (_json_name, prop) in &optional {
425            let field_name = python_field_name(&prop.name);
426            let type_name = python_type_name(&prop.type_expr);
427            cls = cls.add_field(
428                FieldSpec::builder(&field_name, TypeName::optional(type_name))
429                    .initializer(CodeBlock::of("None", ()).expect("None init"))
430                    .build()
431                    .expect("optional field"),
432            );
433        }
434    }
435
436    file = file.add_type(cls.build().ok()?);
437    file.build().ok()
438}
439
440// ---------------------------------------------------------------------------
441// TaggedUnion -> type X = A | B | C
442// ---------------------------------------------------------------------------
443
444fn emit_tagged_union(schema: &IrSchema, tu: &IrTaggedUnion, ir: &IrSpec) -> Option<FileSpec> {
445    let name = schema.name.to_pascal_case();
446    let snake_name = schema.name.to_snake_case();
447
448    let members: Vec<TypeName> = tu
449        .variants
450        .iter()
451        .map(|v| python_type_name(&v.content_type))
452        .collect();
453
454    let union_ty = if members.is_empty() {
455        TypeName::importable("typing", "Any")
456    } else {
457        TypeName::union(members)
458    };
459
460    let type_alias = sigil_quote!(Python {
461        type $N(name.as_str()) = $T(union_ty);
462    })
463    .ok()?;
464
465    let hint = match &tu.tagging {
466        TaggingStyle::Internal => {
467            format!("Discriminator: {} (internal).", tu.discriminator_field)
468        }
469        TaggingStyle::Adjacent { content_field } => format!(
470            "Discriminator: {} / content: {} (adjacent).",
471            tu.discriminator_field, content_field
472        ),
473        TaggingStyle::External => "Discriminator: variant key (external).".to_string(),
474    };
475
476    let doc = match &schema.description {
477        Some(desc) => format!("{desc}\n\n{hint}"),
478        None => hint,
479    };
480
481    let mut file =
482        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
483    let exprs: Vec<&IrTypeExpr> = tu.variants.iter().map(|v| &v.content_type).collect();
484    if exprs.iter().any(|e| needs_typing_literal(e)) {
485        file = file.add_import(ImportSpec::named("typing", "Literal"));
486    }
487    let mut doc_block = String::new();
488    for line in doc.lines() {
489        doc_block.push_str(&format!("# {line}\n"));
490    }
491    file = file.add_raw(&doc_block);
492    file = file.add_code(type_alias);
493
494    if !tu.variants.is_empty() {
495        let helpers = build_tagged_union_helpers(&name, &snake_name, tu, ir);
496        file = file.add_raw(&helpers);
497    }
498
499    file.build().ok()
500}
501
502fn build_tagged_union_helpers(
503    pascal_name: &str,
504    snake_name: &str,
505    tu: &IrTaggedUnion,
506    ir: &IrSpec,
507) -> String {
508    let mut out = String::new();
509    let tag_field = &tu.discriminator_field;
510
511    // Only generate helpers for variants that resolve to Object schemas
512    let resolved_variants: Vec<(&IrTaggedVariant, String)> = tu
513        .variants
514        .iter()
515        .filter_map(|v| {
516            if let IrTypeExpr::Named(ref_name) = &v.content_type
517                && is_object_schema(ref_name, ir)
518            {
519                return Some((v, ref_name.to_pascal_case()));
520            }
521            None
522        })
523        .collect();
524
525    if resolved_variants.is_empty() {
526        return out;
527    }
528
529    // from_dict
530    out.push('\n');
531    out.push_str(&format!(
532        "def {snake_name}_from_dict(data: dict[str, object]) -> {pascal_name}:\n"
533    ));
534    match &tu.tagging {
535        TaggingStyle::Internal => {
536            out.push_str(&format!("    _tag = data[\"{tag_field}\"]\n"));
537            for (i, (variant, py_class)) in resolved_variants.iter().enumerate() {
538                let kw = if i == 0 { "if" } else { "elif" };
539                out.push_str(&format!(
540                    "    {kw} _tag == \"{}\":\n        return {py_class}.from_dict(data)\n",
541                    variant.discriminator_value
542                ));
543            }
544        }
545        TaggingStyle::Adjacent { content_field } => {
546            out.push_str(&format!("    _tag = data[\"{tag_field}\"]\n"));
547            out.push_str(&format!(
548                "    _content = data[\"{content_field}\"]  # type: ignore[assignment]\n"
549            ));
550            for (i, (variant, py_class)) in resolved_variants.iter().enumerate() {
551                let kw = if i == 0 { "if" } else { "elif" };
552                out.push_str(&format!(
553                    "    {kw} _tag == \"{}\":\n        return {py_class}.from_dict(_content)  # type: ignore[arg-type]\n",
554                    variant.discriminator_value
555                ));
556            }
557        }
558        TaggingStyle::External => {
559            for (i, (variant, py_class)) in resolved_variants.iter().enumerate() {
560                let kw = if i == 0 { "if" } else { "elif" };
561                out.push_str(&format!(
562                    "    {kw} \"{}\" in data:\n        return {py_class}.from_dict(data[\"{}\"])  # type: ignore[arg-type]\n",
563                    variant.discriminator_value, variant.discriminator_value
564                ));
565            }
566        }
567    }
568    out.push_str(&format!(
569        "    raise ValueError(f\"Unknown discriminator value for {pascal_name}: {{data}}\")\n"
570    ));
571
572    // to_dict
573    out.push('\n');
574    out.push_str(&format!(
575        "def {snake_name}_to_dict(obj: {pascal_name}) -> dict[str, object]:\n"
576    ));
577    let last_idx = resolved_variants.len() - 1;
578    match &tu.tagging {
579        TaggingStyle::Internal => {
580            for (i, (variant, py_class)) in resolved_variants.iter().enumerate() {
581                let kw = if i == 0 { "if" } else { "elif" };
582                let ignore = if i == last_idx {
583                    "  # type: ignore[reportUnnecessaryIsInstance]"
584                } else {
585                    ""
586                };
587                out.push_str(&format!("    {kw} isinstance(obj, {py_class}):{ignore}\n"));
588                out.push_str("        result = obj.to_dict()\n");
589                out.push_str(&format!(
590                    "        result[\"{tag_field}\"] = \"{}\"\n",
591                    variant.discriminator_value
592                ));
593                out.push_str("        return result\n");
594            }
595        }
596        TaggingStyle::Adjacent { content_field } => {
597            for (i, (variant, py_class)) in resolved_variants.iter().enumerate() {
598                let kw = if i == 0 { "if" } else { "elif" };
599                let ignore = if i == last_idx {
600                    "  # type: ignore[reportUnnecessaryIsInstance]"
601                } else {
602                    ""
603                };
604                out.push_str(&format!("    {kw} isinstance(obj, {py_class}):{ignore}\n"));
605                out.push_str(&format!(
606                    "        return {{\"{tag_field}\": \"{}\", \"{content_field}\": obj.to_dict()}}\n",
607                    variant.discriminator_value
608                ));
609            }
610        }
611        TaggingStyle::External => {
612            for (i, (variant, py_class)) in resolved_variants.iter().enumerate() {
613                let kw = if i == 0 { "if" } else { "elif" };
614                let ignore = if i == last_idx {
615                    "  # type: ignore[reportUnnecessaryIsInstance]"
616                } else {
617                    ""
618                };
619                out.push_str(&format!("    {kw} isinstance(obj, {py_class}):{ignore}\n"));
620                out.push_str(&format!(
621                    "        return {{\"{}\": obj.to_dict()}}\n",
622                    variant.discriminator_value
623                ));
624            }
625        }
626    }
627    out.push_str(&format!(
628        "    raise ValueError(f\"Unknown variant for {pascal_name}: {{type(obj)}}\")\n"
629    ));
630
631    out
632}
633
634// ---------------------------------------------------------------------------
635// Type mapping
636// ---------------------------------------------------------------------------
637
638/// Map an IR type expression to a sigil-stitch TypeName with auto-import tracking.
639pub fn python_type_name(expr: &IrTypeExpr) -> TypeName {
640    match expr {
641        IrTypeExpr::Named(name) => {
642            let py_name = name.to_pascal_case();
643            let module = format!(".{}", name.to_snake_case());
644            TypeName::importable(&module, &py_name)
645        }
646        IrTypeExpr::Primitive(p) => python_primitive_type_name(p),
647        IrTypeExpr::StringLiteral(s) => {
648            let lit = format!("Literal[\"{}\"]", escape_python_string(s));
649            TypeName::raw(&lit)
650        }
651        IrTypeExpr::StringEnum(values) => {
652            let members: Vec<String> = values
653                .iter()
654                .map(|v| format!("\"{}\"", escape_python_string(v)))
655                .collect();
656            let lit = format!("Literal[{}]", members.join(", "));
657            TypeName::raw(&lit)
658        }
659        IrTypeExpr::Array(inner) => {
660            TypeName::generic(TypeName::primitive("list"), vec![python_type_name(inner)])
661        }
662        IrTypeExpr::Map(inner) => TypeName::generic(
663            TypeName::primitive("dict"),
664            vec![TypeName::primitive("str"), python_type_name(inner)],
665        ),
666        IrTypeExpr::Union(members) => {
667            if members.is_empty() {
668                TypeName::importable("typing", "Any")
669            } else {
670                TypeName::union(members.iter().map(python_type_name).collect())
671            }
672        }
673        IrTypeExpr::Nullable(inner) => TypeName::optional(python_type_name(inner)),
674        IrTypeExpr::Any => TypeName::importable("typing", "Any"),
675    }
676}
677
678/// Like `python_type_name` but Named types import from `..models.{snake}` (for API files).
679pub fn api_type_name(expr: &IrTypeExpr) -> TypeName {
680    match expr {
681        IrTypeExpr::Named(name) => {
682            let py_name = name.to_pascal_case();
683            let module = format!("..models.{}", name.to_snake_case());
684            TypeName::importable(&module, &py_name)
685        }
686        IrTypeExpr::Array(inner) => {
687            TypeName::generic(TypeName::primitive("list"), vec![api_type_name(inner)])
688        }
689        IrTypeExpr::Map(inner) => TypeName::generic(
690            TypeName::primitive("dict"),
691            vec![TypeName::primitive("str"), api_type_name(inner)],
692        ),
693        IrTypeExpr::Union(members) => {
694            if members.is_empty() {
695                TypeName::importable("typing", "Any")
696            } else {
697                TypeName::union(members.iter().map(api_type_name).collect())
698            }
699        }
700        IrTypeExpr::Nullable(inner) => TypeName::optional(api_type_name(inner)),
701        _ => python_type_name(expr),
702    }
703}
704
705fn python_primitive_type_name(p: &IrPrimitive) -> TypeName {
706    match p {
707        IrPrimitive::String | IrPrimitive::StringWithFormat(_) => TypeName::primitive("str"),
708        IrPrimitive::Integer | IrPrimitive::IntegerWithFormat(_) => TypeName::primitive("int"),
709        IrPrimitive::Number | IrPrimitive::NumberWithFormat(_) => TypeName::primitive("float"),
710        IrPrimitive::Boolean => TypeName::primitive("bool"),
711        IrPrimitive::Binary => TypeName::primitive("bytes"),
712        IrPrimitive::Date => TypeName::importable("datetime", "date"),
713        IrPrimitive::DateTime => TypeName::importable("datetime", "datetime"),
714        IrPrimitive::Uuid => TypeName::importable("uuid", "UUID"),
715    }
716}
717
718/// Map an IR type expression to a Python type string (for serialization helpers).
719pub fn python_type_str(expr: &IrTypeExpr) -> String {
720    match expr {
721        IrTypeExpr::Named(name) => name.to_pascal_case(),
722        IrTypeExpr::Primitive(p) => python_primitive(p).to_string(),
723        IrTypeExpr::StringLiteral(s) => {
724            format!("Literal[\"{}\"]", escape_python_string(s))
725        }
726        IrTypeExpr::StringEnum(values) => {
727            let members: Vec<String> = values
728                .iter()
729                .map(|v| format!("\"{}\"", escape_python_string(v)))
730                .collect();
731            format!("Literal[{}]", members.join(", "))
732        }
733        IrTypeExpr::Array(inner) => {
734            let inner_ty = python_type_str(inner);
735            format!("list[{inner_ty}]")
736        }
737        IrTypeExpr::Map(inner) => {
738            let inner_ty = python_type_str(inner);
739            format!("dict[str, {inner_ty}]")
740        }
741        IrTypeExpr::Union(members) => {
742            let parts: Vec<String> = members.iter().map(python_type_str).collect();
743            if parts.is_empty() {
744                "Any".to_string()
745            } else {
746                parts.join(" | ")
747            }
748        }
749        IrTypeExpr::Nullable(inner) => {
750            let inner_ty = python_type_str(inner);
751            format!("{inner_ty} | None")
752        }
753        IrTypeExpr::Any => "Any".to_string(),
754    }
755}
756
757fn python_primitive(p: &IrPrimitive) -> &'static str {
758    match p {
759        IrPrimitive::String | IrPrimitive::StringWithFormat(_) => "str",
760        IrPrimitive::Integer | IrPrimitive::IntegerWithFormat(_) => "int",
761        IrPrimitive::Number | IrPrimitive::NumberWithFormat(_) => "float",
762        IrPrimitive::Boolean => "bool",
763        IrPrimitive::Binary => "bytes",
764        IrPrimitive::Date => "datetime.date",
765        IrPrimitive::DateTime => "datetime.datetime",
766        IrPrimitive::Uuid => "uuid.UUID",
767    }
768}
769
770fn needs_typing_literal(expr: &IrTypeExpr) -> bool {
771    match expr {
772        IrTypeExpr::StringLiteral(_) | IrTypeExpr::StringEnum(_) => true,
773        IrTypeExpr::Array(inner) | IrTypeExpr::Map(inner) | IrTypeExpr::Nullable(inner) => {
774            needs_typing_literal(inner)
775        }
776        IrTypeExpr::Union(members) => members.iter().any(needs_typing_literal),
777        _ => false,
778    }
779}
780
781fn needs_typing_literal_in_props(props: &indexmap::IndexMap<String, IrProperty>) -> bool {
782    props.values().any(|p| needs_typing_literal(&p.type_expr))
783}
784
785fn needs_typing_literal_in_exprs(exprs: &[IrTypeExpr]) -> bool {
786    exprs.iter().any(needs_typing_literal)
787}
788
789// ---------------------------------------------------------------------------
790// Serialization helpers
791// ---------------------------------------------------------------------------
792
793fn render_to_dict_expr(
794    value_expr: &str,
795    json_name: &str,
796    ir: &IrSpec,
797    properties: &indexmap::IndexMap<String, IrProperty>,
798) -> String {
799    let prop = properties.get(json_name);
800    let type_expr = prop.map(|p| &p.type_expr);
801    match type_expr {
802        Some(IrTypeExpr::Named(ref_name)) => {
803            if is_object_schema(ref_name, ir) {
804                format!("{value_expr}.to_dict()")
805            } else {
806                value_expr.to_string()
807            }
808        }
809        Some(IrTypeExpr::Array(inner)) => {
810            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
811                && is_object_schema(ref_name, ir)
812            {
813                return format!("[item.to_dict() for item in {value_expr}]");
814            }
815            value_expr.to_string()
816        }
817        Some(IrTypeExpr::Nullable(inner)) => {
818            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
819                && is_object_schema(ref_name, ir)
820            {
821                return format!("{value_expr}.to_dict() if {value_expr} is not None else None");
822            }
823            value_expr.to_string()
824        }
825        _ => value_expr.to_string(),
826    }
827}
828
829fn render_from_dict_expr(
830    json_name: &str,
831    ir: &IrSpec,
832    properties: &indexmap::IndexMap<String, IrProperty>,
833) -> String {
834    let prop = properties.get(json_name);
835    let type_expr = prop.map(|p| &p.type_expr);
836    let accessor = format!("data[\"{json_name}\"]");
837    match type_expr {
838        Some(IrTypeExpr::Named(ref_name)) => {
839            if is_object_schema(ref_name, ir) {
840                let py_name = ref_name.to_pascal_case();
841                format!("{py_name}.from_dict({accessor})  # type: ignore[arg-type]")
842            } else {
843                format!("{accessor}  # type: ignore[assignment]")
844            }
845        }
846        Some(IrTypeExpr::Array(inner)) => {
847            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
848                && is_object_schema(ref_name, ir)
849            {
850                let py_name = ref_name.to_pascal_case();
851                return format!(
852                    "[{py_name}.from_dict(item) for item in {accessor}]  # type: ignore[union-attr]"
853                );
854            }
855            format!("{accessor}  # type: ignore[assignment]")
856        }
857        _ => format!("{accessor}  # type: ignore[assignment]"),
858    }
859}
860
861fn render_from_dict_optional_expr(
862    json_name: &str,
863    ir: &IrSpec,
864    properties: &indexmap::IndexMap<String, IrProperty>,
865) -> String {
866    let prop = properties.get(json_name);
867    let type_expr = prop.map(|p| &p.type_expr);
868    let raw_type = type_expr.map(|t| match t {
869        IrTypeExpr::Nullable(inner) => inner.as_ref(),
870        _ => t,
871    });
872    let accessor = format!("data.get(\"{json_name}\")");
873    match raw_type {
874        Some(IrTypeExpr::Named(ref_name)) => {
875            if is_object_schema(ref_name, ir) {
876                let py_name = ref_name.to_pascal_case();
877                format!(
878                    "{py_name}.from_dict({accessor}) if {accessor} is not None else None  # type: ignore[arg-type]"
879                )
880            } else {
881                format!("{accessor}  # type: ignore[assignment]")
882            }
883        }
884        Some(IrTypeExpr::Array(inner)) => {
885            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
886                && is_object_schema(ref_name, ir)
887            {
888                let py_name = ref_name.to_pascal_case();
889                return format!(
890                    "[{py_name}.from_dict(item) for item in {accessor}] if {accessor} is not None else None  # type: ignore[union-attr]"
891                );
892            }
893            format!("{accessor}  # type: ignore[assignment]")
894        }
895        _ => format!("{accessor}  # type: ignore[assignment]"),
896    }
897}
898
899pub fn is_object_schema(name: &str, ir: &IrSpec) -> bool {
900    ir.schemas
901        .get(name)
902        .is_some_and(|s| matches!(s.kind, IrSchemaKind::Object(_)))
903}
904
905// ---------------------------------------------------------------------------
906// Helpers
907// ---------------------------------------------------------------------------
908
909pub fn python_field_name(name: &str) -> String {
910    let snake = name.to_snake_case();
911    if snake.is_empty() {
912        return "field_".to_string();
913    }
914    match snake.as_str() {
915        "and" | "as" | "assert" | "async" | "await" | "break" | "class" | "continue" | "def"
916        | "del" | "elif" | "else" | "except" | "finally" | "for" | "from" | "global" | "if"
917        | "import" | "in" | "is" | "lambda" | "nonlocal" | "not" | "or" | "pass" | "raise"
918        | "return" | "try" | "while" | "with" | "yield" | "type" => {
919            format!("{snake}_")
920        }
921        _ => snake,
922    }
923}
924
925fn python_enum_member_name(value: &str) -> String {
926    let upper = value
927        .to_uppercase()
928        .replace(|c: char| !c.is_alphanumeric(), "_");
929    if upper.is_empty() {
930        return "EMPTY".to_string();
931    }
932    if upper.starts_with(|c: char| c.is_ascii_digit()) {
933        return format!("N{upper}");
934    }
935    upper
936}
937
938fn escape_python_string(s: &str) -> String {
939    s.replace('\\', "\\\\").replace('"', "\\\"")
940}
941
942fn escape_docstring(s: &str) -> String {
943    s.replace("\"\"\"", "\\\"\\\"\\\"")
944        .lines()
945        .next()
946        .unwrap_or("")
947        .to_string()
948}