normalize-openapi 0.3.2

OpenAPI client code generation
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
//! OpenAPI client code generation.
//!
//! Trait-based design allows multiple implementations per language/framework.
//!
//! # Extensibility
//!
//! Users can register custom generators via [`register()`]:
//!
//! ```ignore
//! use normalize_openapi::{OpenApiClientGenerator, register};
//! use serde_json::Value;
//!
//! struct MyGenerator;
//!
//! impl OpenApiClientGenerator for MyGenerator {
//!     fn language(&self) -> &'static str { "mylang" }
//!     fn variant(&self) -> &'static str { "myvariant" }
//!     fn generate(&self, spec: &Value) -> String { /* ... */ }
//! }
//!
//! // Register before first use
//! register(&MyGenerator);
//! ```

use serde_json::Value;
use std::sync::{OnceLock, RwLock};

/// A code generator for a specific language/framework.
pub trait OpenApiClientGenerator: Send + Sync {
    /// Language name (e.g., "typescript", "python")
    fn language(&self) -> &'static str;

    /// Framework/variant name (e.g., "fetch", "axios", "urllib")
    fn variant(&self) -> &'static str;

    /// Generate client code from OpenAPI JSON.
    fn generate(&self, spec: &Value) -> String;
}

/// Global registry of generator plugins.
static GENERATORS: RwLock<Vec<&'static dyn OpenApiClientGenerator>> = RwLock::new(Vec::new());
static INITIALIZED: OnceLock<()> = OnceLock::new();

/// Register a custom generator plugin.
///
/// Call this before any generation operations to add custom generators.
/// Built-in generators are registered automatically on first use.
pub fn register(generator: &'static dyn OpenApiClientGenerator) {
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    GENERATORS.write().unwrap().push(generator);
}

/// Initialize built-in generators (called automatically on first use).
fn init_builtin() {
    INITIALIZED.get_or_init(|| {
        // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
        let mut generators = GENERATORS.write().unwrap();
        static TS: TypeScriptFetch = TypeScriptFetch;
        static PY: PythonUrllib = PythonUrllib;
        static RS: RustUreq = RustUreq;
        generators.push(&TS);
        generators.push(&PY);
        generators.push(&RS);
    });
}

/// Get a generator by language from the global registry (returns first match).
pub fn get_generator(lang: &str) -> Option<&'static dyn OpenApiClientGenerator> {
    init_builtin();
    let lang_lower = lang.to_lowercase();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    GENERATORS
        .read()
        .unwrap()
        .iter()
        .find(|g| {
            g.language() == lang_lower
                || (lang_lower == "ts" && g.language() == "typescript")
                || (lang_lower == "py" && g.language() == "python")
                || (lang_lower == "rs" && g.language() == "rust")
        })
        .copied()
}

/// List all available generators (language, variant) from the global registry.
pub fn list_generators() -> Vec<(&'static str, &'static str)> {
    init_builtin();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    GENERATORS
        .read()
        .unwrap()
        .iter()
        .map(|g| (g.language(), g.variant()))
        .collect()
}

// Backwards-compatible aliases
/// Find a generator by language (alias for get_generator, returns Box for compatibility).
pub fn find_generator(lang: &str) -> Option<Box<dyn OpenApiClientGenerator>> {
    get_generator(lang).map(|g| Box::new(GeneratorWrapper(g)) as Box<dyn OpenApiClientGenerator>)
}

struct GeneratorWrapper(&'static dyn OpenApiClientGenerator);

impl OpenApiClientGenerator for GeneratorWrapper {
    fn language(&self) -> &'static str {
        self.0.language()
    }

    fn variant(&self) -> &'static str {
        self.0.variant()
    }

    fn generate(&self, spec: &Value) -> String {
        self.0.generate(spec)
    }
}

/// Registry of available generators (returns boxed generators for compatibility).
pub fn generators() -> Vec<Box<dyn OpenApiClientGenerator>> {
    init_builtin();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    GENERATORS
        .read()
        .unwrap()
        .iter()
        .map(|g| Box::new(GeneratorWrapper(*g)) as Box<dyn OpenApiClientGenerator>)
        .collect()
}

// --- TypeScript (fetch) ---

struct TypeScriptFetch;

impl OpenApiClientGenerator for TypeScriptFetch {
    fn language(&self) -> &'static str {
        "typescript"
    }
    fn variant(&self) -> &'static str {
        "fetch"
    }

    fn generate(&self, spec: &Value) -> String {
        let mut out = String::new();
        out.push_str("// Auto-generated from OpenAPI spec\n");
        out.push_str("// Uses fetch (built-in)\n\n");

        // Generate interfaces from schemas
        if let Some(schemas) = spec
            .pointer("/components/schemas")
            .and_then(|s| s.as_object())
        {
            for (name, schema) in schemas {
                out.push_str(&format!("export interface {} {{\n", name));
                if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
                    let required: Vec<&str> = schema
                        .get("required")
                        .and_then(|r| r.as_array())
                        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
                        .unwrap_or_default();
                    for (prop_name, prop) in props {
                        let ts_type = json_schema_to_ts(prop);
                        let opt = if required.contains(&prop_name.as_str()) {
                            ""
                        } else {
                            "?"
                        };
                        out.push_str(&format!("  {}{}: {};\n", prop_name, opt, ts_type));
                    }
                }
                out.push_str("}\n\n");
            }
        }

        // Generate client class
        out.push_str("export class ApiClient {\n");
        out.push_str("  constructor(private baseUrl = 'http://localhost:8080') {}\n\n");
        out.push_str("  private async request<T>(path: string, params?: Record<string, string | number | undefined>): Promise<T> {\n");
        out.push_str("    const url = new URL(path, this.baseUrl);\n");
        out.push_str("    if (params) {\n");
        out.push_str("      for (const [k, v] of Object.entries(params)) {\n");
        out.push_str("        if (v !== undefined) url.searchParams.set(k, String(v));\n");
        out.push_str("      }\n");
        out.push_str("    }\n");
        out.push_str("    const res = await fetch(url.toString());\n");
        out.push_str("    if (!res.ok) throw new Error(`HTTP ${res.status}`);\n");
        out.push_str("    return await res.json() as T;\n");
        out.push_str("  }\n\n");

        // Generate methods from paths
        if let Some(paths) = spec.get("paths").and_then(|p| p.as_object()) {
            for (path, methods) in paths {
                if let Some(op) = methods.get("get").and_then(|g| g.as_object()) {
                    let op_id = op
                        .get("operationId")
                        .and_then(|id| id.as_str())
                        .unwrap_or("unknown");
                    let params = op
                        .get("parameters")
                        .and_then(|p| p.as_array())
                        .map(|a| a.as_slice())
                        .unwrap_or(&[]);

                    let path_params: Vec<&str> = params
                        .iter()
                        .filter(|p| p.get("in").and_then(|i| i.as_str()) == Some("path"))
                        .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
                        .collect();
                    let query_params: Vec<&str> = params
                        .iter()
                        .filter(|p| p.get("in").and_then(|i| i.as_str()) == Some("query"))
                        .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
                        .collect();

                    // Response type from nested path
                    let op_value = Value::Object(op.clone());
                    let resp_type = op_value
                        .pointer("/responses/200/content/application~1json/schema")
                        .map(json_schema_to_ts)
                        .unwrap_or_else(|| "void".to_string());

                    let mut args = Vec::new();
                    for p in &path_params {
                        args.push(format!("{}: string", p));
                    }
                    if !query_params.is_empty() {
                        let opts: Vec<String> = query_params
                            .iter()
                            .map(|p| format!("{}?: string | number", p))
                            .collect();
                        args.push(format!("options?: {{ {} }}", opts.join("; ")));
                    }

                    let url_template = path.replace('{', "${");
                    let call_params = if query_params.is_empty() {
                        ""
                    } else {
                        ", options"
                    };

                    out.push_str(&format!(
                        "  async {}({}): Promise<{}> {{\n",
                        op_id,
                        args.join(", "),
                        resp_type
                    ));
                    out.push_str(&format!(
                        "    return this.request<{}>(`{}`{});\n",
                        resp_type, url_template, call_params
                    ));
                    out.push_str("  }\n\n");
                }
            }
        }

        out.push_str("}\n");
        out
    }
}

// --- Python (urllib) ---

struct PythonUrllib;

impl OpenApiClientGenerator for PythonUrllib {
    fn language(&self) -> &'static str {
        "python"
    }
    fn variant(&self) -> &'static str {
        "urllib"
    }

    fn generate(&self, spec: &Value) -> String {
        let mut out = String::new();
        out.push_str("# Auto-generated from OpenAPI spec\n");
        out.push_str("# Uses urllib (stdlib)\n\n");
        out.push_str("from dataclasses import dataclass\n");
        out.push_str("from typing import Any, Optional\n");
        out.push_str("from urllib.parse import urlencode\n");
        out.push_str("from urllib.request import urlopen\n");
        out.push_str("import json\n\n\n");

        // Generate dataclasses from schemas
        if let Some(schemas) = spec
            .pointer("/components/schemas")
            .and_then(|s| s.as_object())
        {
            for (name, schema) in schemas {
                out.push_str("@dataclass\n");
                out.push_str(&format!("class {}:\n", name));
                if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
                    let required: Vec<&str> = schema
                        .get("required")
                        .and_then(|r| r.as_array())
                        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
                        .unwrap_or_default();

                    // Required fields first
                    for (prop_name, prop) in props {
                        if required.contains(&prop_name.as_str()) {
                            let py_type = json_schema_to_py(prop);
                            out.push_str(&format!("    {}: {}\n", prop_name, py_type));
                        }
                    }
                    // Optional fields
                    for (prop_name, prop) in props {
                        if !required.contains(&prop_name.as_str()) {
                            let py_type = json_schema_to_py(prop);
                            out.push_str(&format!(
                                "    {}: Optional[{}] = None\n",
                                prop_name, py_type
                            ));
                        }
                    }
                    if props.is_empty() {
                        out.push_str("    pass\n");
                    }
                } else {
                    out.push_str("    pass\n");
                }
                out.push_str("\n\n");
            }
        }

        // Generate client class
        out.push_str("class ApiClient:\n");
        out.push_str("    def __init__(self, base_url: str = 'http://localhost:8080'):\n");
        out.push_str("        self.base_url = base_url.rstrip('/')\n\n");
        out.push_str("    def _request(self, path: str, params: Optional[dict] = None) -> dict:\n");
        out.push_str("        url = f'{self.base_url}{path}'\n");
        out.push_str("        if params:\n");
        out.push_str("            filtered = {k: v for k, v in params.items() if v is not None}\n");
        out.push_str("            if filtered:\n");
        out.push_str("                url = f'{url}?{urlencode(filtered)}'\n");
        out.push_str("        with urlopen(url) as response:\n");
        out.push_str("            return json.load(response)\n\n");

        // Generate methods from paths
        if let Some(paths) = spec.get("paths").and_then(|p| p.as_object()) {
            for (path, methods) in paths {
                if let Some(op) = methods.get("get").and_then(|g| g.as_object()) {
                    let op_id = op
                        .get("operationId")
                        .and_then(|id| id.as_str())
                        .unwrap_or("unknown");
                    let params = op
                        .get("parameters")
                        .and_then(|p| p.as_array())
                        .map(|a| a.as_slice())
                        .unwrap_or(&[]);

                    let path_params: Vec<&str> = params
                        .iter()
                        .filter(|p| p.get("in").and_then(|i| i.as_str()) == Some("path"))
                        .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
                        .collect();
                    let query_params: Vec<&str> = params
                        .iter()
                        .filter(|p| p.get("in").and_then(|i| i.as_str()) == Some("query"))
                        .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
                        .collect();

                    let op_value = Value::Object(op.clone());
                    let resp_type = op_value
                        .pointer("/responses/200/content/application~1json/schema")
                        .map(json_schema_to_py)
                        .unwrap_or_else(|| "dict".to_string());

                    let mut args = vec!["self".to_string()];
                    for p in &path_params {
                        args.push(format!("{}: str", p));
                    }
                    if !query_params.is_empty() {
                        args.push("*".to_string());
                        for p in &query_params {
                            args.push(format!("{}: Optional[str] = None", p));
                        }
                    }

                    let params_dict = if query_params.is_empty() {
                        String::new()
                    } else {
                        let kv: Vec<_> = query_params
                            .iter()
                            .map(|p| format!("'{}': {}", p, p))
                            .collect();
                        format!(", {{{}}}", kv.join(", "))
                    };

                    out.push_str(&format!(
                        "    def {}({}) -> {}:\n",
                        op_id,
                        args.join(", "),
                        resp_type
                    ));
                    out.push_str(&format!(
                        "        data = self._request(f'{}'{})\n",
                        path, params_dict
                    ));
                    out.push_str(&format!("        return {}(**data)\n\n", resp_type));
                }
            }
        }

        out
    }
}

// --- Rust (ureq) ---

struct RustUreq;

impl OpenApiClientGenerator for RustUreq {
    fn language(&self) -> &'static str {
        "rust"
    }
    fn variant(&self) -> &'static str {
        "ureq"
    }

    fn generate(&self, spec: &Value) -> String {
        let mut out = String::new();
        out.push_str("//! Auto-generated from OpenAPI spec\n");
        out.push_str("//! Uses ureq (blocking HTTP)\n\n");
        out.push_str("use serde::{Deserialize, Serialize};\n\n");

        // Generate structs from schemas
        if let Some(schemas) = spec
            .pointer("/components/schemas")
            .and_then(|s| s.as_object())
        {
            for (name, schema) in schemas {
                out.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
                out.push_str(&format!("pub struct {} {{\n", name));
                if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
                    let required: Vec<&str> = schema
                        .get("required")
                        .and_then(|r| r.as_array())
                        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
                        .unwrap_or_default();
                    for (prop_name, prop) in props {
                        let rust_type = json_schema_to_rust(prop);
                        let field_type = if required.contains(&prop_name.as_str()) {
                            rust_type
                        } else {
                            format!("Option<{}>", rust_type)
                        };
                        out.push_str(&format!(
                            "    pub {}: {},\n",
                            to_snake_case(prop_name),
                            field_type
                        ));
                    }
                }
                out.push_str("}\n\n");
            }
        }

        // Generate client struct
        out.push_str("pub struct ApiClient {\n");
        out.push_str("    base_url: String,\n");
        out.push_str("}\n\n");

        out.push_str("impl ApiClient {\n");
        out.push_str("    pub fn new(base_url: impl Into<String>) -> Self {\n");
        out.push_str("        Self { base_url: base_url.into() }\n");
        out.push_str("    }\n\n");

        // Generate methods from paths
        if let Some(paths) = spec.get("paths").and_then(|p| p.as_object()) {
            for (path, methods) in paths {
                if let Some(op) = methods.get("get").and_then(|g| g.as_object()) {
                    let op_id = op
                        .get("operationId")
                        .and_then(|id| id.as_str())
                        .unwrap_or("unknown");
                    let params = op
                        .get("parameters")
                        .and_then(|p| p.as_array())
                        .map(|a| a.as_slice())
                        .unwrap_or(&[]);

                    let path_params: Vec<&str> = params
                        .iter()
                        .filter(|p| p.get("in").and_then(|i| i.as_str()) == Some("path"))
                        .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
                        .collect();
                    let query_params: Vec<(&str, bool)> = params
                        .iter()
                        .filter(|p| p.get("in").and_then(|i| i.as_str()) == Some("query"))
                        .filter_map(|p| {
                            let name = p.get("name").and_then(|n| n.as_str())?;
                            let required =
                                p.get("required").and_then(|r| r.as_bool()).unwrap_or(false);
                            Some((name, required))
                        })
                        .collect();

                    let op_value = Value::Object(op.clone());
                    let resp_type = op_value
                        .pointer("/responses/200/content/application~1json/schema")
                        .map(json_schema_to_rust)
                        .unwrap_or_else(|| "()".to_string());

                    // Build function signature
                    let mut args = Vec::new();
                    args.push("&self".to_string());
                    for p in &path_params {
                        args.push(format!("{}: &str", to_snake_case(p)));
                    }
                    for (p, required) in &query_params {
                        let param_type = if *required {
                            "&str".to_string()
                        } else {
                            "Option<&str>".to_string()
                        };
                        args.push(format!("{}: {}", to_snake_case(p), param_type));
                    }

                    out.push_str(&format!(
                        "    pub fn {}({}) -> Result<{}, ureq::Error> {{\n",
                        to_snake_case(op_id),
                        args.join(", "),
                        resp_type
                    ));

                    // Build URL with path params
                    let url_expr = if path_params.is_empty() {
                        format!("format!(\"{{}}{}\"", path)
                    } else {
                        let rust_path = path_params.iter().fold(path.to_string(), |acc, p| {
                            acc.replace(&format!("{{{}}}", p), &format!("{{{}}}", to_snake_case(p)))
                        });
                        format!("format!(\"{{}}{}\", ", rust_path)
                    };
                    out.push_str(&format!("        let url = {}self.base_url);\n", url_expr));

                    // Build request
                    out.push_str("        let mut req = ureq::get(&url);\n");
                    for (p, required) in &query_params {
                        let snake = to_snake_case(p);
                        if *required {
                            out.push_str(&format!(
                                "        req = req.query(\"{}\", {});\n",
                                p, snake
                            ));
                        } else {
                            out.push_str(&format!(
                                "        if let Some(v) = {} {{ req = req.query(\"{}\", v); }}\n",
                                snake, p
                            ));
                        }
                    }

                    out.push_str("        let resp: ");
                    out.push_str(&resp_type);
                    out.push_str(" = req.call()?.into_json()?;\n");
                    out.push_str("        Ok(resp)\n");
                    out.push_str("    }\n\n");
                }
            }
        }

        out.push_str("}\n");
        out
    }
}

fn to_snake_case(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            // normalize-syntax-allow: rust/unwrap-in-impl - char::to_lowercase() always yields at least one char
            result.push(c.to_lowercase().next().unwrap());
        } else {
            result.push(c);
        }
    }
    result
}

fn json_schema_to_rust(schema: &Value) -> String {
    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
        return ref_path
            .split('/')
            .next_back()
            .unwrap_or("serde_json::Value")
            .to_string();
    }

    let type_val = schema.get("type");

    if let Some(arr) = type_val.and_then(|t| t.as_array()) {
        let types: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
        let non_null: Vec<_> = types.iter().filter(|t| **t != "null").collect();
        if non_null.len() == 1 {
            let base = type_str_to_rust(non_null[0]);
            return format!("Option<{}>", base);
        }
    }

    if let Some(type_str) = type_val.and_then(|t| t.as_str()) {
        if type_str == "array" {
            if let Some(items) = schema.get("items") {
                return format!("Vec<{}>", json_schema_to_rust(items));
            }
            return "Vec<serde_json::Value>".to_string();
        }
        return type_str_to_rust(type_str);
    }

    "serde_json::Value".to_string()
}

fn type_str_to_rust(t: &str) -> String {
    match t {
        "string" => "String".to_string(),
        "integer" => "i64".to_string(),
        "number" => "f64".to_string(),
        "boolean" => "bool".to_string(),
        "object" => "serde_json::Value".to_string(),
        _ => "serde_json::Value".to_string(),
    }
}

// --- Helpers ---

fn json_schema_to_ts(schema: &Value) -> String {
    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
        return ref_path
            .split('/')
            .next_back()
            .unwrap_or("unknown")
            .to_string();
    }

    let type_val = schema.get("type");

    if let Some(arr) = type_val.and_then(|t| t.as_array()) {
        let types: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
        let non_null: Vec<_> = types.iter().filter(|t| **t != "null").collect();
        if non_null.len() == 1 {
            let base = type_str_to_ts(non_null[0]);
            return format!("{} | null", base);
        }
    }

    if let Some(type_str) = type_val.and_then(|t| t.as_str()) {
        if type_str == "array" {
            if let Some(items) = schema.get("items") {
                return format!("{}[]", json_schema_to_ts(items));
            }
            return "unknown[]".to_string();
        }
        return type_str_to_ts(type_str);
    }

    "unknown".to_string()
}

fn type_str_to_ts(t: &str) -> String {
    match t {
        "string" => "string".to_string(),
        "integer" | "number" => "number".to_string(),
        "boolean" => "boolean".to_string(),
        "object" => "Record<string, unknown>".to_string(),
        _ => "unknown".to_string(),
    }
}

fn json_schema_to_py(schema: &Value) -> String {
    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
        return ref_path.split('/').next_back().unwrap_or("Any").to_string();
    }

    let type_val = schema.get("type");

    if let Some(arr) = type_val.and_then(|t| t.as_array()) {
        let types: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
        let non_null: Vec<_> = types.iter().filter(|t| **t != "null").collect();
        if non_null.len() == 1 {
            let base = type_str_to_py(non_null[0]);
            return format!("Optional[{}]", base);
        }
    }

    if let Some(type_str) = type_val.and_then(|t| t.as_str()) {
        if type_str == "array" {
            if let Some(items) = schema.get("items") {
                return format!("list[{}]", json_schema_to_py(items));
            }
            return "list".to_string();
        }
        return type_str_to_py(type_str);
    }

    "Any".to_string()
}

fn type_str_to_py(t: &str) -> String {
    match t {
        "string" => "str".to_string(),
        "integer" => "int".to_string(),
        "number" => "float".to_string(),
        "boolean" => "bool".to_string(),
        "object" => "dict".to_string(),
        _ => "Any".to_string(),
    }
}

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

    #[test]
    fn test_find_generator() {
        assert!(find_generator("typescript").is_some());
        assert!(find_generator("ts").is_some());
        assert!(find_generator("python").is_some());
        assert!(find_generator("py").is_some());
        assert!(find_generator("rust").is_some());
        assert!(find_generator("rs").is_some());
        assert!(find_generator("unknown").is_none());
    }

    #[test]
    fn test_list_generators() {
        let gens = list_generators();
        assert!(gens.iter().any(|(l, _)| *l == "typescript"));
        assert!(gens.iter().any(|(l, _)| *l == "python"));
        assert!(gens.iter().any(|(l, _)| *l == "rust"));
    }

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("getUserById"), "get_user_by_id");
        assert_eq!(to_snake_case("API"), "a_p_i");
        assert_eq!(to_snake_case("simple"), "simple");
    }
}