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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
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_first_leaf_name,
    get_node_fields, get_pattern_instance_base, to_camel_case, to_pascal_case,
};

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

    // Header
    writeln!(output, "// Auto-generated BRK JavaScript client").unwrap();
    writeln!(output, "// Do not edit manually\n").unwrap();

    // Generate type definitions from OpenAPI schemas
    generate_type_definitions(&mut output, schemas);

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

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

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

    // Generate tree JSDoc typedefs
    generate_tree_typedefs(&mut output, &metadata.catalog, metadata);

    // Generate the main client class with tree and API methods
    generate_main_client(&mut output, &metadata.catalog, metadata, endpoints);

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

    Ok(())
}

/// Generate JSDoc 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();

    for (name, schema) in schemas {
        let js_type = schema_to_js_type_ctx(schema, Some(name));

        if is_primitive_alias(schema) {
            // Simple type alias: @typedef {number} Height
            writeln!(output, "/** @typedef {{{}}} {} */", js_type, name).unwrap();
        } else if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
            // Object type with properties
            writeln!(output, "/**").unwrap();
            writeln!(output, " * @typedef {{Object}} {}", name).unwrap();
            for (prop_name, prop_schema) in props {
                let prop_type = schema_to_js_type_ctx(prop_schema, Some(name));
                let required = schema
                    .get("required")
                    .and_then(|r| r.as_array())
                    .map(|arr| arr.iter().any(|v| v.as_str() == Some(prop_name)))
                    .unwrap_or(false);
                let optional = if required { "" } else { "=" };
                writeln!(
                    output,
                    " * @property {{{}{}}} {}",
                    prop_type, optional, prop_name
                )
                .unwrap();
            }
            writeln!(output, " */").unwrap();
        } else {
            // Other schemas - just typedef
            writeln!(output, "/** @typedef {{{}}} {} */", js_type, name).unwrap();
        }
    }
    writeln!(output).unwrap();
}

/// Check if schema represents a primitive type alias (like Height = number)
fn is_primitive_alias(schema: &Value) -> bool {
    schema.get("properties").is_none()
        && schema.get("items").is_none()
        && schema.get("anyOf").is_none()
        && schema.get("oneOf").is_none()
        && schema.get("enum").is_none()
}

/// Convert a single JSON type string to JavaScript type
fn json_type_to_js(ty: &str, schema: &Value, current_type: Option<&str>) -> String {
    match ty {
        "integer" | "number" => "number".to_string(),
        "boolean" => "boolean".to_string(),
        "string" => "string".to_string(),
        "null" => "null".to_string(),
        "array" => {
            let item_type = schema
                .get("items")
                .map(|s| schema_to_js_type_ctx(s, current_type))
                .unwrap_or_else(|| "*".to_string());
            format!("{}[]", item_type)
        }
        "object" => {
            // Check if it has additionalProperties (dict-like)
            if let Some(add_props) = schema.get("additionalProperties") {
                let value_type = schema_to_js_type_ctx(add_props, current_type);
                // Use TypeScript index signature syntax for recursive types
                return format!("{{ [key: string]: {} }}", value_type);
            }
            "Object".to_string()
        }
        _ => "*".to_string(),
    }
}

/// Convert JSON Schema to JavaScript/JSDoc type with context for recursive types
fn schema_to_js_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_js_type_ctx(item, current_type);
            if resolved != "*" {
                return resolved;
            }
        }
    }

    // Handle $ref
    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
        return ref_path.rsplit('/').next().unwrap_or("*").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!("({})", 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")
                .map(|t| json_type_to_js(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!("?{}", base_type)
                } else {
                    base_type.clone()
                };
            } else if !types.is_empty() {
                let union = format!("({})", types.join("|"));
                return if has_null {
                    format!("?{}", union)
                } else {
                    union
                };
            }
        }

        // Handle single type string
        if let Some(ty_str) = ty.as_str() {
            return json_type_to_js(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_js_type_ctx(v, current_type))
            .collect();
        // Filter out * and null for cleaner unions
        let filtered: Vec<_> = types.iter().filter(|t| *t != "*").collect();
        if !filtered.is_empty() {
            return format!(
                "({})",
                filtered
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join("|")
            );
        }
        return format!("({})", 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" => "number".to_string(),
            "float" | "double" => "number".to_string(),
            "date" | "date-time" => "string".to_string(),
            _ => "*".to_string(),
        };
    }

    "*".to_string()
}

/// Generate the base BrkClient class with HTTP functionality
fn generate_base_client(output: &mut String) {
    writeln!(
        output,
        r#"/**
 * @typedef {{Object}} BrkClientOptions
 * @property {{string}} baseUrl - Base URL for the API
 * @property {{number}} [timeout] - Request timeout in milliseconds
 */

const _isBrowser = typeof window !== 'undefined' && 'caches' in window;
const _runIdle = (fn) => (globalThis.requestIdleCallback ?? setTimeout)(fn);

/** @type {{Promise<Cache | null>}} */
const _cachePromise = _isBrowser
  ? caches.open('__BRK_CLIENT__').catch(() => null)
  : Promise.resolve(null);

/**
 * Custom error class for BRK client errors
 */
class BrkError extends Error {{
  /**
   * @param {{string}} message
   * @param {{number}} [status]
   */
  constructor(message, status) {{
    super(message);
    this.name = 'BrkError';
    this.status = status;
  }}
}}

/**
 * A metric node that can fetch data for different indexes.
 * @template T
 */
class MetricNode {{
  /**
   * @param {{BrkClientBase}} client
   * @param {{string}} path
   */
  constructor(client, path) {{
    this._client = client;
    this._path = path;
  }}

  /**
   * Fetch all data points for this metric.
   * @param {{(value: T[]) => void}} [onUpdate] - Called when data is available (may be called twice: cache then fresh)
   * @returns {{Promise<T[] | null>}}
   */
  get(onUpdate) {{
    return this._client.get(this._path, onUpdate);
  }}

  /**
   * Fetch data points within a range.
   * @param {{string | number}} from
   * @param {{string | number}} to
   * @param {{(value: T[]) => void}} [onUpdate] - Called when data is available (may be called twice: cache then fresh)
   * @returns {{Promise<T[] | null>}}
   */
  getRange(from, to, onUpdate) {{
    return this._client.get(`${{this._path}}?from=${{from}}&to=${{to}}`, onUpdate);
  }}
}}

/**
 * Base HTTP client for making requests with caching support
 */
class BrkClientBase {{
  /**
   * @param {{BrkClientOptions|string}} options
   */
  constructor(options) {{
    const isString = typeof options === 'string';
    this.baseUrl = isString ? options : options.baseUrl;
    this.timeout = isString ? 5000 : (options.timeout ?? 5000);
  }}

  /**
   * Make a GET request with stale-while-revalidate caching
   * @template T
   * @param {{string}} path
   * @param {{(value: T) => void}} [onUpdate] - Called when data is available
   * @returns {{Promise<T | null>}}
   */
  async get(path, onUpdate) {{
    const url = `${{this.baseUrl}}${{path}}`;
    const cache = await _cachePromise;
    const cachedRes = await cache?.match(url);
    const cachedJson = cachedRes ? await cachedRes.json() : null;

    if (cachedJson) onUpdate?.(cachedJson);
    if (!globalThis.navigator?.onLine) return cachedJson;

    try {{
      const res = await fetch(url, {{ signal: AbortSignal.timeout(this.timeout) }});
      if (!res.ok) throw new BrkError(`HTTP ${{res.status}}`, res.status);
      if (cachedRes?.headers.get('ETag') === res.headers.get('ETag')) return cachedJson;

      const cloned = res.clone();
      const json = await res.json();
      onUpdate?.(json);
      if (cache) _runIdle(() => cache.put(url, cloned));
      return json;
    }} catch (e) {{
      if (cachedJson) return cachedJson;
      throw e;
    }}
  }}
}}

"#
    )
    .unwrap();
}

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

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

    for pattern in patterns {
        // Generate JSDoc typedef for the accessor
        writeln!(output, "/**").unwrap();
        writeln!(output, " * @template T").unwrap();
        writeln!(output, " * @typedef {{Object}} {}", pattern.name).unwrap();
        for index in &pattern.indexes {
            let field_name = index_to_camel_case(index);
            writeln!(output, " * @property {{MetricNode<T>}} {}", field_name).unwrap();
        }
        writeln!(output, " */\n").unwrap();

        // Generate factory function
        writeln!(output, "/**").unwrap();
        writeln!(output, " * Create a {} accessor", pattern.name).unwrap();
        writeln!(output, " * @template T").unwrap();
        writeln!(output, " * @param {{BrkClientBase}} client").unwrap();
        writeln!(output, " * @param {{string}} basePath").unwrap();
        writeln!(output, " * @returns {{{}<T>}}", pattern.name).unwrap();
        writeln!(output, " */").unwrap();
        writeln!(
            output,
            "function create{}(client, basePath) {{",
            pattern.name
        )
        .unwrap();
        writeln!(output, "  return {{").unwrap();

        for (i, index) in pattern.indexes.iter().enumerate() {
            let field_name = index_to_camel_case(index);
            let path_segment = index.serialize_long();
            let comma = if i < pattern.indexes.len() - 1 {
                ","
            } else {
                ""
            };
            writeln!(
                output,
                "    {}: new MetricNode(client, `${{basePath}}/{}`){}",
                field_name, path_segment, comma
            )
            .unwrap();
        }

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

/// Convert an Index to a camelCase field name (e.g., DateIndex -> byDateIndex)
fn index_to_camel_case(index: &Index) -> String {
    format!("by{}", to_pascal_case(index.serialize_long()))
}

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

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

    for pattern in patterns {
        // Check if this pattern is parameterizable (has field positions detected)
        let is_parameterizable = pattern.is_parameterizable();

        // Generate JSDoc typedef
        writeln!(output, "/**").unwrap();
        if pattern.is_generic {
            writeln!(output, " * @template T").unwrap();
        }
        writeln!(output, " * @typedef {{Object}} {}", pattern.name).unwrap();
        for field in &pattern.fields {
            let js_type = field_to_js_type_generic(field, metadata, pattern.is_generic);
            writeln!(
                output,
                " * @property {{{}}} {}",
                js_type,
                to_camel_case(&field.name)
            )
            .unwrap();
        }
        writeln!(output, " */\n").unwrap();

        // Generate factory function
        writeln!(output, "/**").unwrap();
        writeln!(output, " * Create a {} pattern node", pattern.name).unwrap();
        writeln!(output, " * @param {{BrkClientBase}} client").unwrap();
        if is_parameterizable {
            writeln!(output, " * @param {{string}} acc - Accumulated metric name").unwrap();
        } else {
            writeln!(output, " * @param {{string}} basePath").unwrap();
        }
        writeln!(output, " * @returns {{{}}}", pattern.name).unwrap();
        writeln!(output, " */").unwrap();

        let param_name = if is_parameterizable {
            "acc"
        } else {
            "basePath"
        };
        writeln!(
            output,
            "function create{}(client, {}) {{",
            pattern.name, param_name
        )
        .unwrap();
        writeln!(output, "  return {{").unwrap();

        for (i, field) in pattern.fields.iter().enumerate() {
            let comma = if i < pattern.fields.len() - 1 {
                ","
            } else {
                ""
            };

            if is_parameterizable {
                generate_parameterized_field(output, field, pattern, metadata, comma);
            } else {
                generate_tree_path_field(output, field, metadata, comma);
            }
        }

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

/// Generate a field using parameterized (prepend/append) metric name construction
fn generate_parameterized_field(
    output: &mut String,
    field: &PatternField,
    pattern: &StructuralPattern,
    metadata: &ClientMetadata,
    comma: &str,
) {
    let field_name_js = to_camel_case(&field.name);

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

        writeln!(
            output,
            "    {}: create{}(client, {}){}",
            field_name_js, field.rust_type, child_acc, comma
        )
        .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!("`/${{acc}}{suffix}`"),
            FieldNamePosition::Prepend(prefix) => format!("`/{prefix}${{acc}}`"),
            FieldNamePosition::Identity => "`/${acc}`".to_string(),
            FieldNamePosition::SetBase(base) => format!("'/{base}'"),
        }
    } else {
        // Fallback: use field name appended
        format!("`/${{acc}}_{}`", field.name)
    };

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

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

    if metadata.is_pattern_type(&field.rust_type) {
        writeln!(
            output,
            "    {}: create{}(client, `${{basePath}}/{}`){}",
            field_name_js, field.rust_type, field.name, comma
        )
        .unwrap();
    } else if metadata.field_uses_accessor(field) {
        let accessor = metadata.find_index_set_pattern(&field.indexes).unwrap();
        writeln!(
            output,
            "    {}: create{}(client, `${{basePath}}/{}`){}",
            field_name_js, accessor.name, field.name, comma
        )
        .unwrap();
    } else {
        writeln!(
            output,
            "    {}: new MetricNode(client, `${{basePath}}/{}`){}",
            field_name_js, field.name, comma
        )
        .unwrap();
    }
}

/// Convert pattern field to JavaScript/JSDoc type, with optional generic support
fn field_to_js_type_generic(
    field: &PatternField,
    metadata: &ClientMetadata,
    is_generic: bool,
) -> String {
    field_to_js_type_with_generic_value(field, metadata, is_generic, None)
}

/// Convert pattern field to JavaScript/JSDoc type.
/// - `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_js_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 typedefs
fn generate_tree_typedefs(output: &mut String, catalog: &TreeNode, metadata: &ClientMetadata) {
    writeln!(output, "// Catalog tree typedefs\n").unwrap();

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

/// Recursively generate tree typedefs
fn generate_tree_typedef(
    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, "/**").unwrap();
    writeln!(output, " * @typedef {{Object}} {}", name).unwrap();

    for (field, child_fields) in &fields_with_child_info {
        let generic_value_type = child_fields
            .as_ref()
            .and_then(|cf| metadata.get_generic_value_type(&field.rust_type, cf));
        let js_type = field_to_js_type_with_generic_value(
            field,
            metadata,
            false,
            generic_value_type.as_deref(),
        );
        writeln!(
            output,
            " * @property {{{}}} {}",
            js_type,
            to_camel_case(&field.name)
        )
        .unwrap();
    }

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

    // Generate child typedefs
    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_type_name = format!("{}_{}", name, to_pascal_case(child_name));
                generate_tree_typedef(
                    output,
                    &child_type_name,
                    child_node,
                    pattern_lookup,
                    metadata,
                    generated,
                );
            }
        }
    }
}

/// Generate main client
fn generate_main_client(
    output: &mut String,
    catalog: &TreeNode,
    metadata: &ClientMetadata,
    endpoints: &[Endpoint],
) {
    let pattern_lookup = metadata.pattern_lookup();

    writeln!(output, "/**").unwrap();
    writeln!(
        output,
        " * Main BRK client with catalog tree and API methods"
    )
    .unwrap();
    writeln!(output, " * @extends BrkClientBase").unwrap();
    writeln!(output, " */").unwrap();
    writeln!(output, "class BrkClient extends BrkClientBase {{").unwrap();
    writeln!(output, "  /**").unwrap();
    writeln!(output, "   * @param {{BrkClientOptions|string}} options").unwrap();
    writeln!(output, "   */").unwrap();
    writeln!(output, "  constructor(options) {{").unwrap();
    writeln!(output, "    super(options);").unwrap();
    writeln!(output, "    /** @type {{CatalogTree}} */").unwrap();
    writeln!(output, "    this.tree = this._buildTree('');").unwrap();
    writeln!(output, "  }}\n").unwrap();

    // Generate _buildTree method
    writeln!(output, "  /**").unwrap();
    writeln!(output, "   * @private").unwrap();
    writeln!(output, "   * @param {{string}} basePath").unwrap();
    writeln!(output, "   * @returns {{CatalogTree}}").unwrap();
    writeln!(output, "   */").unwrap();
    writeln!(output, "  _buildTree(basePath) {{").unwrap();
    writeln!(output, "    return {{").unwrap();
    generate_tree_initializer(output, catalog, "", 3, &pattern_lookup, metadata);
    writeln!(output, "    }};").unwrap();
    writeln!(output, "  }}\n").unwrap();

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

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

    // Export
    writeln!(
        output,
        "export {{ BrkClient, BrkClientBase, BrkError, MetricNode }};"
    )
    .unwrap();
}

/// Generate tree initializer
fn generate_tree_initializer(
    output: &mut String,
    node: &TreeNode,
    accumulated_name: &str,
    indent: usize,
    pattern_lookup: &std::collections::HashMap<Vec<PatternField>, String>,
    metadata: &ClientMetadata,
) {
    let indent_str = "  ".repeat(indent);

    if let TreeNode::Branch(children) = node {
        for (i, (child_name, child_node)) in children.iter().enumerate() {
            let field_name = to_camel_case(child_name);
            let comma = if i < children.len() - 1 { "," } else { "" };

            match child_node {
                TreeNode::Leaf(leaf) => {
                    // Use leaf.name() (vec.name()) for API path, not tree path
                    let metric_path = format!("/{}", leaf.name());
                    if let Some(accessor) = metadata.find_index_set_pattern(leaf.indexes()) {
                        writeln!(
                            output,
                            "{}{}: create{}(this, '{}'){}",
                            indent_str, field_name, accessor.name, metric_path, comma
                        )
                        .unwrap();
                    } else {
                        writeln!(
                            output,
                            "{}{}: new MetricNode(this, '{}'){}",
                            indent_str, field_name, metric_path, comma
                        )
                        .unwrap();
                    }
                }
                TreeNode::Branch(grandchildren) => {
                    let child_fields = get_node_fields(grandchildren, pattern_lookup);
                    if let Some(pattern_name) = pattern_lookup.get(&child_fields) {
                        // For parameterized patterns, derive accumulated metric name from first leaf
                        let pattern = metadata
                            .structural_patterns
                            .iter()
                            .find(|p| &p.name == pattern_name);
                        let is_parameterizable =
                            pattern.map(|p| p.is_parameterizable()).unwrap_or(false);

                        let arg = if is_parameterizable {
                            // Get the metric base from the first leaf descendant
                            get_pattern_instance_base(child_node, child_name)
                        } else {
                            // Fallback to tree path for non-parameterizable patterns
                            if accumulated_name.is_empty() {
                                format!("/{}", child_name)
                            } else {
                                format!("{}/{}", accumulated_name, child_name)
                            }
                        };

                        writeln!(
                            output,
                            "{}{}: create{}(this, '{}'){}",
                            indent_str, field_name, pattern_name, arg, comma
                        )
                        .unwrap();
                    } else {
                        // Not a pattern - recurse with accumulated name
                        let child_acc =
                            infer_child_accumulated_name(child_node, accumulated_name, child_name);
                        writeln!(output, "{}{}: {{", indent_str, field_name).unwrap();
                        generate_tree_initializer(
                            output,
                            child_node,
                            &child_acc,
                            indent + 1,
                            pattern_lookup,
                            metadata,
                        );
                        writeln!(output, "{}}}{}", indent_str, comma).unwrap();
                    }
                }
            }
        }
    }
}

/// Infer the accumulated metric name for a child node
fn infer_child_accumulated_name(node: &TreeNode, parent_acc: &str, field_name: &str) -> String {
    // Try to infer from first leaf descendant
    if let Some(leaf_name) = get_first_leaf_name(node) {
        // Look for field_name in the leaf metric name
        if let Some(pos) = leaf_name.find(field_name) {
            // The field_name appears in the metric - use it as base
            if pos == 0 {
                // At start - this is the base
                return field_name.to_string();
            } else if leaf_name.chars().nth(pos - 1) == Some('_') {
                // After underscore - likely an append pattern
                if parent_acc.is_empty() {
                    return field_name.to_string();
                }
                return format!("{}_{}", parent_acc, field_name);
            }
        }
    }

    // Fallback: append field name
    if parent_acc.is_empty() {
        field_name.to_string()
    } else {
        format!("{}_{}", parent_acc, field_name)
    }
}

/// Generate API methods
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().unwrap_or("*");

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

        for param in &endpoint.path_params {
            let desc = param.description.as_deref().unwrap_or("");
            writeln!(
                output,
                "   * @param {{{}}} {} {}",
                param.param_type, param.name, desc
            )
            .unwrap();
        }
        for param in &endpoint.query_params {
            let optional = if param.required { "" } else { "=" };
            let desc = param.description.as_deref().unwrap_or("");
            writeln!(
                output,
                "   * @param {{{}{}}} [{}] {}",
                param.param_type, optional, param.name, desc
            )
            .unwrap();
        }

        writeln!(output, "   * @returns {{Promise<{}>}}", return_type).unwrap();
        writeln!(output, "   */").unwrap();

        let params = build_method_params(endpoint);
        writeln!(output, "  async {}({}) {{", method_name, params).unwrap();

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

        if endpoint.query_params.is_empty() {
            writeln!(output, "    return this.get(`{}`);", path).unwrap();
        } else {
            writeln!(output, "    const params = new URLSearchParams();").unwrap();
            for param in &endpoint.query_params {
                if param.required {
                    writeln!(
                        output,
                        "    params.set('{}', String({}));",
                        param.name, param.name
                    )
                    .unwrap();
                } else {
                    writeln!(
                        output,
                        "    if ({} !== undefined) params.set('{}', String({}));",
                        param.name, param.name, param.name
                    )
                    .unwrap();
                }
            }
            writeln!(output, "    const query = params.toString();").unwrap();
            writeln!(
                output,
                "    return this.get(`{}${{query ? '?' + query : ''}}`);",
                path
            )
            .unwrap();
        }

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

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

fn build_method_params(endpoint: &Endpoint) -> String {
    let mut params = Vec::new();
    for param in &endpoint.path_params {
        params.push(param.name.clone());
    }
    for param in &endpoint.query_params {
        params.push(param.name.clone());
    }
    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
}