brk_binder 0.1.0-alpha.1

A generator of binding files for other languages
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
use std::collections::HashSet;
use std::fmt::Write as FmtWrite;
use std::fs;
use std::io;
use std::path::Path;

use brk_types::{Index, TreeNode};

use crate::{
    ClientMetadata, Endpoint, FieldNamePosition, IndexSetPattern, PatternField, StructuralPattern,
    extract_inner_type, get_fields_with_child_info, get_node_fields, get_pattern_instance_base,
    to_pascal_case, to_snake_case,
};

/// Generate Rust client from metadata and OpenAPI endpoints
pub fn generate_rust_client(
    metadata: &ClientMetadata,
    endpoints: &[Endpoint],
    output_dir: &Path,
) -> io::Result<()> {
    let mut output = String::new();

    // Header
    writeln!(output, "// Auto-generated BRK Rust client").unwrap();
    writeln!(output, "// Do not edit manually\n").unwrap();
    writeln!(output, "#![allow(non_camel_case_types)]").unwrap();
    writeln!(output, "#![allow(dead_code)]\n").unwrap();

    // Imports
    generate_imports(&mut output);

    // Generate base client
    generate_base_client(&mut output);

    // Generate MetricNode
    generate_metric_node(&mut output);

    // Generate index accessor structs (for each unique set of indexes)
    generate_index_accessors(&mut output, &metadata.index_set_patterns);

    // Generate pattern structs (reusable, appearing 2+ times)
    generate_pattern_structs(&mut output, &metadata.structural_patterns, metadata);

    // Generate tree - each node uses its pattern or is generated inline
    generate_tree(&mut output, &metadata.catalog, metadata);

    // Generate main client with API methods
    generate_main_client(&mut output, endpoints);

    fs::write(output_dir.join("client.rs"), output)?;

    Ok(())
}

fn generate_imports(output: &mut String) {
    writeln!(
        output,
        r#"use std::marker::PhantomData;
use serde::de::DeserializeOwned;
use brk_types::*;

"#
    )
    .unwrap();
}

fn generate_base_client(output: &mut String) {
    writeln!(
        output,
        r#"/// Error type for BRK client operations.
#[derive(Debug)]
pub struct BrkError {{
    pub message: String,
}}

impl std::fmt::Display for BrkError {{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{
        write!(f, "{{}}", self.message)
    }}
}}

impl std::error::Error for BrkError {{}}

/// Result type for BRK client operations.
pub type Result<T> = std::result::Result<T, BrkError>;

/// Options for configuring the BRK client.
#[derive(Debug, Clone)]
pub struct BrkClientOptions {{
    pub base_url: String,
    pub timeout_ms: u64,
}}

impl Default for BrkClientOptions {{
    fn default() -> Self {{
        Self {{
            base_url: "http://localhost:3000".to_string(),
            timeout_ms: 30000,
        }}
    }}
}}

/// Base HTTP client for making requests.
#[derive(Debug, Clone)]
pub struct BrkClientBase {{
    base_url: String,
    client: reqwest::blocking::Client,
}}

impl BrkClientBase {{
    /// Create a new client with the given base URL.
    pub fn new(base_url: impl Into<String>) -> Result<Self> {{
        let base_url = base_url.into();
        let client = reqwest::blocking::Client::new();
        Ok(Self {{ base_url, client }})
    }}

    /// Create a new client with options.
    pub fn with_options(options: BrkClientOptions) -> Result<Self> {{
        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_millis(options.timeout_ms))
            .build()
            .map_err(|e| BrkError {{ message: e.to_string() }})?;
        Ok(Self {{
            base_url: options.base_url,
            client,
        }})
    }}

    /// Make a GET request.
    pub fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {{
        let url = format!("{{}}{{}}", self.base_url, path);
        self.client
            .get(&url)
            .send()
            .map_err(|e| BrkError {{ message: e.to_string() }})?
            .json()
            .map_err(|e| BrkError {{ message: e.to_string() }})
    }}
}}

"#
    )
    .unwrap();
}

fn generate_metric_node(output: &mut String) {
    writeln!(
        output,
        r#"/// A metric node that can fetch data for different indexes.
pub struct MetricNode<'a, T> {{
    client: &'a BrkClientBase,
    path: String,
    _marker: PhantomData<T>,
}}

impl<'a, T: DeserializeOwned> MetricNode<'a, T> {{
    pub fn new(client: &'a BrkClientBase, path: String) -> Self {{
        Self {{
            client,
            path,
            _marker: PhantomData,
        }}
    }}

    /// Fetch all data points for this metric.
    pub fn get(&self) -> Result<Vec<T>> {{
        self.client.get(&self.path)
    }}

    /// Fetch data points within a date range.
    pub fn get_range(&self, from: &str, to: &str) -> Result<Vec<T>> {{
        let path = format!("{{}}?from={{}}&to={{}}", self.path, from, to);
        self.client.get(&path)
    }}
}}

"#
    )
    .unwrap();
}

/// Generate index accessor structs for each unique set of indexes
fn generate_index_accessors(output: &mut String, patterns: &[IndexSetPattern]) {
    if patterns.is_empty() {
        return;
    }

    writeln!(output, "// Index accessor structs\n").unwrap();

    for pattern in patterns {
        writeln!(
            output,
            "/// Index accessor for metrics with {} indexes.",
            pattern.indexes.len()
        )
        .unwrap();
        writeln!(output, "pub struct {}<'a, T> {{", pattern.name).unwrap();

        for index in &pattern.indexes {
            let field_name = index_to_field_name(index);
            writeln!(output, "    pub {}: MetricNode<'a, T>,", field_name).unwrap();
        }

        writeln!(output, "    _marker: PhantomData<T>,").unwrap();
        writeln!(output, "}}\n").unwrap();

        // Generate impl block with constructor
        writeln!(
            output,
            "impl<'a, T: DeserializeOwned> {}<'a, T> {{",
            pattern.name
        )
        .unwrap();
        writeln!(
            output,
            "    pub fn new(client: &'a BrkClientBase, base_path: &str) -> Self {{"
        )
        .unwrap();
        writeln!(output, "        Self {{").unwrap();

        for index in &pattern.indexes {
            let field_name = index_to_field_name(index);
            let path_segment = index.serialize_long();
            writeln!(
                output,
                "            {}: MetricNode::new(client, format!(\"{{base_path}}/{}\")),",
                field_name, path_segment
            )
            .unwrap();
        }

        writeln!(output, "            _marker: PhantomData,").unwrap();
        writeln!(output, "        }}").unwrap();
        writeln!(output, "    }}").unwrap();
        writeln!(output, "}}\n").unwrap();
    }
}

/// Convert an Index to a snake_case field name (e.g., DateIndex -> by_date_index)
fn index_to_field_name(index: &Index) -> String {
    format!("by_{}", to_snake_case(index.serialize_long()))
}

/// Generate pattern structs (those appearing 2+ times)
fn generate_pattern_structs(
    output: &mut String,
    patterns: &[StructuralPattern],
    metadata: &ClientMetadata,
) {
    if patterns.is_empty() {
        return;
    }

    writeln!(output, "// Reusable pattern structs\n").unwrap();

    for pattern in patterns {
        let is_parameterizable = pattern.is_parameterizable();
        let generic_params = if pattern.is_generic {
            "<'a, T>"
        } else {
            "<'a>"
        };

        writeln!(output, "/// Pattern struct for repeated tree structure.").unwrap();
        writeln!(output, "pub struct {}{} {{", pattern.name, generic_params).unwrap();

        for field in &pattern.fields {
            let field_name = to_snake_case(&field.name);
            let type_annotation =
                field_to_type_annotation_generic(field, metadata, pattern.is_generic);
            writeln!(output, "    pub {}: {},", field_name, type_annotation).unwrap();
        }

        writeln!(output, "}}\n").unwrap();

        // Generate impl block with constructor
        writeln!(
            output,
            "impl{} {}{} {{",
            generic_params, pattern.name, generic_params
        )
        .unwrap();

        if is_parameterizable {
            writeln!(
                output,
                "    /// Create a new pattern node with accumulated metric name."
            )
            .unwrap();
            writeln!(
                output,
                "    pub fn new(client: &'a BrkClientBase, acc: &str) -> Self {{"
            )
            .unwrap();
        } else {
            writeln!(
                output,
                "    pub fn new(client: &'a BrkClientBase, base_path: &str) -> Self {{"
            )
            .unwrap();
        }
        writeln!(output, "        Self {{").unwrap();

        for field in &pattern.fields {
            if is_parameterizable {
                generate_parameterized_rust_field(output, field, pattern, metadata);
            } else {
                generate_tree_path_rust_field(output, field, metadata);
            }
        }

        writeln!(output, "        }}").unwrap();
        writeln!(output, "    }}").unwrap();
        writeln!(output, "}}\n").unwrap();
    }
}

/// Generate a field using parameterized (prepend/append) metric name construction
fn generate_parameterized_rust_field(
    output: &mut String,
    field: &PatternField,
    pattern: &StructuralPattern,
    metadata: &ClientMetadata,
) {
    let field_name = to_snake_case(&field.name);

    // For branch fields, pass the accumulated name to nested pattern
    if metadata.is_pattern_type(&field.rust_type) {
        let child_acc = if let Some(pos) = pattern.get_field_position(&field.name) {
            match pos {
                FieldNamePosition::Append(suffix) => format!("&format!(\"{{acc}}{}\")", suffix),
                FieldNamePosition::Prepend(prefix) => format!("&format!(\"{}{{acc}}\")", prefix),
                FieldNamePosition::Identity => "acc".to_string(),
                FieldNamePosition::SetBase(base) => format!("\"{}\"", base),
            }
        } else {
            format!("&format!(\"{{acc}}_{}\")", field.name)
        };

        writeln!(
            output,
            "            {}: {}::new(client, {}),",
            field_name, field.rust_type, child_acc
        )
        .unwrap();
        return;
    }

    // For leaf fields, construct the metric path based on position
    let metric_expr = if let Some(pos) = pattern.get_field_position(&field.name) {
        match pos {
            FieldNamePosition::Append(suffix) => format!("format!(\"/{{acc}}{}\")", suffix),
            FieldNamePosition::Prepend(prefix) => format!("format!(\"/{}{{acc}}\")", prefix),
            FieldNamePosition::Identity => "format!(\"/{acc}\")".to_string(),
            FieldNamePosition::SetBase(base) => format!("\"/{}\".to_string()", base),
        }
    } else {
        format!("format!(\"/{{acc}}_{}\")", field.name)
    };

    if metadata.field_uses_accessor(field) {
        let accessor = metadata.find_index_set_pattern(&field.indexes).unwrap();
        writeln!(
            output,
            "            {}: {}::new(client, &{}),",
            field_name, accessor.name, metric_expr
        )
        .unwrap();
    } else {
        writeln!(
            output,
            "            {}: MetricNode::new(client, {}),",
            field_name, metric_expr
        )
        .unwrap();
    }
}

/// Generate a field using tree path construction (fallback for non-parameterizable patterns)
fn generate_tree_path_rust_field(
    output: &mut String,
    field: &PatternField,
    metadata: &ClientMetadata,
) {
    let field_name = to_snake_case(&field.name);

    if metadata.is_pattern_type(&field.rust_type) {
        writeln!(
            output,
            "            {}: {}::new(client, &format!(\"{{base_path}}/{}\")),",
            field_name, field.rust_type, field.name
        )
        .unwrap();
    } else if metadata.field_uses_accessor(field) {
        let accessor = metadata.find_index_set_pattern(&field.indexes).unwrap();
        writeln!(
            output,
            "            {}: {}::new(client, &format!(\"{{base_path}}/{}\")),",
            field_name, accessor.name, field.name
        )
        .unwrap();
    } else {
        writeln!(
            output,
            "            {}: MetricNode::new(client, format!(\"{{base_path}}/{}\")),",
            field_name, field.name
        )
        .unwrap();
    }
}

/// Convert a PatternField to the full type annotation, with optional generic support
fn field_to_type_annotation_generic(
    field: &PatternField,
    metadata: &ClientMetadata,
    is_generic: bool,
) -> String {
    field_to_type_annotation_with_generic(field, metadata, is_generic, None)
}

/// Convert a PatternField to the full type annotation.
/// - `is_generic`: If true and field.rust_type is "T", use T in the output
/// - `generic_value_type`: For branch fields that reference a generic pattern, this is the concrete type to substitute
fn field_to_type_annotation_with_generic(
    field: &PatternField,
    metadata: &ClientMetadata,
    is_generic: bool,
    generic_value_type: Option<&str>,
) -> String {
    // For generic patterns, use T instead of concrete value type
    // Also extract inner type from wrappers like Close<Dollars> -> Dollars
    let value_type = if is_generic && field.rust_type == "T" {
        "T".to_string()
    } else {
        extract_inner_type(&field.rust_type)
    };

    if metadata.is_pattern_type(&field.rust_type) {
        // Check if this pattern is generic and we have a value type
        if metadata.is_pattern_generic(&field.rust_type)
            && let Some(vt) = generic_value_type
        {
            return format!("{}<'a, {}>", field.rust_type, vt);
        }
        format!("{}<'a>", field.rust_type)
    } else if let Some(accessor) = metadata.find_index_set_pattern(&field.indexes) {
        // Leaf with a reusable accessor pattern
        format!("{}<'a, {}>", accessor.name, value_type)
    } else {
        // Leaf with unique index set - use MetricNode directly
        format!("MetricNode<'a, {}>", value_type)
    }
}

/// Generate the catalog tree structure
fn generate_tree(output: &mut String, catalog: &TreeNode, metadata: &ClientMetadata) {
    writeln!(output, "// Catalog tree\n").unwrap();

    let pattern_lookup = metadata.pattern_lookup();
    let mut generated = HashSet::new();
    generate_tree_node(
        output,
        "CatalogTree",
        catalog,
        &pattern_lookup,
        metadata,
        &mut generated,
    );
}

/// Recursively generate tree nodes
fn generate_tree_node(
    output: &mut String,
    name: &str,
    node: &TreeNode,
    pattern_lookup: &std::collections::HashMap<Vec<PatternField>, String>,
    metadata: &ClientMetadata,
    generated: &mut HashSet<String>,
) {
    let TreeNode::Branch(children) = node else {
        return;
    };

    let fields_with_child_info = get_fields_with_child_info(children, name, pattern_lookup);
    let fields: Vec<PatternField> = fields_with_child_info
        .iter()
        .map(|(f, _)| f.clone())
        .collect();

    // Skip if this matches a pattern (already generated separately)
    if let Some(pattern_name) = pattern_lookup.get(&fields)
        && pattern_name != name
    {
        return;
    }

    if generated.contains(name) {
        return;
    }
    generated.insert(name.to_string());

    writeln!(output, "/// Catalog tree node.").unwrap();
    writeln!(output, "pub struct {}<'a> {{", name).unwrap();

    for (field, child_fields) in &fields_with_child_info {
        let field_name = to_snake_case(&field.name);
        let generic_value_type = child_fields
            .as_ref()
            .and_then(|cf| metadata.get_generic_value_type(&field.rust_type, cf));
        let type_annotation = field_to_type_annotation_with_generic(
            field,
            metadata,
            false,
            generic_value_type.as_deref(),
        );
        writeln!(output, "    pub {}: {},", field_name, type_annotation).unwrap();
    }

    writeln!(output, "}}\n").unwrap();

    // Generate impl block
    writeln!(output, "impl<'a> {}<'a> {{", name).unwrap();
    writeln!(
        output,
        "    pub fn new(client: &'a BrkClientBase, base_path: &str) -> Self {{"
    )
    .unwrap();
    writeln!(output, "        Self {{").unwrap();

    for (field, (child_name, child_node)) in fields.iter().zip(children.iter()) {
        let field_name = to_snake_case(&field.name);
        if metadata.is_pattern_type(&field.rust_type) {
            let pattern = metadata.find_pattern(&field.rust_type);
            let is_parameterizable = pattern.is_some_and(|p| p.is_parameterizable());

            if is_parameterizable {
                let metric_base = get_pattern_instance_base(child_node, child_name);
                writeln!(
                    output,
                    "            {}: {}::new(client, \"{}\"),",
                    field_name, field.rust_type, metric_base
                )
                .unwrap();
            } else {
                writeln!(
                    output,
                    "            {}: {}::new(client, &format!(\"{{base_path}}/{}\")),",
                    field_name, field.rust_type, field.name
                )
                .unwrap();
            }
        } else if metadata.field_uses_accessor(field) {
            let metric_path = if let TreeNode::Leaf(leaf) = child_node {
                format!("/{}", leaf.name())
            } else {
                format!("{{base_path}}/{}", field.name)
            };
            let accessor = metadata.find_index_set_pattern(&field.indexes).unwrap();
            if metric_path.contains("{base_path}") {
                writeln!(
                    output,
                    "            {}: {}::new(client, &format!(\"{}\")),",
                    field_name, accessor.name, metric_path
                )
                .unwrap();
            } else {
                writeln!(
                    output,
                    "            {}: {}::new(client, \"{}\"),",
                    field_name, accessor.name, metric_path
                )
                .unwrap();
            }
        } else {
            let metric_path = if let TreeNode::Leaf(leaf) = child_node {
                format!("/{}", leaf.name())
            } else {
                format!("{{base_path}}/{}", field.name)
            };
            if metric_path.contains("{base_path}") {
                writeln!(
                    output,
                    "            {}: MetricNode::new(client, format!(\"{}\")),",
                    field_name, metric_path
                )
                .unwrap();
            } else {
                writeln!(
                    output,
                    "            {}: MetricNode::new(client, \"{}\".to_string()),",
                    field_name, metric_path
                )
                .unwrap();
            }
        }
    }

    writeln!(output, "        }}").unwrap();
    writeln!(output, "    }}").unwrap();
    writeln!(output, "}}\n").unwrap();

    // Recursively generate child nodes that aren't patterns
    for (child_name, child_node) in children {
        if let TreeNode::Branch(grandchildren) = child_node {
            let child_fields = get_node_fields(grandchildren, pattern_lookup);
            if !pattern_lookup.contains_key(&child_fields) {
                let child_struct_name = format!("{}_{}", name, to_pascal_case(child_name));
                generate_tree_node(
                    output,
                    &child_struct_name,
                    child_node,
                    pattern_lookup,
                    metadata,
                    generated,
                );
            }
        }
    }
}

/// Generate the main client struct
fn generate_main_client(output: &mut String, endpoints: &[Endpoint]) {
    writeln!(
        output,
        r#"/// Main BRK client with catalog tree and API methods.
pub struct BrkClient {{
    base: BrkClientBase,
}}

impl BrkClient {{
    /// Create a new client with the given base URL.
    pub fn new(base_url: impl Into<String>) -> Result<Self> {{
        Ok(Self {{
            base: BrkClientBase::new(base_url)?,
        }})
    }}

    /// Create a new client with options.
    pub fn with_options(options: BrkClientOptions) -> Result<Self> {{
        Ok(Self {{
            base: BrkClientBase::with_options(options)?,
        }})
    }}

    /// Get the catalog tree for navigating metrics.
    pub fn tree(&self) -> CatalogTree<'_> {{
        CatalogTree::new(&self.base, "")
    }}
"#
    )
    .unwrap();

    // Generate API methods
    generate_api_methods(output, endpoints);

    writeln!(output, "}}").unwrap();
}

/// Generate API methods from OpenAPI endpoints
fn generate_api_methods(output: &mut String, endpoints: &[Endpoint]) {
    for endpoint in endpoints {
        if !endpoint.should_generate() {
            continue;
        }

        let method_name = endpoint_to_method_name(endpoint);
        let return_type = endpoint
            .response_type
            .as_deref()
            .map(js_type_to_rust)
            .unwrap_or_else(|| "serde_json::Value".to_string());

        // Build doc comment
        writeln!(
            output,
            "    /// {}",
            endpoint.summary.as_deref().unwrap_or(&method_name)
        )
        .unwrap();

        // Build method signature
        let params = build_method_params(endpoint);
        writeln!(
            output,
            "    pub fn {}(&self{}) -> Result<{}> {{",
            method_name, params, return_type
        )
        .unwrap();

        // Build path
        let path = build_path_template(&endpoint.path, &endpoint.path_params);

        if endpoint.query_params.is_empty() {
            writeln!(output, "        self.base.get(&format!(\"{}\"))", path).unwrap();
        } else {
            writeln!(output, "        let mut query = Vec::new();").unwrap();
            for param in &endpoint.query_params {
                if param.required {
                    writeln!(
                        output,
                        "        query.push(format!(\"{}={{}}\", {}));",
                        param.name, param.name
                    )
                    .unwrap();
                } else {
                    writeln!(
                        output,
                        "        if let Some(v) = {} {{ query.push(format!(\"{}={{}}\", v)); }}",
                        param.name, param.name
                    )
                    .unwrap();
                }
            }
            writeln!(output, "        let query_str = if query.is_empty() {{ String::new() }} else {{ format!(\"?{{}}\", query.join(\"&\")) }};").unwrap();
            writeln!(
                output,
                "        self.base.get(&format!(\"{}{{}}\", query_str))",
                path
            )
            .unwrap();
        }

        writeln!(output, "    }}\n").unwrap();
    }
}

fn endpoint_to_method_name(endpoint: &Endpoint) -> String {
    to_snake_case(&endpoint.operation_name())
}

fn build_method_params(endpoint: &Endpoint) -> String {
    let mut params = Vec::new();
    for param in &endpoint.path_params {
        params.push(format!(", {}: &str", param.name));
    }
    for param in &endpoint.query_params {
        if param.required {
            params.push(format!(", {}: &str", param.name));
        } else {
            params.push(format!(", {}: Option<&str>", param.name));
        }
    }
    params.join("")
}

fn build_path_template(path: &str, path_params: &[super::Parameter]) -> String {
    let mut result = path.to_string();
    for param in path_params {
        let placeholder = format!("{{{}}}", param.name);
        let interpolation = format!("{{{}}}", param.name);
        result = result.replace(&placeholder, &interpolation);
    }
    result
}

/// Convert JS-style type to Rust type (e.g., "Txid[]" -> "Vec<Txid>")
fn js_type_to_rust(js_type: &str) -> String {
    if let Some(inner) = js_type.strip_suffix("[]") {
        format!("Vec<{}>", js_type_to_rust(inner))
    } else {
        match js_type {
            "string" => "String".to_string(),
            "number" => "f64".to_string(),
            "boolean" => "bool".to_string(),
            "*" => "serde_json::Value".to_string(),
            other => other.to_string(),
        }
    }
}