Skip to main content

alef_e2e/codegen/
ruby.rs

1//! Ruby e2e test generator using RSpec.
2//!
3//! Generates `e2e/ruby/Gemfile` and `spec/{category}_spec.rb` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{ruby_string_literal, ruby_template_to_interpolation, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{
11    Assertion, CallbackAction, Fixture, FixtureGroup, TemplateReturnForm, ValidationErrorExpectation,
12};
13use alef_core::backend::GeneratedFile;
14use alef_core::config::ResolvedCrateConfig;
15use alef_core::hash::{self, CommentStyle};
16use alef_core::template_versions as tv;
17use anyhow::Result;
18use heck::ToSnakeCase;
19use std::collections::HashMap;
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24use super::client;
25
26/// Ruby e2e code generator.
27pub struct RubyCodegen;
28
29impl E2eCodegen for RubyCodegen {
30    fn generate(
31        &self,
32        groups: &[FixtureGroup],
33        e2e_config: &E2eConfig,
34        config: &ResolvedCrateConfig,
35        _type_defs: &[alef_core::ir::TypeDef],
36    ) -> Result<Vec<GeneratedFile>> {
37        let lang = self.language_name();
38        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
39
40        let mut files = Vec::new();
41
42        // Resolve call config with overrides.
43        let call = &e2e_config.call;
44        let overrides = call.overrides.get(lang);
45        let module_path = overrides
46            .and_then(|o| o.module.as_ref())
47            .cloned()
48            .unwrap_or_else(|| call.module.clone());
49        let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
50        let options_type = overrides.and_then(|o| o.options_type.clone());
51        let empty_enum_fields = HashMap::new();
52        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
53        let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
54
55        // Resolve package config.
56        let ruby_pkg = e2e_config.resolve_package("ruby");
57        let gem_name = ruby_pkg
58            .as_ref()
59            .and_then(|p| p.name.as_ref())
60            .cloned()
61            .unwrap_or_else(|| config.name.replace('-', "_"));
62        let gem_path = ruby_pkg
63            .as_ref()
64            .and_then(|p| p.path.as_ref())
65            .cloned()
66            .unwrap_or_else(|| "../../packages/ruby".to_string());
67        let gem_version = ruby_pkg
68            .as_ref()
69            .and_then(|p| p.version.as_ref())
70            .cloned()
71            .or_else(|| config.resolved_version())
72            .unwrap_or_else(|| "0.1.0".to_string());
73
74        // Generate Gemfile.
75        files.push(GeneratedFile {
76            path: output_base.join("Gemfile"),
77            content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
78            generated_header: false,
79        });
80
81        // Generate .rubocop.yaml for linting generated specs.
82        files.push(GeneratedFile {
83            path: output_base.join(".rubocop.yaml"),
84            content: render_rubocop_yaml(),
85            generated_header: false,
86        });
87
88        // Check if any fixture is an HTTP test (needs mock server bootstrap).
89        let has_http_fixtures = groups
90            .iter()
91            .flat_map(|g| g.fixtures.iter())
92            .any(|f| f.needs_mock_server());
93
94        // Check if any fixture uses file_path or bytes args (needs chdir to test_documents).
95        let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
96            let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
97            cc.args
98                .iter()
99                .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
100        });
101
102        // Always generate spec/spec_helper.rb when file-based or HTTP fixtures are present.
103        if has_file_fixtures || has_http_fixtures {
104            files.push(GeneratedFile {
105                path: output_base.join("spec").join("spec_helper.rb"),
106                content: render_spec_helper(
107                    has_file_fixtures,
108                    has_http_fixtures,
109                    &e2e_config.test_documents_relative_from(1),
110                ),
111                generated_header: true,
112            });
113        }
114
115        // Generate spec files per category.
116        let spec_base = output_base.join("spec");
117
118        for group in groups {
119            let active: Vec<&Fixture> = group
120                .fixtures
121                .iter()
122                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
123                .collect();
124
125            if active.is_empty() {
126                continue;
127            }
128
129            let field_resolver_pre = FieldResolver::new(
130                &e2e_config.fields,
131                &e2e_config.fields_optional,
132                &e2e_config.result_fields,
133                &e2e_config.fields_array,
134                &std::collections::HashSet::new(),
135            );
136            // Skip the entire file if no fixture in this category produces output.
137            let has_any_output = active.iter().any(|f| {
138                // HTTP tests always produce output.
139                if f.is_http_test() {
140                    return true;
141                }
142                let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
143                let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
144                expects_error || has_not_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
145            });
146            if !has_any_output {
147                continue;
148            }
149
150            let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
151            let field_resolver = FieldResolver::new(
152                &e2e_config.fields,
153                &e2e_config.fields_optional,
154                &e2e_config.result_fields,
155                &e2e_config.fields_array,
156                &std::collections::HashSet::new(),
157            );
158            let content = render_spec_file(
159                &group.category,
160                &active,
161                &module_path,
162                class_name.as_deref(),
163                &gem_name,
164                &field_resolver,
165                options_type.as_deref(),
166                enum_fields,
167                result_is_simple,
168                e2e_config,
169                has_file_fixtures || has_http_fixtures,
170            );
171            files.push(GeneratedFile {
172                path: spec_base.join(filename),
173                content,
174                generated_header: true,
175            });
176        }
177
178        Ok(files)
179    }
180
181    fn language_name(&self) -> &'static str {
182        "ruby"
183    }
184}
185
186// ---------------------------------------------------------------------------
187// Rendering
188// ---------------------------------------------------------------------------
189
190fn render_gemfile(
191    gem_name: &str,
192    gem_path: &str,
193    gem_version: &str,
194    dep_mode: crate::config::DependencyMode,
195) -> String {
196    let gem_line = match dep_mode {
197        crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
198        crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
199    };
200    crate::template_env::render(
201        "ruby/Gemfile.jinja",
202        minijinja::context! {
203            gem_line => gem_line,
204            rspec => tv::gem::RSPEC_E2E,
205            rubocop => tv::gem::RUBOCOP_E2E,
206            rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
207            faraday => tv::gem::FARADAY,
208        },
209    )
210}
211
212fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
213    let header = hash::header(CommentStyle::Hash);
214    let mut out = header;
215    out.push_str("# frozen_string_literal: true\n");
216
217    if has_file_fixtures {
218        let _ = writeln!(out);
219        let _ = writeln!(
220            out,
221            "# Change to the configured test-documents directory so that fixture file paths like"
222        );
223        let _ = writeln!(
224            out,
225            "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
226        );
227        let _ = writeln!(
228            out,
229            "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
230        );
231        let _ = writeln!(
232            out,
233            "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
234        );
235        let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
236    }
237
238    if has_http_fixtures {
239        out.push_str(
240            r#"
241require 'json'
242require 'open3'
243
244# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
245RSpec.configure do |config|
246  config.before(:suite) do
247    bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
248    fixtures_dir = File.expand_path('../../../fixtures', __dir__)
249    unless File.exist?(bin)
250      warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
251    end
252    stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
253    # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
254    url = nil
255    8.times do
256      line = stdout.readline.strip rescue break
257      if line.start_with?('MOCK_SERVER_URL=')
258        url = line.split('=', 2).last
259        ENV['MOCK_SERVER_URL'] = url
260      elsif line.start_with?('MOCK_SERVERS=')
261        json_val = line.split('=', 2).last
262        ENV['MOCK_SERVERS'] = json_val
263        JSON.parse(json_val).each do |fid, furl|
264          ENV["MOCK_SERVER_#{fid.upcase}"] = furl
265        end
266        break
267      elsif url
268        break
269      end
270    end
271    # Drain stdout in background.
272    Thread.new { stdout.read }
273    # Store stdin so we can close it on teardown.
274    @_mock_server_stdin = stdin
275  end
276
277  config.after(:suite) do
278    @_mock_server_stdin&.close
279  end
280end
281"#,
282        );
283    }
284
285    out
286}
287
288fn render_rubocop_yaml() -> String {
289    crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
290}
291
292#[allow(clippy::too_many_arguments)]
293fn render_spec_file(
294    category: &str,
295    fixtures: &[&Fixture],
296    module_path: &str,
297    class_name: Option<&str>,
298    gem_name: &str,
299    field_resolver: &FieldResolver,
300    options_type: Option<&str>,
301    enum_fields: &HashMap<String, String>,
302    result_is_simple: bool,
303    e2e_config: &E2eConfig,
304    needs_spec_helper: bool,
305) -> String {
306    // Resolve client_factory from ruby override.
307    let client_factory = e2e_config
308        .call
309        .overrides
310        .get("ruby")
311        .and_then(|o| o.client_factory.as_deref());
312
313    // Build requires list
314    let require_name = if module_path.is_empty() { gem_name } else { module_path };
315    let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
316
317    let has_http = fixtures.iter().any(|f| f.is_http_test());
318    if needs_spec_helper || has_http {
319        requires.push("spec_helper".to_string());
320    }
321
322    // Build the Ruby module/class qualifier for calls.
323    let call_receiver = class_name
324        .map(|s| s.to_string())
325        .unwrap_or_else(|| ruby_module_name(module_path));
326
327    // Check for array contains assertions
328    let has_array_contains = fixtures.iter().any(|fixture| {
329        fixture.assertions.iter().any(|a| {
330            matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
331                && a.field
332                    .as_deref()
333                    .is_some_and(|f| !f.is_empty() && field_resolver.is_array(field_resolver.resolve(f)))
334        })
335    });
336
337    // Build examples
338    let mut examples = Vec::new();
339    for fixture in fixtures {
340        if fixture.http.is_some() {
341            // HTTP example is handled separately (uses shared driver)
342            let mut out = String::new();
343            render_http_example(&mut out, fixture);
344            examples.push(out);
345        } else {
346            // Resolve per-fixture call config so we can detect streaming up front.
347            let fixture_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
348            let fixture_call_overrides = fixture_call.overrides.get("ruby");
349            let raw_function_name = fixture_call_overrides
350                .and_then(|o| o.function.as_ref())
351                .cloned()
352                .unwrap_or_else(|| fixture_call.function.clone());
353
354            let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
355            let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
356            let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
357            let is_streaming = raw_function_name == "chat_stream";
358
359            // Non-HTTP, non-streaming fixtures with no usable assertions stay pending.
360            // A fixture whose only assertion is `not_error` is still testable — it
361            // verifies the call does not raise, so route it to render_example.
362            if !expects_error && !has_usable && !has_not_error && !is_streaming {
363                let test_name = sanitize_ident(&fixture.id);
364                let description = fixture.description.replace('\'', "\\'");
365                let mut out = String::new();
366                out.push_str(&format!("  it '{test_name}: {description}' do\n"));
367                out.push_str("    skip 'Non-HTTP fixture cannot be tested via Net::HTTP'\n");
368                out.push_str("  end\n");
369                examples.push(out);
370            } else {
371                // Streaming methods do not take the `_async` suffix — Magnus emits
372                // `chat_stream` as a block-yielding method. All other async Rust
373                // methods are bound with the `_async` suffix.
374                let fixture_function_name = if is_streaming {
375                    raw_function_name
376                } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
377                    format!("{raw_function_name}_async")
378                } else {
379                    raw_function_name
380                };
381                let fixture_result_var = &fixture_call.result_var;
382                let fixture_args = &fixture_call.args;
383                let fixture_client_factory = fixture_call_overrides
384                    .and_then(|o| o.client_factory.as_deref())
385                    .or(client_factory);
386                let fixture_options_type = fixture_call_overrides
387                    .and_then(|o| o.options_type.as_deref())
388                    .or(options_type);
389
390                let fixture_extra_args: Vec<String> =
391                    fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
392                // Use per-fixture-call result_is_simple so per-call overrides like
393                // `speech` (returns bytes) take precedence over the top-level call default.
394                let fixture_result_is_simple =
395                    fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
396                // Per-call enum_fields take precedence — e.g. `[crates.e2e.calls.create_batch.overrides.ruby] enum_fields`
397                // labels `status = "BatchStatus"` for the batch lifecycle, but the global
398                // `[crates.e2e.call.overrides.ruby]` map only carries chat-shape entries.
399                let fixture_enum_fields: &HashMap<String, String> =
400                    fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
401                let example = if is_streaming {
402                    render_chat_stream_example(
403                        fixture,
404                        &fixture_function_name,
405                        &call_receiver,
406                        fixture_args,
407                        fixture_options_type,
408                        fixture_enum_fields,
409                        e2e_config,
410                        fixture_client_factory,
411                        &fixture_extra_args,
412                    )
413                } else {
414                    render_example(
415                        fixture,
416                        &fixture_function_name,
417                        &call_receiver,
418                        fixture_result_var,
419                        fixture_args,
420                        field_resolver,
421                        fixture_options_type,
422                        fixture_enum_fields,
423                        fixture_result_is_simple,
424                        e2e_config,
425                        fixture_client_factory,
426                        &fixture_extra_args,
427                    )
428                };
429                examples.push(example);
430            }
431        }
432    }
433
434    let header = hash::header(CommentStyle::Hash);
435    crate::template_env::render(
436        "ruby/test_file.jinja",
437        minijinja::context! {
438            category => category,
439            requires => requires,
440            has_array_contains => has_array_contains,
441            has_http => has_http,
442            examples => examples,
443            header => header,
444        },
445    )
446}
447
448/// Check if a fixture has at least one assertion that will produce an executable
449/// expect() call (not just a skip comment).
450fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
451    fixture.assertions.iter().any(|a| {
452        // not_error is implicit (call succeeding), error is handled separately.
453        if a.assertion_type == "not_error" || a.assertion_type == "error" {
454            return false;
455        }
456        // Check field validity.
457        if let Some(f) = &a.field {
458            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
459                return false;
460            }
461            // When result_is_simple, skip non-content fields.
462            if result_is_simple {
463                let f_lower = f.to_lowercase();
464                if !f.is_empty()
465                    && f_lower != "content"
466                    && (f_lower.starts_with("metadata")
467                        || f_lower.starts_with("document")
468                        || f_lower.starts_with("structure"))
469                {
470                    return false;
471                }
472            }
473        }
474        true
475    })
476}
477
478// ---------------------------------------------------------------------------
479// HTTP test rendering — shared-driver integration
480// ---------------------------------------------------------------------------
481
482/// Thin renderer that emits RSpec `describe` + `it` blocks targeting a mock server
483/// via `Net::HTTP`. Satisfies [`client::TestClientRenderer`] so the shared
484/// [`client::http_call::render_http_test`] driver drives the call sequence.
485struct RubyTestClientRenderer;
486
487impl client::TestClientRenderer for RubyTestClientRenderer {
488    fn language_name(&self) -> &'static str {
489        "ruby"
490    }
491
492    /// Emit `describe '{fn_name}' do` + inner `it '{description}' do`.
493    ///
494    /// `fn_name` is the sanitised fixture id used as the describe label.
495    /// When `skip_reason` is `Some`, the inner `it` block gets a `skip` call so
496    /// the shared driver short-circuits before emitting any assertions.
497    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
498        let escaped_description = description.replace('\'', "\\'");
499        let rendered = crate::template_env::render(
500            "ruby/http_test.jinja",
501            minijinja::context! {
502                fn_name => fn_name,
503                description => escaped_description,
504                skip_reason => skip_reason,
505            },
506        );
507        out.push_str(&rendered);
508    }
509
510    /// Close the inner `it` block and the outer `describe` block.
511    fn render_test_close(&self, out: &mut String) {
512        let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
513        out.push_str(&rendered);
514    }
515
516    /// Emit a `Net::HTTP` request to the mock server using the path from `ctx`.
517    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
518        let method = ctx.method.to_uppercase();
519        let method_class = http_method_class(&method);
520
521        let has_body = ctx
522            .body
523            .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
524
525        let ruby_body = if has_body {
526            json_to_ruby(ctx.body.unwrap())
527        } else {
528            String::new()
529        };
530
531        let headers: Vec<minijinja::Value> = ctx
532            .headers
533            .iter()
534            .filter(|(k, _)| {
535                // Skip Content-Type when already set from the body above.
536                !(has_body && k.to_lowercase() == "content-type")
537            })
538            .map(|(k, v)| {
539                minijinja::context! {
540                    key_literal => ruby_string_literal(k),
541                    value_literal => ruby_string_literal(v),
542                }
543            })
544            .collect();
545
546        let rendered = crate::template_env::render(
547            "ruby/http_request.jinja",
548            minijinja::context! {
549                method_class => method_class,
550                path => ctx.path,
551                has_body => has_body,
552                ruby_body => ruby_body,
553                headers => headers,
554                response_var => ctx.response_var,
555            },
556        );
557        out.push_str(&rendered);
558    }
559
560    /// Emit `expect(response.code.to_i).to eq(status)`.
561    ///
562    /// Net::HTTP returns the HTTP status as a `String`; `.to_i` converts it for
563    /// comparison with the integer literal from the fixture.
564    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
565        out.push_str(&format!("      expect({response_var}.code.to_i).to eq({status})\n"));
566    }
567
568    /// Emit a header assertion using `response[header_key]`.
569    ///
570    /// Handles the three special tokens: `<<present>>`, `<<absent>>`, `<<uuid>>`.
571    fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
572        let header_key = name.to_lowercase();
573        let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
574        let assertion = match expected {
575            "<<present>>" => {
576                format!("      expect({header_expr}).not_to be_nil\n")
577            }
578            "<<absent>>" => {
579                format!("      expect({header_expr}).to be_nil\n")
580            }
581            "<<uuid>>" => {
582                format!(
583                    "      expect({header_expr}).to match(/\\A[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}\\z/i)\n"
584                )
585            }
586            literal => {
587                let ruby_val = ruby_string_literal(literal);
588                format!("      expect({header_expr}).to eq({ruby_val})\n")
589            }
590        };
591        out.push_str(&assertion);
592    }
593
594    /// Emit a full JSON body equality assertion.
595    ///
596    /// Plain string bodies are compared as raw text; structured bodies are parsed
597    /// with `JSON.parse` and compared as Ruby Hash/Array values.
598    fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
599        match expected {
600            serde_json::Value::String(s) => {
601                let ruby_val = ruby_string_literal(s);
602                out.push_str(&format!("      expect({response_var}.body).to eq({ruby_val})\n"));
603            }
604            _ => {
605                let ruby_val = json_to_ruby(expected);
606                out.push_str(&format!(
607                    "      _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
608                ));
609                out.push_str(&format!("      expect(_body).to eq({ruby_val})\n"));
610            }
611        }
612    }
613
614    /// Emit partial body assertions: one `expect(_body[key]).to eq(val)` per field.
615    fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
616        if let Some(obj) = expected.as_object() {
617            out.push_str(&format!("      _body = JSON.parse({response_var}.body)\n"));
618            for (key, val) in obj {
619                let ruby_key = ruby_string_literal(key);
620                let ruby_val = json_to_ruby(val);
621                out.push_str(&format!("      expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
622            }
623        }
624    }
625
626    /// Emit validation-error assertions, checking each expected `msg` against the
627    /// parsed body's `errors` array.
628    fn render_assert_validation_errors(
629        &self,
630        out: &mut String,
631        response_var: &str,
632        errors: &[ValidationErrorExpectation],
633    ) {
634        for err in errors {
635            let msg_lit = ruby_string_literal(&err.msg);
636            out.push_str(&format!("      _body = JSON.parse({response_var}.body)\n"));
637            out.push_str("      _errors = _body['errors'] || []\n");
638            out.push_str(&format!(
639                "      expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
640            ));
641        }
642    }
643}
644
645/// Render an RSpec example for an HTTP server test fixture via the shared driver.
646///
647/// Delegates to [`client::http_call::render_http_test`] after handling the one
648/// Ruby-specific pre-condition: HTTP 101 (WebSocket upgrade) cannot be exercised
649/// via `Net::HTTP` and is emitted as a pending `it` block directly.
650fn render_http_example(out: &mut String, fixture: &Fixture) {
651    // HTTP 101 (WebSocket upgrade) cannot be tested via Net::HTTP.
652    // Emit the skip block directly rather than pushing a skip directive through
653    // the shared driver, which would require a full `fixture.skip` entry.
654    if fixture
655        .http
656        .as_ref()
657        .is_some_and(|h| h.expected_response.status_code == 101)
658    {
659        if let Some(http) = fixture.http.as_ref() {
660            let description = fixture.description.replace('\'', "\\'");
661            let method = http.request.method.to_uppercase();
662            let path = &http.request.path;
663            let rendered = crate::template_env::render(
664                "ruby/http_101_skip.jinja",
665                minijinja::context! {
666                    method => method,
667                    path => path,
668                    description => description,
669                },
670            );
671            out.push_str(&rendered);
672        }
673        return;
674    }
675
676    client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
677}
678
679/// Convert an uppercase HTTP method string to Ruby's Net::HTTP class name.
680/// Ruby uses title-cased names: Get, Post, Put, Delete, Patch, Head, Options, Trace.
681fn http_method_class(method: &str) -> String {
682    let mut chars = method.chars();
683    match chars.next() {
684        None => String::new(),
685        Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
686    }
687}
688
689// ---------------------------------------------------------------------------
690// Chat-stream test rendering — block iteration with local aggregation
691// ---------------------------------------------------------------------------
692
693/// Render an RSpec example for a `chat_stream` fixture.
694///
695/// The Ruby binding's `chat_stream` is block-yielding: each yielded value is a
696/// `LiterLlm::ChatCompletionChunk`. The codegen builds local aggregator vars
697/// (`chunks`, `stream_content`, `stream_complete`, plus optional
698/// `last_finish_reason`, `tool_calls_json`, `total_tokens`) inside the block and
699/// then emits assertions on those locals — never on response pseudo-fields.
700#[allow(clippy::too_many_arguments)]
701fn render_chat_stream_example(
702    fixture: &Fixture,
703    function_name: &str,
704    call_receiver: &str,
705    args: &[crate::config::ArgMapping],
706    options_type: Option<&str>,
707    enum_fields: &HashMap<String, String>,
708    e2e_config: &E2eConfig,
709    client_factory: Option<&str>,
710    extra_args: &[String],
711) -> String {
712    let test_name = sanitize_ident(&fixture.id);
713    let description = fixture.description.replace('\'', "\\'");
714    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
715    let fixture_id = fixture.id.clone();
716
717    let (mut setup_lines, args_str) = build_args_and_setup(
718        &fixture.input,
719        args,
720        call_receiver,
721        options_type,
722        enum_fields,
723        false,
724        fixture,
725    );
726
727    let mut final_args = args_str;
728    if !extra_args.is_empty() {
729        let extra_str = extra_args.join(", ");
730        if final_args.is_empty() {
731            final_args = extra_str;
732        } else {
733            final_args = format!("{final_args}, {extra_str}");
734        }
735    }
736
737    // Detect which aggregators a fixture's assertions actually need so we don't
738    // emit unused locals (rubocop trips on assigned-but-unread vars).
739    let mut needs_finish_reason = false;
740    let mut needs_tool_calls_json = false;
741    let mut needs_tool_calls_0_function_name = false;
742    let mut needs_total_tokens = false;
743    for a in &fixture.assertions {
744        if let Some(f) = a.field.as_deref() {
745            match f {
746                "finish_reason" => needs_finish_reason = true,
747                "tool_calls" => needs_tool_calls_json = true,
748                "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
749                "usage.total_tokens" => needs_total_tokens = true,
750                _ => {}
751            }
752        }
753    }
754
755    let mut out = String::new();
756    out.push_str(&format!("  it '{test_name}: {description}' do\n"));
757
758    // Client construction.
759    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
760    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
761    if let Some(cf) = client_factory {
762        if has_mock && let Some(key_var) = api_key_var {
763            let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
764            out.push_str(&format!("    api_key = ENV['{key_var}']\n"));
765            out.push_str("    if api_key && !api_key.empty?\n");
766            out.push_str(&format!(
767                "      warn \"{test_name}: using real API ({key_var} is set)\"\n"
768            ));
769            out.push_str(&format!("      client = {call_receiver}.{cf}(api_key)\n"));
770            out.push_str("    else\n");
771            out.push_str(&format!(
772                "      warn \"{test_name}: using mock server ({key_var} not set)\"\n"
773            ));
774            out.push_str(&format!("      mock_url = {mock_url_expr}\n"));
775            out.push_str(&format!("      client = {call_receiver}.{cf}('test-key', mock_url)\n"));
776            out.push_str("    end\n");
777        } else if has_mock {
778            let base_url_expr = if fixture.has_host_root_route() {
779                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
780                format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
781            } else {
782                format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
783            };
784            out.push_str(&format!(
785                "    client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
786            ));
787        } else if let Some(key_var) = api_key_var {
788            out.push_str(&format!("    api_key = ENV['{key_var}']\n"));
789            out.push_str(&format!("    skip '{key_var} not set' unless api_key\n"));
790            out.push_str(&format!("    client = {call_receiver}.{cf}(api_key)\n"));
791        } else {
792            out.push_str(&format!("    client = {call_receiver}.{cf}('test-key')\n"));
793        }
794    }
795
796    // Visitor (rare for streaming, but support it for parity).
797    if let Some(visitor_spec) = &fixture.visitor {
798        let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
799    }
800    for line in &setup_lines {
801        out.push_str(&format!("    {line}\n"));
802    }
803
804    let call_expr = if client_factory.is_some() {
805        format!("client.{function_name}({final_args})")
806    } else {
807        format!("{call_receiver}.{function_name}({final_args})")
808    };
809
810    if expects_error {
811        out.push_str(&format!("    expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
812        out.push_str("  end\n");
813        return out;
814    }
815
816    // Build aggregators inside a block so the iterator drives the stream synchronously.
817    out.push_str("    chunks = []\n");
818    out.push_str("    stream_content = ''.dup\n");
819    out.push_str("    stream_complete = false\n");
820    if needs_finish_reason {
821        out.push_str("    last_finish_reason = nil\n");
822    }
823    if needs_tool_calls_json {
824        out.push_str("    tool_calls_json = nil\n");
825    }
826    if needs_tool_calls_0_function_name {
827        out.push_str("    tool_calls_0_function_name = nil\n");
828    }
829    if needs_total_tokens {
830        out.push_str("    total_tokens = nil\n");
831    }
832    out.push_str(&format!("    {call_expr} do |chunk|\n"));
833    out.push_str("      chunks << chunk\n");
834    out.push_str("      choice = chunk.choices && chunk.choices[0]\n");
835    out.push_str("      if choice\n");
836    out.push_str("        delta = choice.delta\n");
837    out.push_str("        if delta && delta.content\n");
838    out.push_str("          stream_content << delta.content\n");
839    out.push_str("        end\n");
840    if needs_finish_reason {
841        out.push_str("        if choice.finish_reason\n");
842        out.push_str("          last_finish_reason = choice.finish_reason.to_s\n");
843        out.push_str("        end\n");
844    }
845    if needs_tool_calls_json || needs_tool_calls_0_function_name {
846        out.push_str("        tcs = delta && delta.tool_calls\n");
847        out.push_str("        if tcs && !tcs.empty?\n");
848        if needs_tool_calls_json {
849            out.push_str(
850                "          tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
851            );
852        }
853        if needs_tool_calls_0_function_name {
854            out.push_str(
855                "          tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
856            );
857        }
858        out.push_str("        end\n");
859    }
860    out.push_str("      end\n");
861    if needs_total_tokens {
862        out.push_str("      if chunk.usage && chunk.usage.total_tokens\n");
863        out.push_str("        total_tokens = chunk.usage.total_tokens\n");
864        out.push_str("      end\n");
865    }
866    out.push_str("    end\n");
867    out.push_str("    stream_complete = true\n");
868
869    // Render assertions on the local aggregator vars.
870    for assertion in &fixture.assertions {
871        emit_chat_stream_assertion(&mut out, assertion, e2e_config);
872    }
873
874    // Always assert that the stream completed cleanly so non-empty test bodies
875    // are guaranteed by RSpec's at-least-one-expectation requirement.
876    if !fixture
877        .assertions
878        .iter()
879        .any(|a| a.field.as_deref() == Some("stream_complete"))
880    {
881        out.push_str("    expect(stream_complete).to be(true)\n");
882    }
883
884    out.push_str("  end\n");
885    out
886}
887
888/// Map a streaming fixture assertion to an `expect` call on the local aggregator
889/// variable produced by [`render_chat_stream_example`]. Pseudo-fields like
890/// `chunks` / `stream_content` / `stream_complete` resolve to the in-block locals,
891/// not response accessors.
892fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
893    let atype = assertion.assertion_type.as_str();
894    if atype == "not_error" || atype == "error" {
895        return;
896    }
897    let field = assertion.field.as_deref().unwrap_or("");
898
899    enum Kind {
900        Chunks,
901        Bool,
902        Str,
903        IntTokens,
904        Json,
905        Unsupported,
906    }
907
908    let (expr, kind) = match field {
909        "chunks" => ("chunks", Kind::Chunks),
910        "stream_content" => ("stream_content", Kind::Str),
911        "stream_complete" => ("stream_complete", Kind::Bool),
912        "no_chunks_after_done" => ("stream_complete", Kind::Bool),
913        "finish_reason" => ("last_finish_reason", Kind::Str),
914        "tool_calls" => ("tool_calls_json", Kind::Json),
915        "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
916        "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
917        _ => ("", Kind::Unsupported),
918    };
919
920    if matches!(kind, Kind::Unsupported) {
921        out.push_str(&format!(
922            "    # skipped: streaming assertion on unsupported field '{field}'\n"
923        ));
924        return;
925    }
926
927    match (atype, &kind) {
928        ("count_min", Kind::Chunks) => {
929            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
930                out.push_str(&format!("    expect({expr}.length).to be >= {n}\n"));
931            }
932        }
933        ("count_equals", Kind::Chunks) => {
934            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
935                out.push_str(&format!("    expect({expr}.length).to eq({n})\n"));
936            }
937        }
938        ("equals", Kind::Str) => {
939            if let Some(val) = &assertion.value {
940                let rb_val = json_to_ruby(val);
941                // Mirror Python's `expr.strip() == expected.strip()` pattern: converters
942                // commonly emit a trailing newline that fixture authors don't write into the
943                // expected string, so strip both sides for the equality check.
944                out.push_str(&format!("    expect({expr}.to_s.strip).to eq({rb_val}.strip)\n"));
945            }
946        }
947        ("contains", Kind::Str) => {
948            if let Some(val) = &assertion.value {
949                let rb_val = json_to_ruby(val);
950                out.push_str(&format!("    expect({expr}.to_s).to include({rb_val})\n"));
951            }
952        }
953        ("not_empty", Kind::Str) => {
954            out.push_str(&format!("    expect({expr}.to_s).not_to be_empty\n"));
955        }
956        ("not_empty", Kind::Json) => {
957            out.push_str(&format!("    expect({expr}).not_to be_nil\n"));
958        }
959        ("is_empty", Kind::Str) => {
960            out.push_str(&format!("    expect({expr}.to_s).to be_empty\n"));
961        }
962        ("is_true", Kind::Bool) => {
963            out.push_str(&format!("    expect({expr}).to be(true)\n"));
964        }
965        ("is_false", Kind::Bool) => {
966            out.push_str(&format!("    expect({expr}).to be(false)\n"));
967        }
968        ("greater_than_or_equal", Kind::IntTokens) => {
969            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
970                out.push_str(&format!("    expect({expr}).to be >= {n}\n"));
971            }
972        }
973        ("equals", Kind::IntTokens) => {
974            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
975                out.push_str(&format!("    expect({expr}).to eq({n})\n"));
976            }
977        }
978        _ => {
979            out.push_str(&format!(
980                "    # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
981            ));
982        }
983    }
984}
985
986// ---------------------------------------------------------------------------
987// Function-call test rendering
988// ---------------------------------------------------------------------------
989
990#[allow(clippy::too_many_arguments)]
991fn render_example(
992    fixture: &Fixture,
993    function_name: &str,
994    call_receiver: &str,
995    result_var: &str,
996    args: &[crate::config::ArgMapping],
997    field_resolver: &FieldResolver,
998    options_type: Option<&str>,
999    enum_fields: &HashMap<String, String>,
1000    result_is_simple: bool,
1001    e2e_config: &E2eConfig,
1002    client_factory: Option<&str>,
1003    extra_args: &[String],
1004) -> String {
1005    let test_name = sanitize_ident(&fixture.id);
1006    let description = fixture.description.replace('\'', "\\'");
1007    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1008    let fixture_id = fixture.id.clone();
1009
1010    let (mut setup_lines, args_str) = build_args_and_setup(
1011        &fixture.input,
1012        args,
1013        call_receiver,
1014        options_type,
1015        enum_fields,
1016        result_is_simple,
1017        fixture,
1018    );
1019
1020    // Build visitor if present and add to setup
1021    let mut visitor_arg = String::new();
1022    if let Some(visitor_spec) = &fixture.visitor {
1023        visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1024    }
1025
1026    let mut final_args = if visitor_arg.is_empty() {
1027        args_str
1028    } else if args_str.is_empty() {
1029        visitor_arg
1030    } else {
1031        format!("{args_str}, {visitor_arg}")
1032    };
1033
1034    // Append per-fixture extra_args (e.g. trailing `nil` for `list_files(purpose)`).
1035    if !extra_args.is_empty() {
1036        let extra_str = extra_args.join(", ");
1037        if final_args.is_empty() {
1038            final_args = extra_str;
1039        } else {
1040            final_args = format!("{final_args}, {extra_str}");
1041        }
1042    }
1043
1044    // When client_factory is configured, create a client instance and call methods on it.
1045    let call_expr = if client_factory.is_some() {
1046        format!("client.{function_name}({final_args})")
1047    } else {
1048        format!("{call_receiver}.{function_name}({final_args})")
1049    };
1050
1051    // Check if any non-error assertion actually uses the result variable.
1052    let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1053
1054    // Render all assertions upfront into a string
1055    let mut assertions_rendered = String::new();
1056    for assertion in &fixture.assertions {
1057        render_assertion(
1058            &mut assertions_rendered,
1059            assertion,
1060            result_var,
1061            field_resolver,
1062            result_is_simple,
1063            e2e_config,
1064            enum_fields,
1065        );
1066    }
1067
1068    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1069    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1070    let has_mock_and_key = has_mock && api_key_var.is_some();
1071    crate::template_env::render(
1072        "ruby/test_function.jinja",
1073        minijinja::context! {
1074            test_name => test_name,
1075            description => description,
1076            expects_error => expects_error,
1077            setup_lines => setup_lines,
1078            call_expr => call_expr,
1079            result_var => result_var,
1080            assertions_rendered => assertions_rendered,
1081            has_usable => has_usable,
1082            client_factory => client_factory,
1083            fixture_id => fixture_id,
1084            call_receiver => call_receiver,
1085            has_mock => has_mock,
1086            api_key_var => api_key_var,
1087            has_mock_and_key => has_mock_and_key,
1088        },
1089    )
1090}
1091
1092/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1093///
1094/// Returns `(setup_lines, args_string)`.
1095/// Emit Ruby batch item constructors for BatchBytesItem or BatchFileItem arrays.
1096fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1097    if let Some(items) = arr.as_array() {
1098        let item_strs: Vec<String> = items
1099            .iter()
1100            .filter_map(|item| {
1101                if let Some(obj) = item.as_object() {
1102                    match elem_type {
1103                        "BatchBytesItem" => {
1104                            let content = obj.get("content").and_then(|v| v.as_array());
1105                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1106                            let config = obj.get("config");
1107                            let content_code = if let Some(arr) = content {
1108                                let bytes: Vec<String> =
1109                                    arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1110                                // Pass as Ruby array - Magnus will convert Array<u8> to Vec<u8>
1111                                format!("[{}]", bytes.join(", "))
1112                            } else {
1113                                "[]".to_string()
1114                            };
1115                            let config_arg = if let Some(cfg) = config {
1116                                if cfg.is_null() {
1117                                    "nil".to_string()
1118                                } else {
1119                                    json_to_ruby(cfg)
1120                                }
1121                            } else {
1122                                "nil".to_string()
1123                            };
1124                            Some(format!(
1125                                "Kreuzberg::{}.new(content: {}, mime_type: \"{}\", config: {})",
1126                                elem_type, content_code, mime_type, config_arg
1127                            ))
1128                        }
1129                        "BatchFileItem" => {
1130                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1131                            let config = obj.get("config");
1132                            let config_arg = if let Some(cfg) = config {
1133                                if cfg.is_null() {
1134                                    "nil".to_string()
1135                                } else {
1136                                    json_to_ruby(cfg)
1137                                }
1138                            } else {
1139                                "nil".to_string()
1140                            };
1141                            Some(format!(
1142                                "Kreuzberg::{}.new(path: \"{}\", config: {})",
1143                                elem_type, path, config_arg
1144                            ))
1145                        }
1146                        _ => None,
1147                    }
1148                } else {
1149                    None
1150                }
1151            })
1152            .collect();
1153        format!("[{}]", item_strs.join(", "))
1154    } else {
1155        "[]".to_string()
1156    }
1157}
1158
1159fn build_args_and_setup(
1160    input: &serde_json::Value,
1161    args: &[crate::config::ArgMapping],
1162    call_receiver: &str,
1163    options_type: Option<&str>,
1164    enum_fields: &HashMap<String, String>,
1165    result_is_simple: bool,
1166    fixture: &crate::fixture::Fixture,
1167) -> (Vec<String>, String) {
1168    let fixture_id = &fixture.id;
1169    if args.is_empty() {
1170        // No args config: pass the whole input only when it's non-empty.
1171        // Functions with no parameters have empty input and must be called
1172        // with no arguments — not with `{}` or `nil`.
1173        let is_empty_input = match input {
1174            serde_json::Value::Null => true,
1175            serde_json::Value::Object(m) => m.is_empty(),
1176            _ => false,
1177        };
1178        if is_empty_input {
1179            return (Vec::new(), String::new());
1180        }
1181        return (Vec::new(), json_to_ruby(input));
1182    }
1183
1184    let mut setup_lines: Vec<String> = Vec::new();
1185    let mut parts: Vec<String> = Vec::new();
1186    // Track optional args that were skipped; if a later arg is emitted we must back-fill nil
1187    // to preserve positional correctness (e.g. extract_file(path, nil, config)).
1188    let mut skipped_optional_count: usize = 0;
1189
1190    for arg in args {
1191        if arg.arg_type == "mock_url" {
1192            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1193            for _ in 0..skipped_optional_count {
1194                parts.push("nil".to_string());
1195            }
1196            skipped_optional_count = 0;
1197            if fixture.has_host_root_route() {
1198                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1199                setup_lines.push(format!(
1200                    "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1201                    arg.name,
1202                ));
1203            } else {
1204                setup_lines.push(format!(
1205                    "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1206                    arg.name,
1207                ));
1208            }
1209            parts.push(arg.name.clone());
1210            continue;
1211        }
1212
1213        // Handle bytes arguments: load from file if needed
1214        if arg.arg_type == "bytes" {
1215            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1216            for _ in 0..skipped_optional_count {
1217                parts.push("nil".to_string());
1218            }
1219            skipped_optional_count = 0;
1220            let resolved = resolve_field(input, &arg.field);
1221            if let Some(s) = resolved.as_str() {
1222                if is_file_path(s) {
1223                    // File path: load with File.read and convert to bytes array
1224                    setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1225                } else if is_base64(s) {
1226                    // Base64: decode it
1227                    setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1228                } else {
1229                    // Inline text: encode to binary and convert to bytes array
1230                    let escaped = ruby_string_literal(s);
1231                    setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1232                }
1233                parts.push(arg.name.clone());
1234            } else {
1235                parts.push("nil".to_string());
1236            }
1237            continue;
1238        }
1239
1240        // Handle file_path arguments: pass the path string as-is
1241        if arg.arg_type == "file_path" {
1242            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1243            for _ in 0..skipped_optional_count {
1244                parts.push("nil".to_string());
1245            }
1246            skipped_optional_count = 0;
1247            let resolved = resolve_field(input, &arg.field);
1248            if let Some(s) = resolved.as_str() {
1249                let escaped = ruby_string_literal(s);
1250                parts.push(escaped);
1251            } else if arg.optional {
1252                skipped_optional_count += 1;
1253                continue;
1254            } else {
1255                parts.push("''".to_string());
1256            }
1257            continue;
1258        }
1259
1260        if arg.arg_type == "handle" {
1261            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1262            for _ in 0..skipped_optional_count {
1263                parts.push("nil".to_string());
1264            }
1265            skipped_optional_count = 0;
1266            // Generate a create_engine (or equivalent) call and pass the variable.
1267            let constructor_name = format!("create_{}", arg.name.to_snake_case());
1268            let config_value = resolve_field(input, &arg.field);
1269            if config_value.is_null()
1270                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1271            {
1272                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1273            } else {
1274                let literal = json_to_ruby(config_value);
1275                let name = &arg.name;
1276                setup_lines.push(format!("{name}_config = {literal}"));
1277                setup_lines.push(format!(
1278                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1279                    arg.name,
1280                    name = name,
1281                ));
1282            }
1283            parts.push(arg.name.clone());
1284            continue;
1285        }
1286
1287        let resolved = resolve_field(input, &arg.field);
1288        let val = if resolved.is_null() { None } else { Some(resolved) };
1289        match val {
1290            None | Some(serde_json::Value::Null) if arg.optional => {
1291                // Optional arg with no fixture value: defer; emit nil only if a later arg is present.
1292                skipped_optional_count += 1;
1293                continue;
1294            }
1295            None | Some(serde_json::Value::Null) => {
1296                // Required arg with no fixture value: flush deferred nils, then pass a default.
1297                for _ in 0..skipped_optional_count {
1298                    parts.push("nil".to_string());
1299                }
1300                skipped_optional_count = 0;
1301                let default_val = match arg.arg_type.as_str() {
1302                    "string" => "''".to_string(),
1303                    "int" | "integer" => "0".to_string(),
1304                    "float" | "number" => "0.0".to_string(),
1305                    "bool" | "boolean" => "false".to_string(),
1306                    _ => "nil".to_string(),
1307                };
1308                parts.push(default_val);
1309            }
1310            Some(v) => {
1311                // Flush deferred nil placeholders for skipped optional args that precede this one.
1312                for _ in 0..skipped_optional_count {
1313                    parts.push("nil".to_string());
1314                }
1315                skipped_optional_count = 0;
1316                // For json_object args with options_type, construct a typed options object.
1317                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
1318                if arg.arg_type == "json_object" && !v.is_null() {
1319                    // Check for batch item arrays (element_type set to BatchBytesItem/BatchFileItem)
1320                    if let Some(elem_type) = &arg.element_type {
1321                        if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1322                            parts.push(emit_ruby_batch_item_array(v, elem_type));
1323                            continue;
1324                        }
1325                    }
1326                    // Otherwise handle regular options_type objects
1327                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1328                        let kwargs: Vec<String> = obj
1329                            .iter()
1330                            .map(|(k, vv)| {
1331                                let snake_key = k.to_snake_case();
1332                                let rb_val = if enum_fields.contains_key(k) {
1333                                    if let Some(s) = vv.as_str() {
1334                                        let snake_val = s.to_snake_case();
1335                                        format!("'{snake_val}'")
1336                                    } else {
1337                                        json_to_ruby(vv)
1338                                    }
1339                                } else {
1340                                    json_to_ruby(vv)
1341                                };
1342                                format!("{snake_key}: {rb_val}")
1343                            })
1344                            .collect();
1345                        if result_is_simple {
1346                            parts.push(format!("{{{}}}", kwargs.join(", ")));
1347                        } else {
1348                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1349                        }
1350                        continue;
1351                    }
1352                }
1353                parts.push(json_to_ruby(v));
1354            }
1355        }
1356    }
1357
1358    (setup_lines, parts.join(", "))
1359}
1360
1361fn render_assertion(
1362    out: &mut String,
1363    assertion: &Assertion,
1364    result_var: &str,
1365    field_resolver: &FieldResolver,
1366    result_is_simple: bool,
1367    e2e_config: &E2eConfig,
1368    per_call_enum_fields: &HashMap<String, String>,
1369) {
1370    // For simple-result methods (e.g. `speech` returning bytes), every field-based
1371    // assertion targets the result itself — there's no struct to access. Drop
1372    // length-only assertions onto the result directly and skip anything else.
1373    if result_is_simple {
1374        if let Some(f) = &assertion.field {
1375            if !f.is_empty() {
1376                match assertion.assertion_type.as_str() {
1377                    "not_empty" => {
1378                        out.push_str(&format!("    expect({result_var}.to_s).not_to be_empty\n"));
1379                        return;
1380                    }
1381                    "is_empty" => {
1382                        out.push_str(&format!("    expect({result_var}.to_s).to be_empty\n"));
1383                        return;
1384                    }
1385                    "count_equals" => {
1386                        if let Some(val) = &assertion.value {
1387                            let rb_val = json_to_ruby(val);
1388                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1389                        }
1390                        return;
1391                    }
1392                    "count_min" => {
1393                        if let Some(val) = &assertion.value {
1394                            let rb_val = json_to_ruby(val);
1395                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1396                        }
1397                        return;
1398                    }
1399                    _ => {
1400                        out.push_str(&format!(
1401                            "    # skipped: field '{f}' not applicable for simple result type\n"
1402                        ));
1403                        return;
1404                    }
1405                }
1406            }
1407        }
1408    }
1409    // Handle synthetic / derived fields before the is_valid_for_result check
1410    // so they are never treated as struct attribute accesses on the result.
1411    if let Some(f) = &assertion.field {
1412        match f.as_str() {
1413            "chunks_have_content" => {
1414                let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1415                match assertion.assertion_type.as_str() {
1416                    "is_true" => {
1417                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1418                    }
1419                    "is_false" => {
1420                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1421                    }
1422                    _ => {
1423                        out.push_str(&format!(
1424                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1425                        ));
1426                    }
1427                }
1428                return;
1429            }
1430            "chunks_have_embeddings" => {
1431                let pred =
1432                    format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1433                match assertion.assertion_type.as_str() {
1434                    "is_true" => {
1435                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1436                    }
1437                    "is_false" => {
1438                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1439                    }
1440                    _ => {
1441                        out.push_str(&format!(
1442                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1443                        ));
1444                    }
1445                }
1446                return;
1447            }
1448            // ---- EmbedResponse virtual fields ----
1449            // embed_texts returns Array<Array<Float>> in Ruby — no wrapper struct.
1450            // result_var is the embedding matrix; use it directly.
1451            "embeddings" => {
1452                match assertion.assertion_type.as_str() {
1453                    "count_equals" => {
1454                        if let Some(val) = &assertion.value {
1455                            let rb_val = json_to_ruby(val);
1456                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1457                        }
1458                    }
1459                    "count_min" => {
1460                        if let Some(val) = &assertion.value {
1461                            let rb_val = json_to_ruby(val);
1462                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1463                        }
1464                    }
1465                    "not_empty" => {
1466                        out.push_str(&format!("    expect({result_var}).not_to be_empty\n"));
1467                    }
1468                    "is_empty" => {
1469                        out.push_str(&format!("    expect({result_var}).to be_empty\n"));
1470                    }
1471                    _ => {
1472                        out.push_str("    # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1473                    }
1474                }
1475                return;
1476            }
1477            "embedding_dimensions" => {
1478                let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1479                match assertion.assertion_type.as_str() {
1480                    "equals" => {
1481                        if let Some(val) = &assertion.value {
1482                            let rb_val = json_to_ruby(val);
1483                            out.push_str(&format!("    expect({expr}).to eq({rb_val})\n"));
1484                        }
1485                    }
1486                    "greater_than" => {
1487                        if let Some(val) = &assertion.value {
1488                            let rb_val = json_to_ruby(val);
1489                            out.push_str(&format!("    expect({expr}).to be > {rb_val}\n"));
1490                        }
1491                    }
1492                    _ => {
1493                        out.push_str(
1494                            "    # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1495                        );
1496                    }
1497                }
1498                return;
1499            }
1500            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1501                let pred = match f.as_str() {
1502                    "embeddings_valid" => {
1503                        format!("{result_var}.all? {{ |e| !e.empty? }}")
1504                    }
1505                    "embeddings_finite" => {
1506                        format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1507                    }
1508                    "embeddings_non_zero" => {
1509                        format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1510                    }
1511                    "embeddings_normalized" => {
1512                        format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1513                    }
1514                    _ => unreachable!(),
1515                };
1516                match assertion.assertion_type.as_str() {
1517                    "is_true" => {
1518                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1519                    }
1520                    "is_false" => {
1521                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1522                    }
1523                    _ => {
1524                        out.push_str(&format!(
1525                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1526                        ));
1527                    }
1528                }
1529                return;
1530            }
1531            // ---- keywords / keywords_count ----
1532            // Ruby ExtractionResult does not expose extracted_keywords; skip.
1533            "keywords" | "keywords_count" => {
1534                out.push_str(&format!(
1535                    "    # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1536                ));
1537                return;
1538            }
1539            _ => {}
1540        }
1541    }
1542
1543    // Skip assertions on fields that don't exist on the result type.
1544    if let Some(f) = &assertion.field {
1545        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1546            out.push_str(&format!("    # skipped: field '{f}' not available on result type\n"));
1547            return;
1548        }
1549    }
1550
1551    // When result_is_simple, skip assertions that reference non-content fields.
1552    if result_is_simple {
1553        if let Some(f) = &assertion.field {
1554            let f_lower = f.to_lowercase();
1555            if !f.is_empty()
1556                && f_lower != "content"
1557                && (f_lower.starts_with("metadata")
1558                    || f_lower.starts_with("document")
1559                    || f_lower.starts_with("structure"))
1560            {
1561                return;
1562            }
1563        }
1564    }
1565
1566    // result_is_simple: treat the result itself as the content string, but only
1567    // when there is no explicit field (or the field is "content"). Count/length
1568    // assertions on named fields (e.g. "warnings") must still walk the field path.
1569    let field_expr = match &assertion.field {
1570        Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1571            field_resolver.accessor(f, "ruby", result_var)
1572        }
1573        _ => result_var.to_string(),
1574    };
1575
1576    // For string equality, strip trailing whitespace to handle trailing newlines
1577    // from the converter. Ruby enum fields (Magnus binds Rust enums as Symbols),
1578    // are coerced to String via .to_s so `eq("stop")` matches `:stop`. Look up the
1579    // field in both the global `[crates.e2e] fields_enum` set AND the per-call
1580    // override `[crates.e2e.calls.<x>.overrides.<lang>] enum_fields = { ... }` —
1581    // downstream config that already labels e.g. `status = "BatchStatus"` for the
1582    // Java/C#/Python sides should apply here too without a Ruby-only duplicate.
1583    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1584        let resolved = field_resolver.resolve(f);
1585        e2e_config.fields_enum.contains(f)
1586            || e2e_config.fields_enum.contains(resolved)
1587            || per_call_enum_fields.contains_key(f)
1588            || per_call_enum_fields.contains_key(resolved)
1589    });
1590    let stripped_field_expr = if result_is_simple {
1591        format!("{field_expr}.to_s.strip")
1592    } else if field_is_enum {
1593        format!("{field_expr}.to_s")
1594    } else {
1595        field_expr.clone()
1596    };
1597
1598    // Detect whether the assertion field resolves to an array type so that
1599    // contains assertions can iterate items instead of calling .to_s on the array.
1600    let field_is_array = assertion
1601        .field
1602        .as_deref()
1603        .filter(|f| !f.is_empty())
1604        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1605
1606    match assertion.assertion_type.as_str() {
1607        "equals" => {
1608            if let Some(expected) = &assertion.value {
1609                let is_boolean_val = expected.as_bool().is_some();
1610                let bool_val = expected
1611                    .as_bool()
1612                    .map(|b| if b { "true" } else { "false" })
1613                    .unwrap_or("");
1614                let rb_val = json_to_ruby(expected);
1615                // Mirror Python's `expr.strip() == expected.strip()` pattern when comparing
1616                // string values: converters commonly emit a trailing newline that fixture
1617                // authors don't write into the expected string.
1618                let cmp_expr = if expected.is_string() && !field_is_enum {
1619                    format!("{stripped_field_expr}.to_s.strip")
1620                } else {
1621                    stripped_field_expr.clone()
1622                };
1623                let cmp_expected = if expected.is_string() && !field_is_enum {
1624                    format!("{rb_val}.strip")
1625                } else {
1626                    rb_val
1627                };
1628
1629                let rendered = crate::template_env::render(
1630                    "ruby/assertion.jinja",
1631                    minijinja::context! {
1632                        assertion_type => "equals",
1633                        stripped_field_expr => cmp_expr,
1634                        is_boolean_val => is_boolean_val,
1635                        bool_val => bool_val,
1636                        expected_val => cmp_expected,
1637                    },
1638                );
1639                out.push_str(&rendered);
1640            }
1641        }
1642        "contains" => {
1643            if let Some(expected) = &assertion.value {
1644                let rb_val = json_to_ruby(expected);
1645                let rendered = crate::template_env::render(
1646                    "ruby/assertion.jinja",
1647                    minijinja::context! {
1648                        assertion_type => "contains",
1649                        field_expr => field_expr.clone(),
1650                        field_is_array => field_is_array && expected.is_string(),
1651                        expected_val => rb_val,
1652                    },
1653                );
1654                out.push_str(&rendered);
1655            }
1656        }
1657        "contains_all" => {
1658            if let Some(values) = &assertion.values {
1659                let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1660                let rendered = crate::template_env::render(
1661                    "ruby/assertion.jinja",
1662                    minijinja::context! {
1663                        assertion_type => "contains_all",
1664                        field_expr => field_expr.clone(),
1665                        field_is_array => field_is_array,
1666                        values_list => values_list,
1667                    },
1668                );
1669                out.push_str(&rendered);
1670            }
1671        }
1672        "not_contains" => {
1673            if let Some(expected) = &assertion.value {
1674                let rb_val = json_to_ruby(expected);
1675                let rendered = crate::template_env::render(
1676                    "ruby/assertion.jinja",
1677                    minijinja::context! {
1678                        assertion_type => "not_contains",
1679                        field_expr => field_expr.clone(),
1680                        field_is_array => field_is_array && expected.is_string(),
1681                        expected_val => rb_val,
1682                    },
1683                );
1684                out.push_str(&rendered);
1685            }
1686        }
1687        "not_empty" => {
1688            let rendered = crate::template_env::render(
1689                "ruby/assertion.jinja",
1690                minijinja::context! {
1691                    assertion_type => "not_empty",
1692                    field_expr => field_expr.clone(),
1693                },
1694            );
1695            out.push_str(&rendered);
1696        }
1697        "is_empty" => {
1698            let rendered = crate::template_env::render(
1699                "ruby/assertion.jinja",
1700                minijinja::context! {
1701                    assertion_type => "is_empty",
1702                    field_expr => field_expr.clone(),
1703                },
1704            );
1705            out.push_str(&rendered);
1706        }
1707        "contains_any" => {
1708            if let Some(values) = &assertion.values {
1709                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1710                let rendered = crate::template_env::render(
1711                    "ruby/assertion.jinja",
1712                    minijinja::context! {
1713                        assertion_type => "contains_any",
1714                        field_expr => field_expr.clone(),
1715                        values_list => items,
1716                    },
1717                );
1718                out.push_str(&rendered);
1719            }
1720        }
1721        "greater_than" => {
1722            if let Some(val) = &assertion.value {
1723                let rb_val = json_to_ruby(val);
1724                let rendered = crate::template_env::render(
1725                    "ruby/assertion.jinja",
1726                    minijinja::context! {
1727                        assertion_type => "greater_than",
1728                        field_expr => field_expr.clone(),
1729                        expected_val => rb_val,
1730                    },
1731                );
1732                out.push_str(&rendered);
1733            }
1734        }
1735        "less_than" => {
1736            if let Some(val) = &assertion.value {
1737                let rb_val = json_to_ruby(val);
1738                let rendered = crate::template_env::render(
1739                    "ruby/assertion.jinja",
1740                    minijinja::context! {
1741                        assertion_type => "less_than",
1742                        field_expr => field_expr.clone(),
1743                        expected_val => rb_val,
1744                    },
1745                );
1746                out.push_str(&rendered);
1747            }
1748        }
1749        "greater_than_or_equal" => {
1750            if let Some(val) = &assertion.value {
1751                let rb_val = json_to_ruby(val);
1752                let rendered = crate::template_env::render(
1753                    "ruby/assertion.jinja",
1754                    minijinja::context! {
1755                        assertion_type => "greater_than_or_equal",
1756                        field_expr => field_expr.clone(),
1757                        expected_val => rb_val,
1758                    },
1759                );
1760                out.push_str(&rendered);
1761            }
1762        }
1763        "less_than_or_equal" => {
1764            if let Some(val) = &assertion.value {
1765                let rb_val = json_to_ruby(val);
1766                let rendered = crate::template_env::render(
1767                    "ruby/assertion.jinja",
1768                    minijinja::context! {
1769                        assertion_type => "less_than_or_equal",
1770                        field_expr => field_expr.clone(),
1771                        expected_val => rb_val,
1772                    },
1773                );
1774                out.push_str(&rendered);
1775            }
1776        }
1777        "starts_with" => {
1778            if let Some(expected) = &assertion.value {
1779                let rb_val = json_to_ruby(expected);
1780                let rendered = crate::template_env::render(
1781                    "ruby/assertion.jinja",
1782                    minijinja::context! {
1783                        assertion_type => "starts_with",
1784                        field_expr => field_expr.clone(),
1785                        expected_val => rb_val,
1786                    },
1787                );
1788                out.push_str(&rendered);
1789            }
1790        }
1791        "ends_with" => {
1792            if let Some(expected) = &assertion.value {
1793                let rb_val = json_to_ruby(expected);
1794                let rendered = crate::template_env::render(
1795                    "ruby/assertion.jinja",
1796                    minijinja::context! {
1797                        assertion_type => "ends_with",
1798                        field_expr => field_expr.clone(),
1799                        expected_val => rb_val,
1800                    },
1801                );
1802                out.push_str(&rendered);
1803            }
1804        }
1805        "min_length" | "max_length" | "count_min" | "count_equals" => {
1806            if let Some(val) = &assertion.value {
1807                if let Some(n) = val.as_u64() {
1808                    let rendered = crate::template_env::render(
1809                        "ruby/assertion.jinja",
1810                        minijinja::context! {
1811                            assertion_type => assertion.assertion_type.as_str(),
1812                            field_expr => field_expr.clone(),
1813                            check_n => n,
1814                        },
1815                    );
1816                    out.push_str(&rendered);
1817                }
1818            }
1819        }
1820        "is_true" => {
1821            let rendered = crate::template_env::render(
1822                "ruby/assertion.jinja",
1823                minijinja::context! {
1824                    assertion_type => "is_true",
1825                    field_expr => field_expr.clone(),
1826                },
1827            );
1828            out.push_str(&rendered);
1829        }
1830        "is_false" => {
1831            let rendered = crate::template_env::render(
1832                "ruby/assertion.jinja",
1833                minijinja::context! {
1834                    assertion_type => "is_false",
1835                    field_expr => field_expr.clone(),
1836                },
1837            );
1838            out.push_str(&rendered);
1839        }
1840        "method_result" => {
1841            if let Some(method_name) = &assertion.method {
1842                // Derive call_receiver for module-level helper calls.
1843                let lang = "ruby";
1844                let call = &e2e_config.call;
1845                let overrides = call.overrides.get(lang);
1846                let module_path = overrides
1847                    .and_then(|o| o.module.as_ref())
1848                    .cloned()
1849                    .unwrap_or_else(|| call.module.clone());
1850                let call_receiver = ruby_module_name(&module_path);
1851
1852                let call_expr =
1853                    build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
1854                let check = assertion.check.as_deref().unwrap_or("is_true");
1855
1856                let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
1857                    "equals" => {
1858                        if let Some(val) = &assertion.value {
1859                            let is_bool = val.as_bool().is_some();
1860                            let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
1861                            let rb_val = json_to_ruby(val);
1862                            (rb_val, is_bool, bool_str.to_string(), 0)
1863                        } else {
1864                            (String::new(), false, String::new(), 0)
1865                        }
1866                    }
1867                    "greater_than_or_equal" => {
1868                        if let Some(val) = &assertion.value {
1869                            (json_to_ruby(val), false, String::new(), 0)
1870                        } else {
1871                            (String::new(), false, String::new(), 0)
1872                        }
1873                    }
1874                    "count_min" => {
1875                        if let Some(val) = &assertion.value {
1876                            let n = val.as_u64().unwrap_or(0);
1877                            (String::new(), false, String::new(), n)
1878                        } else {
1879                            (String::new(), false, String::new(), 0)
1880                        }
1881                    }
1882                    "contains" => {
1883                        if let Some(val) = &assertion.value {
1884                            (json_to_ruby(val), false, String::new(), 0)
1885                        } else {
1886                            (String::new(), false, String::new(), 0)
1887                        }
1888                    }
1889                    _ => (String::new(), false, String::new(), 0),
1890                };
1891
1892                let rendered = crate::template_env::render(
1893                    "ruby/assertion.jinja",
1894                    minijinja::context! {
1895                        assertion_type => "method_result",
1896                        call_expr => call_expr,
1897                        check => check,
1898                        check_val => check_val_str,
1899                        is_boolean_check => is_boolean_check,
1900                        bool_check_val => bool_check_val,
1901                        check_n => check_n_val,
1902                    },
1903                );
1904                out.push_str(&rendered);
1905            } else {
1906                panic!("Ruby e2e generator: method_result assertion missing 'method' field");
1907            }
1908        }
1909        "matches_regex" => {
1910            if let Some(expected) = &assertion.value {
1911                let rb_val = json_to_ruby(expected);
1912                let rendered = crate::template_env::render(
1913                    "ruby/assertion.jinja",
1914                    minijinja::context! {
1915                        assertion_type => "matches_regex",
1916                        field_expr => field_expr.clone(),
1917                        expected_val => rb_val,
1918                    },
1919                );
1920                out.push_str(&rendered);
1921            }
1922        }
1923        "not_error" => {
1924            // Already handled by the call succeeding without exception.
1925        }
1926        "error" => {
1927            // Handled at the example level.
1928        }
1929        other => {
1930            panic!("Ruby e2e generator: unsupported assertion type: {other}");
1931        }
1932    }
1933}
1934
1935/// Build a Ruby call expression for a `method_result` assertion on a tree-sitter Tree.
1936/// Maps method names to the appropriate Ruby method or module-function calls.
1937fn build_ruby_method_call(
1938    call_receiver: &str,
1939    result_var: &str,
1940    method_name: &str,
1941    args: Option<&serde_json::Value>,
1942) -> String {
1943    match method_name {
1944        "root_child_count" => format!("{result_var}.root_node.child_count"),
1945        "root_node_type" => format!("{result_var}.root_node.type"),
1946        "named_children_count" => format!("{result_var}.root_node.named_child_count"),
1947        "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
1948        "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
1949        "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
1950        "contains_node_type" => {
1951            let node_type = args
1952                .and_then(|a| a.get("node_type"))
1953                .and_then(|v| v.as_str())
1954                .unwrap_or("");
1955            format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
1956        }
1957        "find_nodes_by_type" => {
1958            let node_type = args
1959                .and_then(|a| a.get("node_type"))
1960                .and_then(|v| v.as_str())
1961                .unwrap_or("");
1962            format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
1963        }
1964        "run_query" => {
1965            let query_source = args
1966                .and_then(|a| a.get("query_source"))
1967                .and_then(|v| v.as_str())
1968                .unwrap_or("");
1969            let language = args
1970                .and_then(|a| a.get("language"))
1971                .and_then(|v| v.as_str())
1972                .unwrap_or("");
1973            format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
1974        }
1975        _ => format!("{result_var}.{method_name}"),
1976    }
1977}
1978
1979/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
1980/// (e.g., "HtmlToMarkdown").
1981fn ruby_module_name(module_path: &str) -> String {
1982    use heck::ToUpperCamelCase;
1983    module_path.to_upper_camel_case()
1984}
1985
1986/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
1987fn json_to_ruby(value: &serde_json::Value) -> String {
1988    match value {
1989        serde_json::Value::String(s) => ruby_string_literal(s),
1990        serde_json::Value::Bool(true) => "true".to_string(),
1991        serde_json::Value::Bool(false) => "false".to_string(),
1992        serde_json::Value::Number(n) => n.to_string(),
1993        serde_json::Value::Null => "nil".to_string(),
1994        serde_json::Value::Array(arr) => {
1995            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
1996            format!("[{}]", items.join(", "))
1997        }
1998        serde_json::Value::Object(map) => {
1999            let items: Vec<String> = map
2000                .iter()
2001                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
2002                .collect();
2003            format!("{{ {} }}", items.join(", "))
2004        }
2005    }
2006}
2007
2008// ---------------------------------------------------------------------------
2009// Visitor generation
2010// ---------------------------------------------------------------------------
2011
2012/// Build a Ruby visitor object and add setup lines. Returns the visitor expression.
2013fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
2014    setup_lines.push("visitor = Class.new do".to_string());
2015    for (method_name, action) in &visitor_spec.callbacks {
2016        emit_ruby_visitor_method(setup_lines, method_name, action);
2017    }
2018    setup_lines.push("end.new".to_string());
2019    "visitor".to_string()
2020}
2021
2022/// Emit a Ruby visitor method for a callback action.
2023fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2024    let params = match method_name {
2025        "visit_link" => "ctx, href, text, title",
2026        "visit_image" => "ctx, src, alt, title",
2027        "visit_heading" => "ctx, level, text, id",
2028        "visit_code_block" => "ctx, lang, code",
2029        "visit_code_inline"
2030        | "visit_strong"
2031        | "visit_emphasis"
2032        | "visit_strikethrough"
2033        | "visit_underline"
2034        | "visit_subscript"
2035        | "visit_superscript"
2036        | "visit_mark"
2037        | "visit_button"
2038        | "visit_summary"
2039        | "visit_figcaption"
2040        | "visit_definition_term"
2041        | "visit_definition_description" => "ctx, text",
2042        "visit_text" => "ctx, text",
2043        "visit_list_item" => "ctx, ordered, marker, text",
2044        "visit_blockquote" => "ctx, content, depth",
2045        "visit_table_row" => "ctx, cells, is_header",
2046        "visit_custom_element" => "ctx, tag_name, html",
2047        "visit_form" => "ctx, action_url, method",
2048        "visit_input" => "ctx, input_type, name, value",
2049        "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2050        "visit_details" => "ctx, is_open",
2051        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2052        "visit_list_start" => "ctx, ordered",
2053        "visit_list_end" => "ctx, ordered, output",
2054        _ => "ctx",
2055    };
2056
2057    // Pre-compute action type and values
2058    let (action_type, action_value, return_form) = match action {
2059        CallbackAction::Skip => ("skip", String::new(), "dict"),
2060        CallbackAction::Continue => ("continue", String::new(), "dict"),
2061        CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2062        CallbackAction::Custom { output } => {
2063            let escaped = ruby_string_literal(output);
2064            ("custom", escaped, "dict")
2065        }
2066        CallbackAction::CustomTemplate { template, return_form } => {
2067            let interpolated = ruby_template_to_interpolation(template);
2068            let form = match return_form {
2069                TemplateReturnForm::Dict => "dict",
2070                TemplateReturnForm::BareString => "bare_string",
2071            };
2072            ("custom_template", format!("\"{interpolated}\""), form)
2073        }
2074    };
2075
2076    let rendered = crate::template_env::render(
2077        "ruby/visitor_method.jinja",
2078        minijinja::context! {
2079            method_name => method_name,
2080            params => params,
2081            action_type => action_type,
2082            action_value => action_value,
2083            return_form => return_form,
2084        },
2085    );
2086    for line in rendered.lines() {
2087        setup_lines.push(line.to_string());
2088    }
2089}
2090
2091/// Classify a fixture string value that maps to a `bytes` argument.
2092///
2093/// Returns true if the value looks like a file path (e.g. "pdf/fake_memo.pdf").
2094/// File paths have the pattern: alphanumeric/something.extension
2095fn is_file_path(s: &str) -> bool {
2096    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2097        return false;
2098    }
2099
2100    let first = s.chars().next().unwrap_or('\0');
2101    if first.is_ascii_alphanumeric() || first == '_' {
2102        if let Some(slash_pos) = s.find('/') {
2103            if slash_pos > 0 {
2104                let after_slash = &s[slash_pos + 1..];
2105                if after_slash.contains('.') && !after_slash.is_empty() {
2106                    return true;
2107                }
2108            }
2109        }
2110    }
2111
2112    false
2113}
2114
2115/// Check if a string looks like base64-encoded data.
2116/// If it's not a file path or inline text, assume it's base64.
2117fn is_base64(s: &str) -> bool {
2118    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2119        return false;
2120    }
2121
2122    if is_file_path(s) {
2123        return false;
2124    }
2125
2126    true
2127}