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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
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 serde_json::Value;

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

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

    // Header
    writeln!(output, "# Auto-generated BRK Python client").unwrap();
    writeln!(output, "# Do not edit manually\n").unwrap();
    writeln!(output, "from __future__ import annotations").unwrap();
    writeln!(
        output,
        "from typing import TypeVar, Generic, Any, Optional, List, Literal, TypedDict"
    )
    .unwrap();
    writeln!(output, "import httpx\n").unwrap();

    // Type variable for generic MetricNode
    writeln!(output, "T = TypeVar('T')\n").unwrap();

    // Generate type definitions from OpenAPI schemas (now includes leaf types from catalog)
    generate_type_definitions(&mut output, schemas);

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

    // Generate MetricNode class
    generate_metric_node(&mut output);

    // Generate index accessor classes
    generate_index_accessors(&mut output, &metadata.index_set_patterns);

    // Generate structural pattern classes
    generate_structural_patterns(&mut output, &metadata.structural_patterns, metadata);

    // Generate tree classes
    generate_tree_classes(&mut output, &metadata.catalog, metadata);

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

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

    Ok(())
}

/// Generate Python type definitions from OpenAPI schemas
fn generate_type_definitions(output: &mut String, schemas: &TypeSchemas) {
    if schemas.is_empty() {
        return;
    }

    writeln!(output, "# Type definitions\n").unwrap();

    // Sort types by dependencies (types that reference other types must come after)
    let sorted_names = topological_sort_schemas(schemas);

    for name in sorted_names {
        let Some(schema) = schemas.get(&name) else {
            continue;
        };
        if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
            // Object type -> TypedDict
            writeln!(output, "class {}(TypedDict):", name).unwrap();
            for (prop_name, prop_schema) in props {
                let prop_type = schema_to_python_type_ctx(prop_schema, Some(&name));
                let safe_name = escape_python_keyword(prop_name);
                writeln!(output, "    {}: {}", safe_name, prop_type).unwrap();
            }
            writeln!(output).unwrap();
        } else if is_enum_schema(schema) {
            // Enum type -> Literal union
            let py_type = schema_to_python_type_ctx(schema, Some(&name));
            writeln!(output, "{} = {}", name, py_type).unwrap();
        } else {
            // Primitive type alias
            let py_type = schema_to_python_type_ctx(schema, Some(&name));
            writeln!(output, "{} = {}", name, py_type).unwrap();
        }
    }
    writeln!(output).unwrap();
}

/// Topologically sort schema names so dependencies come before dependents.
/// Types that reference other types (via $ref) must be defined after their dependencies.
fn topological_sort_schemas(schemas: &TypeSchemas) -> Vec<String> {
    use std::collections::{HashMap, HashSet};

    // Build dependency graph
    let mut deps: HashMap<String, HashSet<String>> = HashMap::new();
    for (name, schema) in schemas {
        let mut type_deps = HashSet::new();
        collect_schema_refs(schema, &mut type_deps);
        // Only keep deps that are in our schemas
        type_deps.retain(|d| schemas.contains_key(d));
        deps.insert(name.clone(), type_deps);
    }

    // Kahn's algorithm for topological sort
    let mut in_degree: HashMap<String, usize> = HashMap::new();
    for name in schemas.keys() {
        in_degree.insert(name.clone(), 0);
    }
    for type_deps in deps.values() {
        for dep in type_deps {
            *in_degree.entry(dep.clone()).or_insert(0) += 1;
        }
    }

    // Start with types that have no dependents (are not referenced by others)
    let mut queue: Vec<String> = in_degree
        .iter()
        .filter(|(_, count)| **count == 0)
        .map(|(name, _)| name.clone())
        .collect();
    queue.sort(); // Deterministic order

    let mut result = Vec::new();
    while let Some(name) = queue.pop() {
        result.push(name.clone());
        if let Some(type_deps) = deps.get(&name) {
            for dep in type_deps {
                if let Some(count) = in_degree.get_mut(dep) {
                    *count = count.saturating_sub(1);
                    if *count == 0 {
                        queue.push(dep.clone());
                        queue.sort(); // Keep sorted for determinism
                    }
                }
            }
        }
    }

    // Reverse so dependencies come first
    result.reverse();

    // Add any types that weren't processed (e.g., due to circular refs or other edge cases)
    let result_set: HashSet<_> = result.iter().cloned().collect();
    let mut missing: Vec<_> = schemas
        .keys()
        .filter(|k| !result_set.contains(*k))
        .cloned()
        .collect();
    missing.sort();
    result.extend(missing);

    result
}

/// Collect all type references ($ref) from a schema
fn collect_schema_refs(schema: &Value, refs: &mut std::collections::HashSet<String>) {
    match schema {
        Value::Object(map) => {
            if let Some(ref_path) = map.get("$ref").and_then(|r| r.as_str())
                && let Some(type_name) = ref_path.rsplit('/').next()
            {
                refs.insert(type_name.to_string());
            }
            for value in map.values() {
                collect_schema_refs(value, refs);
            }
        }
        Value::Array(arr) => {
            for item in arr {
                collect_schema_refs(item, refs);
            }
        }
        _ => {}
    }
}

/// Convert a single JSON type string to Python type
fn json_type_to_python(ty: &str, schema: &Value, current_type: Option<&str>) -> String {
    match ty {
        "integer" => "int".to_string(),
        "number" => "float".to_string(),
        "boolean" => "bool".to_string(),
        "string" => "str".to_string(),
        "null" => "None".to_string(),
        "array" => {
            let item_type = schema
                .get("items")
                .map(|s| schema_to_python_type_ctx(s, current_type))
                .unwrap_or_else(|| "Any".to_string());
            format!("List[{}]", item_type)
        }
        "object" => {
            // Check if it has additionalProperties (dict-like)
            if let Some(add_props) = schema.get("additionalProperties") {
                let value_type = schema_to_python_type_ctx(add_props, current_type);
                return format!("dict[str, {}]", value_type);
            }
            "dict".to_string()
        }
        _ => "Any".to_string(),
    }
}

/// Convert JSON Schema to Python type with context for detecting self-references
fn schema_to_python_type_ctx(schema: &Value, current_type: Option<&str>) -> String {
    // Handle allOf (try each element until we find a resolvable type)
    if let Some(all_of) = schema.get("allOf").and_then(|v| v.as_array()) {
        for item in all_of {
            let resolved = schema_to_python_type_ctx(item, current_type);
            if resolved != "Any" {
                return resolved;
            }
        }
    }

    // Handle $ref
    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
        let type_name = ref_path.rsplit('/').next().unwrap_or("Any");
        // Quote self-references to handle recursive types
        if current_type == Some(type_name) {
            return format!("\"{}\"", type_name);
        }
        return type_name.to_string();
    }

    // Handle enum (array of string values)
    if let Some(enum_values) = schema.get("enum").and_then(|e| e.as_array()) {
        let literals: Vec<String> = enum_values
            .iter()
            .filter_map(|v| v.as_str())
            .map(|s| format!("\"{}\"", s))
            .collect();
        if !literals.is_empty() {
            return format!("Literal[{}]", literals.join(", "));
        }
    }

    // Handle type field (can be string or array of strings)
    if let Some(ty) = schema.get("type") {
        // Handle array of types like ["string", "null"] for Optional
        if let Some(type_array) = ty.as_array() {
            let types: Vec<String> = type_array
                .iter()
                .filter_map(|t| t.as_str())
                .filter(|t| *t != "null") // Filter out null for cleaner Optional handling
                .map(|t| json_type_to_python(t, schema, current_type))
                .collect();
            let has_null = type_array.iter().any(|t| t.as_str() == Some("null"));

            if types.len() == 1 {
                let base_type = &types[0];
                return if has_null {
                    format!("Optional[{}]", base_type)
                } else {
                    base_type.clone()
                };
            } else if !types.is_empty() {
                let union = types.join(" | ");
                return if has_null {
                    format!("Optional[{}]", union)
                } else {
                    union
                };
            }
        }

        // Handle single type string
        if let Some(ty_str) = ty.as_str() {
            return json_type_to_python(ty_str, schema, current_type);
        }
    }

    // Handle anyOf/oneOf
    if let Some(variants) = schema
        .get("anyOf")
        .or_else(|| schema.get("oneOf"))
        .and_then(|v| v.as_array())
    {
        let types: Vec<String> = variants
            .iter()
            .map(|v| schema_to_python_type_ctx(v, current_type))
            .collect();
        // Filter out Any and null for cleaner unions
        let filtered: Vec<_> = types.iter().filter(|t| *t != "Any").collect();
        if !filtered.is_empty() {
            return filtered
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(" | ");
        }
        return types.join(" | ");
    }

    // Check for format hint without type (common in OpenAPI)
    if let Some(format) = schema.get("format").and_then(|f| f.as_str()) {
        return match format {
            "int32" | "int64" => "int".to_string(),
            "float" | "double" => "float".to_string(),
            "date" | "date-time" => "str".to_string(),
            _ => "Any".to_string(),
        };
    }

    "Any".to_string()
}

/// Make a name safe for Python: escape keywords and prefix digit-starting names
fn escape_python_keyword(name: &str) -> String {
    const PYTHON_KEYWORDS: &[&str] = &[
        "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class",
        "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global",
        "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return",
        "try", "while", "with", "yield",
    ];
    // Names starting with digit need underscore prefix
    let name = if name
        .chars()
        .next()
        .map(|c| c.is_ascii_digit())
        .unwrap_or(false)
    {
        format!("_{}", name)
    } else {
        name.to_string()
    };
    // Reserved keywords get underscore suffix
    if PYTHON_KEYWORDS.contains(&name.as_str()) {
        format!("{}_", name)
    } else {
        name
    }
}

/// Generate the base BrkClient class with HTTP functionality
fn generate_base_client(output: &mut String) {
    writeln!(
        output,
        r#"class BrkError(Exception):
    """Custom error class for BRK client errors."""

    def __init__(self, message: str, status: Optional[int] = None):
        super().__init__(message)
        self.status = status


class BrkClientBase:
    """Base HTTP client for making requests."""

    def __init__(self, base_url: str, timeout: float = 30.0):
        self.base_url = base_url
        self.timeout = timeout
        self._client = httpx.Client(timeout=timeout)

    def get(self, path: str) -> Any:
        """Make a GET request."""
        try:
            response = self._client.get(f"{{self.base_url}}{{path}}")
            response.raise_for_status()
            return response.json()
        except httpx.HTTPStatusError as e:
            raise BrkError(f"HTTP error: {{e.response.status_code}}", e.response.status_code)
        except httpx.RequestError as e:
            raise BrkError(str(e))

    def close(self):
        """Close the HTTP client."""
        self._client.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

"#
    )
    .unwrap();
}

/// Generate the MetricNode class
fn generate_metric_node(output: &mut String) {
    writeln!(
        output,
        r#"class MetricNode(Generic[T]):
    """A metric node that can fetch data for different indexes."""

    def __init__(self, client: BrkClientBase, path: str):
        self._client = client
        self._path = path

    def get(self) -> List[T]:
        """Fetch all data points for this metric."""
        return self._client.get(self._path)

    def get_range(self, from_date: str, to_date: str) -> List[T]:
        """Fetch data points within a date range."""
        return self._client.get(f"{{self._path}}?from={{from_date}}&to={{to_date}}")

"#
    )
    .unwrap();
}

/// Generate index accessor classes
fn generate_index_accessors(output: &mut String, patterns: &[IndexSetPattern]) {
    if patterns.is_empty() {
        return;
    }

    writeln!(output, "# Index accessor classes\n").unwrap();

    for pattern in patterns {
        writeln!(output, "class {}(Generic[T]):", pattern.name).unwrap();
        writeln!(
            output,
            "    \"\"\"Index accessor for metrics with {} indexes.\"\"\"",
            pattern.indexes.len()
        )
        .unwrap();
        writeln!(output, "    ").unwrap();
        writeln!(
            output,
            "    def __init__(self, client: BrkClientBase, base_path: str):"
        )
        .unwrap();

        for index in &pattern.indexes {
            let field_name = index_to_snake_case(index);
            let path_segment = index.serialize_long();
            writeln!(
                output,
                "        self.{}: MetricNode[T] = MetricNode(client, f'{{base_path}}/{}')",
                field_name, path_segment
            )
            .unwrap();
        }

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

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

/// Generate structural pattern classes
fn generate_structural_patterns(
    output: &mut String,
    patterns: &[StructuralPattern],
    metadata: &ClientMetadata,
) {
    if patterns.is_empty() {
        return;
    }

    writeln!(output, "# Reusable structural pattern classes\n").unwrap();

    for pattern in patterns {
        let is_parameterizable = pattern.is_parameterizable();

        // For generic patterns, inherit from Generic[T]
        if pattern.is_generic {
            writeln!(output, "class {}(Generic[T]):", pattern.name).unwrap();
        } else {
            writeln!(output, "class {}:", pattern.name).unwrap();
        }
        writeln!(
            output,
            "    \"\"\"Pattern struct for repeated tree structure.\"\"\""
        )
        .unwrap();
        writeln!(output, "    ").unwrap();

        if is_parameterizable {
            writeln!(
                output,
                "    def __init__(self, client: BrkClientBase, acc: str):"
            )
            .unwrap();
            writeln!(
                output,
                "        \"\"\"Create pattern node with accumulated metric name.\"\"\""
            )
            .unwrap();
        } else {
            writeln!(
                output,
                "    def __init__(self, client: BrkClientBase, base_path: str):"
            )
            .unwrap();
        }

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

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

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

    // 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!("f'{{acc}}{}'", suffix),
                FieldNamePosition::Prepend(prefix) => format!("f'{}{{acc}}'", prefix),
                FieldNamePosition::Identity => "acc".to_string(),
                FieldNamePosition::SetBase(base) => format!("'{}'", base),
            }
        } else {
            format!("f'{{acc}}_{}'", field.name)
        };

        writeln!(
            output,
            "        self.{}: {} = {}(client, {})",
            field_name, py_type, 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!("f'/{{acc}}{}'", suffix),
            FieldNamePosition::Prepend(prefix) => format!("f'/{}{{acc}}'", prefix),
            FieldNamePosition::Identity => "f'/{acc}'".to_string(),
            FieldNamePosition::SetBase(base) => format!("'/{}'", base),
        }
    } else {
        format!("f'/{{acc}}_{}'", field.name)
    };

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

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

    if metadata.is_pattern_type(&field.rust_type) {
        writeln!(
            output,
            "        self.{}: {} = {}(client, f'{{base_path}}/{}')",
            field_name, py_type, 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,
            "        self.{}: {} = {}(client, f'{{base_path}}/{}')",
            field_name, py_type, accessor.name, field.name
        )
        .unwrap();
    } else {
        writeln!(
            output,
            "        self.{}: {} = MetricNode(client, f'{{base_path}}/{}')",
            field_name, py_type, field.name
        )
        .unwrap();
    }
}

/// Convert pattern field to Python type annotation
fn field_to_python_type(field: &PatternField, metadata: &ClientMetadata) -> String {
    field_to_python_type_generic(field, metadata, false)
}

/// Convert pattern field to Python type annotation, with optional generic support
fn field_to_python_type_generic(
    field: &PatternField,
    metadata: &ClientMetadata,
    is_generic: bool,
) -> String {
    field_to_python_type_with_generic_value(field, metadata, is_generic, None)
}

/// Convert pattern field to Python 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_python_type_with_generic_value(
    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!("{}[{}]", field.rust_type, vt);
        }
        field.rust_type.clone()
    } else if let Some(accessor) = metadata.find_index_set_pattern(&field.indexes) {
        // Leaf with accessor - use value_type as the generic
        format!("{}[{}]", accessor.name, value_type)
    } else {
        // Leaf - use value_type as the generic
        format!("MetricNode[{}]", value_type)
    }
}


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

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

/// Recursively generate tree classes
fn generate_tree_class(
    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)
    if pattern_lookup.contains_key(&fields) && pattern_lookup.get(&fields) != Some(&name.to_string())
    {
        return;
    }

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

    writeln!(output, "class {}:", name).unwrap();
    writeln!(output, "    \"\"\"Catalog tree node.\"\"\"").unwrap();
    writeln!(output, "    ").unwrap();
    writeln!(
        output,
        "    def __init__(self, client: BrkClientBase, base_path: str = ''):"
    )
    .unwrap();

    for ((field, child_fields_opt), (child_name, child_node)) in
        fields_with_child_info.iter().zip(children.iter())
    {
        let generic_value_type = child_fields_opt
            .as_ref()
            .and_then(|cf| metadata.get_generic_value_type(&field.rust_type, cf));
        let py_type = field_to_python_type_with_generic_value(
            field,
            metadata,
            false,
            generic_value_type.as_deref(),
        );
        let field_name_py = 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,
                    "        self.{}: {} = {}(client, '{}')",
                    field_name_py, py_type, field.rust_type, metric_base
                )
                .unwrap();
            } else {
                writeln!(
                    output,
                    "        self.{}: {} = {}(client, f'{{base_path}}/{}')",
                    field_name_py, py_type, 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,
                    "        self.{}: {} = {}(client, f'{}')",
                    field_name_py, py_type, accessor.name, metric_path
                )
                .unwrap();
            } else {
                writeln!(
                    output,
                    "        self.{}: {} = {}(client, '{}')",
                    field_name_py, py_type, 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,
                    "        self.{}: {} = MetricNode(client, f'{}')",
                    field_name_py, py_type, metric_path
                )
                .unwrap();
            } else {
                writeln!(
                    output,
                    "        self.{}: {} = MetricNode(client, '{}')",
                    field_name_py, py_type, metric_path
                )
                .unwrap();
            }
        }
    }

    writeln!(output).unwrap();

    // Generate child classes
    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_class_name = format!("{}_{}", name, to_pascal_case(child_name));
                generate_tree_class(
                    output,
                    &child_class_name,
                    child_node,
                    pattern_lookup,
                    metadata,
                    generated,
                );
            }
        }
    }
}

/// Generate the main client class
fn generate_main_client(output: &mut String, endpoints: &[Endpoint]) {
    writeln!(output, "class BrkClient(BrkClientBase):").unwrap();
    writeln!(
        output,
        "    \"\"\"Main BRK client with catalog tree and API methods.\"\"\""
    )
    .unwrap();
    writeln!(output, "    ").unwrap();
    writeln!(
        output,
        "    def __init__(self, base_url: str = 'http://localhost:3000', timeout: float = 30.0):"
    )
    .unwrap();
    writeln!(output, "        super().__init__(base_url, timeout)").unwrap();
    writeln!(output, "        self.tree = CatalogTree(self)").unwrap();
    writeln!(output).unwrap();

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

/// 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_python)
            .unwrap_or_else(|| "Any".to_string());

        // Build method signature
        let params = build_method_params(endpoint);
        writeln!(
            output,
            "    def {}(self{}) -> {}:",
            method_name, params, return_type
        )
        .unwrap();

        // Docstring
        if let Some(summary) = &endpoint.summary {
            writeln!(output, "        \"\"\"{}\"\"\"", summary).unwrap();
        }

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

        if endpoint.query_params.is_empty() {
            if endpoint.path_params.is_empty() {
                writeln!(output, "        return self.get('{}')", path).unwrap();
            } else {
                writeln!(output, "        return self.get(f'{}')", path).unwrap();
            }
        } else {
            writeln!(output, "        params = []").unwrap();
            for param in &endpoint.query_params {
                // Use safe name for Python variable, original name for API query parameter
                let safe_name = escape_python_keyword(&param.name);
                if param.required {
                    writeln!(
                        output,
                        "        params.append(f'{}={{{}}}')",
                        param.name, safe_name
                    )
                    .unwrap();
                } else {
                    writeln!(
                        output,
                        "        if {} is not None: params.append(f'{}={{{}}}')",
                        safe_name, param.name, safe_name
                    )
                    .unwrap();
                }
            }
            writeln!(output, "        query = '&'.join(params)").unwrap();
            writeln!(
                output,
                "        return self.get(f'{}{{\"?\" + query if query else \"\"}}')",
                path
            )
            .unwrap();
        }

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

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

/// Convert JS-style type to Python type (e.g., "Txid[]" -> "List[Txid]", "number" -> "int")
fn js_type_to_python(js_type: &str) -> String {
    if let Some(inner) = js_type.strip_suffix("[]") {
        format!("List[{}]", js_type_to_python(inner))
    } else {
        match js_type {
            "number" => "int".to_string(),
            "boolean" => "bool".to_string(),
            "string" => "str".to_string(),
            "null" => "None".to_string(),
            "Object" | "object" => "dict".to_string(),
            "*" => "Any".to_string(),
            _ => js_type.to_string(),
        }
    }
}

fn build_method_params(endpoint: &Endpoint) -> String {
    let mut params = Vec::new();
    for param in &endpoint.path_params {
        let safe_name = escape_python_keyword(&param.name);
        params.push(format!(", {}: str", safe_name));
    }
    for param in &endpoint.query_params {
        let safe_name = escape_python_keyword(&param.name);
        if param.required {
            params.push(format!(", {}: str", safe_name));
        } else {
            params.push(format!(", {}: Optional[str] = None", safe_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);
        // Use escaped name for Python variable interpolation in f-string
        let safe_name = escape_python_keyword(&param.name);
        let interpolation = format!("{{{}}}", safe_name);
        result = result.replace(&placeholder, &interpolation);
    }
    result
}