Skip to main content

alef_e2e/codegen/
rust.rs

1//! Rust e2e test code generator.
2//!
3//! Generates `e2e/rust/Cargo.toml` and `tests/{category}_test.rs` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{escape_rust, rust_raw_string, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::AlefConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions as tv;
15use anyhow::Result;
16use std::fmt::Write as FmtWrite;
17use std::path::PathBuf;
18
19/// Rust e2e test code generator.
20pub struct RustE2eCodegen;
21
22impl super::E2eCodegen for RustE2eCodegen {
23    fn generate(
24        &self,
25        groups: &[FixtureGroup],
26        e2e_config: &E2eConfig,
27        alef_config: &AlefConfig,
28    ) -> Result<Vec<GeneratedFile>> {
29        let mut files = Vec::new();
30        let output_base = PathBuf::from(e2e_config.effective_output()).join("rust");
31
32        // Resolve crate name and path from config.
33        let crate_name = resolve_crate_name(e2e_config, alef_config);
34        let crate_path = resolve_crate_path(e2e_config, &crate_name);
35        let dep_name = crate_name.replace('-', "_");
36
37        // Cargo.toml
38        // Check if any call config (default or named) uses json_object/handle args (needs serde_json dep).
39        let all_call_configs = std::iter::once(&e2e_config.call).chain(e2e_config.calls.values());
40        let needs_serde_json = all_call_configs
41            .flat_map(|c| c.args.iter())
42            .any(|a| a.arg_type == "json_object" || a.arg_type == "handle");
43
44        // Check if any fixture in any group requires a mock HTTP server.
45        // This includes both liter-llm mock_response fixtures and spikard http fixtures.
46        let needs_mock_server = groups
47            .iter()
48            .flat_map(|g| g.fixtures.iter())
49            .any(|f| !is_skipped(f, "rust") && f.needs_mock_server());
50
51        // Tokio is needed when any test is async (mock server or async call config).
52        let any_async_call = std::iter::once(&e2e_config.call)
53            .chain(e2e_config.calls.values())
54            .any(|c| c.r#async);
55        let needs_tokio = needs_mock_server || any_async_call;
56
57        let crate_version = resolve_crate_version(e2e_config);
58        files.push(GeneratedFile {
59            path: output_base.join("Cargo.toml"),
60            content: render_cargo_toml(
61                &crate_name,
62                &dep_name,
63                &crate_path,
64                needs_serde_json,
65                needs_mock_server,
66                needs_tokio,
67                e2e_config.dep_mode,
68                crate_version.as_deref(),
69                &alef_config.crate_config.features,
70            ),
71            generated_header: true,
72        });
73
74        // Generate mock_server.rs when at least one fixture uses mock_response.
75        if needs_mock_server {
76            files.push(GeneratedFile {
77                path: output_base.join("tests").join("mock_server.rs"),
78                content: render_mock_server_module(),
79                generated_header: true,
80            });
81            // Generate standalone mock-server binary for cross-language e2e suites.
82            files.push(GeneratedFile {
83                path: output_base.join("src").join("main.rs"),
84                content: render_mock_server_binary(),
85                generated_header: true,
86            });
87        }
88
89        // Per-category test files.
90        for group in groups {
91            let fixtures: Vec<&Fixture> = group.fixtures.iter().filter(|f| !is_skipped(f, "rust")).collect();
92
93            if fixtures.is_empty() {
94                continue;
95            }
96
97            let filename = format!("{}_test.rs", sanitize_filename(&group.category));
98            let content = render_test_file(&group.category, &fixtures, e2e_config, &dep_name, needs_mock_server);
99
100            files.push(GeneratedFile {
101                path: output_base.join("tests").join(filename),
102                content,
103                generated_header: true,
104            });
105        }
106
107        Ok(files)
108    }
109
110    fn language_name(&self) -> &'static str {
111        "rust"
112    }
113}
114
115// ---------------------------------------------------------------------------
116// Config resolution helpers
117// ---------------------------------------------------------------------------
118
119fn resolve_crate_name(_e2e_config: &E2eConfig, alef_config: &AlefConfig) -> String {
120    // Always use the Cargo package name (with hyphens) from alef.toml [crate].
121    // The `crate_name` override in [e2e.call.overrides.rust] is for the Rust
122    // import identifier, not the Cargo package name.
123    alef_config.crate_config.name.clone()
124}
125
126fn resolve_crate_path(e2e_config: &E2eConfig, crate_name: &str) -> String {
127    e2e_config
128        .resolve_package("rust")
129        .and_then(|p| p.path.clone())
130        .unwrap_or_else(|| format!("../../crates/{crate_name}"))
131}
132
133fn resolve_crate_version(e2e_config: &E2eConfig) -> Option<String> {
134    e2e_config.resolve_package("rust").and_then(|p| p.version.clone())
135}
136
137fn resolve_function_name_for_call(call_config: &crate::config::CallConfig) -> String {
138    call_config
139        .overrides
140        .get("rust")
141        .and_then(|o| o.function.clone())
142        .unwrap_or_else(|| call_config.function.clone())
143}
144
145fn resolve_module(e2e_config: &E2eConfig, dep_name: &str) -> String {
146    resolve_module_for_call(&e2e_config.call, dep_name)
147}
148
149fn resolve_module_for_call(call_config: &crate::config::CallConfig, dep_name: &str) -> String {
150    // For Rust, the module name is the crate identifier (underscores).
151    // Priority: override.crate_name > override.module > dep_name
152    let overrides = call_config.overrides.get("rust");
153    overrides
154        .and_then(|o| o.crate_name.clone())
155        .or_else(|| overrides.and_then(|o| o.module.clone()))
156        .unwrap_or_else(|| dep_name.to_string())
157}
158
159fn is_skipped(fixture: &Fixture, language: &str) -> bool {
160    fixture.skip.as_ref().is_some_and(|s| s.should_skip(language))
161}
162
163// ---------------------------------------------------------------------------
164// Rendering
165// ---------------------------------------------------------------------------
166
167#[allow(clippy::too_many_arguments)]
168pub fn render_cargo_toml(
169    crate_name: &str,
170    dep_name: &str,
171    crate_path: &str,
172    needs_serde_json: bool,
173    needs_mock_server: bool,
174    needs_tokio: bool,
175    dep_mode: crate::config::DependencyMode,
176    version: Option<&str>,
177    features: &[String],
178) -> String {
179    let e2e_name = format!("{dep_name}-e2e-rust");
180    // Use only the features explicitly configured in alef.toml.
181    // Do NOT auto-add "serde" — the target crate may not have that feature.
182    // serde_json is added as a separate dependency when needed.
183    let effective_features: Vec<&str> = features.iter().map(|s| s.as_str()).collect();
184    let features_str = if effective_features.is_empty() {
185        String::new()
186    } else {
187        format!(", default-features = false, features = {:?}", effective_features)
188    };
189    let dep_spec = match dep_mode {
190        crate::config::DependencyMode::Registry => {
191            let ver = version.unwrap_or("0.1.0");
192            if crate_name != dep_name {
193                format!("{dep_name} = {{ package = \"{crate_name}\", version = \"{ver}\"{features_str} }}")
194            } else if effective_features.is_empty() {
195                format!("{dep_name} = \"{ver}\"")
196            } else {
197                format!("{dep_name} = {{ version = \"{ver}\"{features_str} }}")
198            }
199        }
200        crate::config::DependencyMode::Local => {
201            if crate_name != dep_name {
202                format!("{dep_name} = {{ package = \"{crate_name}\", path = \"{crate_path}\"{features_str} }}")
203            } else if effective_features.is_empty() {
204                format!("{dep_name} = {{ path = \"{crate_path}\" }}")
205            } else {
206                format!("{dep_name} = {{ path = \"{crate_path}\"{features_str} }}")
207            }
208        }
209    };
210    // serde_json is needed either when args use json_object/handle, or when the
211    // mock server binary is present (it uses serde_json::Value for fixture bodies).
212    let effective_needs_serde_json = needs_serde_json || needs_mock_server;
213    let serde_line = if effective_needs_serde_json {
214        "\nserde_json = \"1\""
215    } else {
216        ""
217    };
218    // An empty `[workspace]` table makes the e2e crate its own workspace root, so
219    // it never gets pulled into a parent crate's workspace. This means consumers
220    // don't have to remember to add `e2e/rust` to `workspace.exclude`, and
221    // `cargo fmt`/`cargo build` work the same whether the parent has a
222    // workspace or not.
223    // Mock server requires axum (HTTP router) and tokio-stream (SSE streaming).
224    // The standalone binary additionally needs serde (derive) and walkdir.
225    let mock_lines = if needs_mock_server {
226        format!(
227            "\naxum = \"{axum}\"\ntokio-stream = \"{tokio_stream}\"\nserde = {{ version = \"1\", features = [\"derive\"] }}\nwalkdir = \"{walkdir}\"",
228            axum = tv::cargo::AXUM,
229            tokio_stream = tv::cargo::TOKIO_STREAM,
230            walkdir = tv::cargo::WALKDIR,
231        )
232    } else {
233        String::new()
234    };
235    let mut machete_ignored: Vec<&str> = Vec::new();
236    if effective_needs_serde_json {
237        machete_ignored.push("\"serde_json\"");
238    }
239    if needs_mock_server {
240        machete_ignored.push("\"axum\"");
241        machete_ignored.push("\"tokio-stream\"");
242        machete_ignored.push("\"serde\"");
243        machete_ignored.push("\"walkdir\"");
244    }
245    let machete_section = if machete_ignored.is_empty() {
246        String::new()
247    } else {
248        format!(
249            "\n[package.metadata.cargo-machete]\nignored = [{}]\n",
250            machete_ignored.join(", ")
251        )
252    };
253    let tokio_line = if needs_tokio {
254        "\ntokio = { version = \"1\", features = [\"full\"] }"
255    } else {
256        ""
257    };
258    let bin_section = if needs_mock_server {
259        "\n[[bin]]\nname = \"mock-server\"\npath = \"src/main.rs\"\n"
260    } else {
261        ""
262    };
263    let header = hash::header(CommentStyle::Hash);
264    format!(
265        r#"{header}
266[workspace]
267
268[package]
269name = "{e2e_name}"
270version = "0.1.0"
271edition = "2021"
272license = "MIT"
273publish = false
274{bin_section}
275[dependencies]
276{dep_spec}{serde_line}{mock_lines}{tokio_line}
277{machete_section}"#
278    )
279}
280
281fn render_test_file(
282    category: &str,
283    fixtures: &[&Fixture],
284    e2e_config: &E2eConfig,
285    dep_name: &str,
286    needs_mock_server: bool,
287) -> String {
288    let mut out = String::new();
289    out.push_str(&hash::header(CommentStyle::DoubleSlash));
290    let _ = writeln!(out, "//! E2e tests for category: {category}");
291    let _ = writeln!(out);
292
293    let module = resolve_module(e2e_config, dep_name);
294    let field_resolver = FieldResolver::new(
295        &e2e_config.fields,
296        &e2e_config.fields_optional,
297        &e2e_config.result_fields,
298        &e2e_config.fields_array,
299    );
300
301    // Collect all unique (module, function) pairs needed across all fixtures in this file.
302    // Fixtures that name a specific call may use a different function (and module) than
303    // the default [e2e.call] config.
304    let mut imported: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();
305    for fixture in fixtures.iter() {
306        let call_config = e2e_config.resolve_call(fixture.call.as_deref());
307        let fn_name = resolve_function_name_for_call(call_config);
308        let mod_name = resolve_module_for_call(call_config, dep_name);
309        imported.insert((mod_name, fn_name));
310    }
311    // Emit use statements, grouping by module when possible.
312    let mut by_module: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
313    for (mod_name, fn_name) in &imported {
314        by_module.entry(mod_name.clone()).or_default().push(fn_name.clone());
315    }
316    for (mod_name, fns) in &by_module {
317        if fns.len() == 1 {
318            let _ = writeln!(out, "use {mod_name}::{};", fns[0]);
319        } else {
320            let joined = fns.join(", ");
321            let _ = writeln!(out, "use {mod_name}::{{{joined}}};");
322        }
323    }
324
325    // Import handle constructor functions and the config type they use.
326    let has_handle_args = e2e_config.call.args.iter().any(|a| a.arg_type == "handle");
327    if has_handle_args {
328        let _ = writeln!(out, "use {module}::CrawlConfig;");
329    }
330    for arg in &e2e_config.call.args {
331        if arg.arg_type == "handle" {
332            use heck::ToSnakeCase;
333            let constructor_name = format!("create_{}", arg.name.to_snake_case());
334            let _ = writeln!(out, "use {module}::{constructor_name};");
335        }
336    }
337
338    // Import mock_server module when any fixture in this file uses mock_response.
339    let file_needs_mock = needs_mock_server && fixtures.iter().any(|f| f.needs_mock_server());
340    if file_needs_mock {
341        let _ = writeln!(out, "mod mock_server;");
342        let _ = writeln!(out, "use mock_server::{{MockRoute, MockServer}};");
343    }
344
345    // Import the visitor trait, result enum, and node context when any fixture
346    // in this file declares a `visitor` block. Without these, the inline
347    // `impl HtmlVisitor for _TestVisitor` block fails to resolve.
348    let file_needs_visitor = fixtures.iter().any(|f| f.visitor.is_some());
349    if file_needs_visitor {
350        let visitor_trait = resolve_visitor_trait(&module);
351        let _ = writeln!(out, "use {module}::{{{visitor_trait}, NodeContext, VisitResult}};");
352    }
353
354    let _ = writeln!(out);
355
356    for fixture in fixtures {
357        render_test_function(&mut out, fixture, e2e_config, dep_name, &field_resolver);
358        let _ = writeln!(out);
359    }
360
361    if !out.ends_with('\n') {
362        out.push('\n');
363    }
364    out
365}
366
367fn render_test_function(
368    out: &mut String,
369    fixture: &Fixture,
370    e2e_config: &E2eConfig,
371    dep_name: &str,
372    field_resolver: &FieldResolver,
373) {
374    let fn_name = sanitize_ident(&fixture.id);
375    let description = &fixture.description;
376    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
377    let function_name = resolve_function_name_for_call(call_config);
378    let module = resolve_module_for_call(call_config, dep_name);
379    let result_var = &call_config.result_var;
380    let has_mock = fixture.needs_mock_server();
381
382    // Tests with a mock server are always async (Axum requires a Tokio runtime).
383    let is_async = call_config.r#async || has_mock;
384    if is_async {
385        let _ = writeln!(out, "#[tokio::test]");
386        let _ = writeln!(out, "async fn test_{fn_name}() {{");
387    } else {
388        let _ = writeln!(out, "#[test]");
389        let _ = writeln!(out, "fn test_{fn_name}() {{");
390    }
391    let _ = writeln!(out, "    // {description}");
392
393    // Emit mock server setup before building arguments so arg expressions can
394    // reference `mock_server.url` when needed.
395    if has_mock {
396        render_mock_server_setup(out, fixture, e2e_config);
397    }
398
399    // Check if any assertion is an error assertion.
400    let has_error_assertion = fixture.assertions.iter().any(|a| a.assertion_type == "error");
401
402    // Resolve Rust-specific overrides for argument shaping.
403    let rust_overrides = call_config.overrides.get("rust");
404    let wrap_options_in_some = rust_overrides.is_some_and(|o| o.wrap_options_in_some);
405    let extra_args: Vec<String> = rust_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
406
407    // Emit input variable bindings from args config.
408    let mut arg_exprs: Vec<String> = Vec::new();
409    for arg in &call_config.args {
410        let value = resolve_field(&fixture.input, &arg.field);
411        let var_name = &arg.name;
412        let (bindings, expr) = render_rust_arg(
413            var_name,
414            value,
415            &arg.arg_type,
416            arg.optional,
417            &module,
418            &fixture.id,
419            if has_mock {
420                Some("mock_server.url.as_str()")
421            } else {
422                None
423            },
424            arg.owned,
425            arg.element_type.as_deref(),
426        );
427        for binding in &bindings {
428            let _ = writeln!(out, "    {binding}");
429        }
430        // For functions whose options slot is owned `Option<T>` rather than `&T`,
431        // wrap the json_object expression in `Some(...).clone()` so it matches
432        // the parameter shape. Other arg types pass through unchanged.
433        let final_expr = if wrap_options_in_some && arg.arg_type == "json_object" {
434            if let Some(rest) = expr.strip_prefix('&') {
435                format!("Some({rest}.clone())")
436            } else {
437                format!("Some({expr})")
438            }
439        } else {
440            expr
441        };
442        arg_exprs.push(final_expr);
443    }
444
445    // Emit visitor if present in fixture.
446    if let Some(visitor_spec) = &fixture.visitor {
447        let _ = writeln!(out, "    struct _TestVisitor;");
448        let _ = writeln!(out, "    impl {} for _TestVisitor {{", resolve_visitor_trait(&module));
449        for (method_name, action) in &visitor_spec.callbacks {
450            emit_rust_visitor_method(out, method_name, action);
451        }
452        let _ = writeln!(out, "    }}");
453        let _ = writeln!(
454            out,
455            "    let visitor = std::rc::Rc::new(std::cell::RefCell::new(_TestVisitor));"
456        );
457        arg_exprs.push("Some(visitor)".to_string());
458    } else {
459        // No fixture-supplied visitor: append any extra positional args declared in
460        // the rust override (e.g. trailing `None` for an Option<VisitorParam> slot).
461        arg_exprs.extend(extra_args);
462    }
463
464    let args_str = arg_exprs.join(", ");
465
466    let await_suffix = if is_async { ".await" } else { "" };
467
468    let result_is_tree = call_config.result_var == "tree";
469    // When the rust override sets result_is_simple, the function returns a plain type
470    // (String, Vec<T>, etc.) — field-access assertions use the result var directly.
471    let result_is_simple = rust_overrides.is_some_and(|o| o.result_is_simple);
472    // When result_is_vec is set, the function returns Vec<T>. Field-path assertions
473    // are wrapped in `.iter().all(|r| ...)` so every element is checked.
474    let result_is_vec = rust_overrides.is_some_and(|o| o.result_is_vec);
475    // When result_is_option is set, the function returns Option<T>. Field-path
476    // assertions unwrap first via `.as_ref().expect("Option should be Some")`.
477    let result_is_option = rust_overrides.is_some_and(|o| o.result_is_option);
478
479    if has_error_assertion {
480        let _ = writeln!(out, "    let {result_var} = {function_name}({args_str}){await_suffix};");
481        // Render error assertions.
482        for assertion in &fixture.assertions {
483            render_assertion(
484                out,
485                assertion,
486                result_var,
487                &module,
488                dep_name,
489                true,
490                &[],
491                field_resolver,
492                result_is_tree,
493                result_is_simple,
494                false,
495                false,
496            );
497        }
498        let _ = writeln!(out, "}}");
499        return;
500    }
501
502    // Non-error path: unwrap the result.
503    let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
504
505    // Check if any assertion actually uses the result variable.
506    // If all assertions are skipped (field not on result type), use `_` to avoid
507    // Rust's "variable never used" warning.
508    let has_usable_assertion = fixture.assertions.iter().any(|a| {
509        if a.assertion_type == "not_error" || a.assertion_type == "error" {
510            return false;
511        }
512        if a.assertion_type == "method_result" {
513            // method_result assertions that would generate only a TODO comment don't use the
514            // result variable. These are: missing `method` field, or unsupported `check` type.
515            let supported_checks = [
516                "equals",
517                "is_true",
518                "is_false",
519                "greater_than_or_equal",
520                "count_min",
521                "is_error",
522                "contains",
523                "not_empty",
524                "is_empty",
525            ];
526            let check = a.check.as_deref().unwrap_or("is_true");
527            if a.method.is_none() || !supported_checks.contains(&check) {
528                return false;
529            }
530        }
531        match &a.field {
532            Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
533            _ => true,
534        }
535    });
536
537    let result_binding = if has_usable_assertion {
538        result_var.to_string()
539    } else {
540        "_".to_string()
541    };
542
543    // Detect Option-returning functions: only skip unwrap when ALL assertions are
544    // pure emptiness/bool checks with NO field access (is_none/is_some on the result itself).
545    // If any assertion accesses a field (e.g. `html`), we need the inner value, so unwrap.
546    let has_field_access = fixture
547        .assertions
548        .iter()
549        .any(|a| a.field.as_ref().is_some_and(|f| !f.is_empty()));
550    let only_emptiness_checks = !has_field_access
551        && fixture.assertions.iter().all(|a| {
552            matches!(
553                a.assertion_type.as_str(),
554                "is_empty" | "is_false" | "not_empty" | "is_true" | "not_error"
555            )
556        });
557
558    // Per-rust override of the call-level `returns_result`. When set, takes
559    // precedence over `CallConfig.returns_result` for the Rust generator only.
560    let returns_result = rust_overrides
561        .and_then(|o| o.returns_result)
562        .unwrap_or(call_config.returns_result);
563
564    let unwrap_suffix = if returns_result {
565        ".expect(\"should succeed\")"
566    } else {
567        ""
568    };
569    if only_emptiness_checks || !returns_result {
570        // Option-returning or non-Result-returning: bind raw value, no unwrap.
571        let _ = writeln!(
572            out,
573            "    let {result_binding} = {function_name}({args_str}){await_suffix};"
574        );
575    } else if has_not_error || !fixture.assertions.is_empty() {
576        let _ = writeln!(
577            out,
578            "    let {result_binding} = {function_name}({args_str}){await_suffix}{unwrap_suffix};"
579        );
580    } else {
581        let _ = writeln!(
582            out,
583            "    let {result_binding} = {function_name}({args_str}){await_suffix};"
584        );
585    }
586
587    // Emit Option field unwrap bindings for any fields accessed in assertions.
588    // Use FieldResolver to handle optional fields, including nested/aliased paths.
589    let string_assertion_types = [
590        "equals",
591        "contains",
592        "contains_all",
593        "contains_any",
594        "not_contains",
595        "starts_with",
596        "ends_with",
597        "min_length",
598        "max_length",
599        "matches_regex",
600    ];
601    let mut unwrapped_fields: Vec<(String, String)> = Vec::new(); // (fixture_field, local_var)
602    for assertion in &fixture.assertions {
603        if let Some(f) = &assertion.field {
604            if !f.is_empty()
605                && string_assertion_types.contains(&assertion.assertion_type.as_str())
606                && !unwrapped_fields.iter().any(|(ff, _)| ff == f)
607            {
608                // Only unwrap optional string fields — numeric optionals (u64, usize)
609                // don't support .as_deref() and should be compared directly.
610                let is_string_assertion = assertion.value.as_ref().is_none_or(|v| v.is_string());
611                if !is_string_assertion {
612                    continue;
613                }
614                if let Some((binding, local_var)) = field_resolver.rust_unwrap_binding(f, result_var) {
615                    let _ = writeln!(out, "    {binding}");
616                    unwrapped_fields.push((f.clone(), local_var));
617                }
618            }
619        }
620    }
621
622    // Render assertions.
623    for assertion in &fixture.assertions {
624        if assertion.assertion_type == "not_error" {
625            // Already handled by .expect() above.
626            continue;
627        }
628        render_assertion(
629            out,
630            assertion,
631            result_var,
632            &module,
633            dep_name,
634            false,
635            &unwrapped_fields,
636            field_resolver,
637            result_is_tree,
638            result_is_simple,
639            result_is_vec,
640            result_is_option,
641        );
642    }
643
644    let _ = writeln!(out, "}}");
645}
646
647// ---------------------------------------------------------------------------
648// Argument rendering
649// ---------------------------------------------------------------------------
650
651#[allow(clippy::too_many_arguments)]
652fn render_rust_arg(
653    name: &str,
654    value: &serde_json::Value,
655    arg_type: &str,
656    optional: bool,
657    module: &str,
658    fixture_id: &str,
659    mock_base_url: Option<&str>,
660    owned: bool,
661    element_type: Option<&str>,
662) -> (Vec<String>, String) {
663    if arg_type == "mock_url" {
664        let lines = vec![format!(
665            "let {name} = format!(\"{{}}/fixtures/{{}}\", std::env::var(\"MOCK_SERVER_URL\").expect(\"MOCK_SERVER_URL not set\"), \"{fixture_id}\");"
666        )];
667        return (lines, format!("&{name}"));
668    }
669    // When the arg is a base_url and a mock server is running, use the mock server URL.
670    if arg_type == "base_url" {
671        if let Some(url_expr) = mock_base_url {
672            return (vec![], url_expr.to_string());
673        }
674        // No mock server: fall through to string handling below.
675    }
676    if arg_type == "handle" {
677        // Generate a create_engine (or equivalent) call and pass the config.
678        // If the fixture has input.config, serialize it as a json_object and pass it;
679        // otherwise pass None.
680        use heck::ToSnakeCase;
681        let constructor_name = format!("create_{}", name.to_snake_case());
682        let mut lines = Vec::new();
683        if value.is_null() || value.is_object() && value.as_object().unwrap().is_empty() {
684            lines.push(format!(
685                "let {name} = {constructor_name}(None).expect(\"handle creation should succeed\");"
686            ));
687        } else {
688            // Serialize the config JSON and deserialize at runtime.
689            let json_literal = serde_json::to_string(value).unwrap_or_default();
690            let escaped = json_literal.replace('\\', "\\\\").replace('"', "\\\"");
691            lines.push(format!(
692                "let {name}_config: CrawlConfig = serde_json::from_str(\"{escaped}\").expect(\"config should parse\");"
693            ));
694            lines.push(format!(
695                "let {name} = {constructor_name}(Some({name}_config)).expect(\"handle creation should succeed\");"
696            ));
697        }
698        return (lines, format!("&{name}"));
699    }
700    if arg_type == "json_object" {
701        return render_json_object_arg(name, value, optional, owned, element_type, module);
702    }
703    if value.is_null() && !optional {
704        // Required arg with no fixture value: use a language-appropriate default.
705        let default_val = match arg_type {
706            "string" => "String::new()".to_string(),
707            "int" | "integer" => "0".to_string(),
708            "float" | "number" => "0.0_f64".to_string(),
709            "bool" | "boolean" => "false".to_string(),
710            _ => "Default::default()".to_string(),
711        };
712        // String args are passed by reference in Rust.
713        let expr = if arg_type == "string" {
714            format!("&{name}")
715        } else {
716            name.to_string()
717        };
718        return (vec![format!("let {name} = {default_val};")], expr);
719    }
720    let literal = json_to_rust_literal(value, arg_type);
721    // String args are passed by reference in Rust.
722    // Bytes args are strings passed as .as_bytes().
723    let pass_by_ref = arg_type == "string" || arg_type == "bytes";
724    let optional_expr = |n: &str| {
725        if arg_type == "string" {
726            format!("{n}.as_deref()")
727        } else if arg_type == "bytes" {
728            format!("{n}.as_deref().map(|v| v.as_slice())")
729        } else {
730            format!("{n}.as_ref()")
731        }
732    };
733    let expr = |n: &str| {
734        if arg_type == "bytes" {
735            format!("{n}.as_bytes()")
736        } else if pass_by_ref {
737            format!("&{n}")
738        } else {
739            n.to_string()
740        }
741    };
742    if optional && value.is_null() {
743        let none_decl = match arg_type {
744            "string" => format!("let {name}: Option<String> = None;"),
745            "bytes" => format!("let {name}: Option<Vec<u8>> = None;"),
746            _ => format!("let {name} = None;"),
747        };
748        (vec![none_decl], optional_expr(name))
749    } else if optional {
750        (vec![format!("let {name} = Some({literal});")], optional_expr(name))
751    } else {
752        (vec![format!("let {name} = {literal};")], expr(name))
753    }
754}
755
756/// Render a `json_object` argument: serialize the fixture JSON as a `serde_json::json!` literal
757/// and deserialize it through serde at runtime. Type inference from the function signature
758/// determines the concrete type, keeping the generator generic.
759///
760/// `owned` — when true the binding is passed by value (no leading `&`); use for `Vec<T>` params.
761/// `element_type` — when set, emits `Vec<element_type>` annotation to satisfy type inference for
762///   `&[T]` parameters where `serde_json::from_value` cannot resolve the unsized slice type.
763fn render_json_object_arg(
764    name: &str,
765    value: &serde_json::Value,
766    optional: bool,
767    owned: bool,
768    element_type: Option<&str>,
769    _module: &str,
770) -> (Vec<String>, String) {
771    // Owned params (Vec<T>) are passed by value; ref params (most configs) use &.
772    let pass_by_ref = !owned;
773
774    if value.is_null() && optional {
775        // Use Default::default() — Rust functions take &T (or T for owned), not Option<T>.
776        let expr = if pass_by_ref {
777            format!("&{name}")
778        } else {
779            name.to_string()
780        };
781        return (vec![format!("let {name} = Default::default();")], expr);
782    }
783
784    // Fixture keys are camelCase; the Rust ConversionOptions type uses snake_case serde.
785    // Normalize keys before building the json! literal so deserialization succeeds.
786    let normalized = super::normalize_json_keys_to_snake_case(value);
787    // Build the json! macro invocation from the fixture object.
788    let json_literal = json_value_to_macro_literal(&normalized);
789    let mut lines = Vec::new();
790    lines.push(format!("let {name}_json = serde_json::json!({json_literal});"));
791
792    // When an explicit element type is given, annotate with Vec<T> so that
793    // serde_json::from_value can infer the element type for &[T] parameters (A4 fix).
794    let deser_expr = if let Some(elem) = element_type {
795        format!("serde_json::from_value::<Vec<{elem}>>({name}_json).unwrap()")
796    } else {
797        format!("serde_json::from_value({name}_json).unwrap()")
798    };
799
800    // A1 fix: always deser as T (never wrap in Some()); optional non-null args target
801    // &T not &Option<T>. Pass as &T (ref) or T (owned) depending on the `owned` flag.
802    lines.push(format!("let {name} = {deser_expr};"));
803    let expr = if pass_by_ref {
804        format!("&{name}")
805    } else {
806        name.to_string()
807    };
808    (lines, expr)
809}
810
811/// Convert a `serde_json::Value` into a string suitable for the `serde_json::json!()` macro.
812fn json_value_to_macro_literal(value: &serde_json::Value) -> String {
813    match value {
814        serde_json::Value::Null => "null".to_string(),
815        serde_json::Value::Bool(b) => format!("{b}"),
816        serde_json::Value::Number(n) => n.to_string(),
817        serde_json::Value::String(s) => {
818            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
819            format!("\"{escaped}\"")
820        }
821        serde_json::Value::Array(arr) => {
822            let items: Vec<String> = arr.iter().map(json_value_to_macro_literal).collect();
823            format!("[{}]", items.join(", "))
824        }
825        serde_json::Value::Object(obj) => {
826            let entries: Vec<String> = obj
827                .iter()
828                .map(|(k, v)| {
829                    let escaped_key = k.replace('\\', "\\\\").replace('"', "\\\"");
830                    format!("\"{escaped_key}\": {}", json_value_to_macro_literal(v))
831                })
832                .collect();
833            format!("{{{}}}", entries.join(", "))
834        }
835    }
836}
837
838fn json_to_rust_literal(value: &serde_json::Value, arg_type: &str) -> String {
839    match value {
840        serde_json::Value::Null => "None".to_string(),
841        serde_json::Value::Bool(b) => format!("{b}"),
842        serde_json::Value::Number(n) => {
843            if arg_type.contains("float") || arg_type.contains("f64") || arg_type.contains("f32") {
844                if let Some(f) = n.as_f64() {
845                    return format!("{f}_f64");
846                }
847            }
848            n.to_string()
849        }
850        serde_json::Value::String(s) => rust_raw_string(s),
851        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
852            let json_str = serde_json::to_string(value).unwrap_or_default();
853            let literal = rust_raw_string(&json_str);
854            format!("serde_json::from_str({literal}).unwrap()")
855        }
856    }
857}
858
859// ---------------------------------------------------------------------------
860// Mock server helpers
861// ---------------------------------------------------------------------------
862
863/// Emit mock server setup lines into a test function body.
864///
865/// Builds `MockRoute` objects from the fixture's `mock_response` and starts
866/// the server.  The resulting `mock_server` variable is in scope for the rest
867/// of the test function.
868fn render_mock_server_setup(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig) {
869    let mock = match fixture.mock_response.as_ref() {
870        Some(m) => m,
871        None => return,
872    };
873
874    // Resolve the HTTP path and method from the call config.
875    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
876    let path = call_config.path.as_deref().unwrap_or("/");
877    let method = call_config.method.as_deref().unwrap_or("POST");
878
879    let status = mock.status;
880
881    // Render headers map as a Vec<(String, String)> literal for stable iteration order.
882    let mut header_entries: Vec<(&String, &String)> = mock.headers.iter().collect();
883    header_entries.sort_by(|a, b| a.0.cmp(b.0));
884    let render_headers = |out: &mut String| {
885        let _ = writeln!(out, "        headers: vec![");
886        for (name, value) in &header_entries {
887            let n = rust_raw_string(name);
888            let v = rust_raw_string(value);
889            let _ = writeln!(out, "            ({n}.to_string(), {v}.to_string()),");
890        }
891        let _ = writeln!(out, "        ],");
892    };
893
894    if let Some(chunks) = &mock.stream_chunks {
895        // Streaming SSE response.
896        let _ = writeln!(out, "    let mock_route = MockRoute {{");
897        let _ = writeln!(out, "        path: \"{path}\",");
898        let _ = writeln!(out, "        method: \"{method}\",");
899        let _ = writeln!(out, "        status: {status},");
900        let _ = writeln!(out, "        body: String::new(),");
901        let _ = writeln!(out, "        stream_chunks: vec![");
902        for chunk in chunks {
903            let chunk_str = match chunk {
904                serde_json::Value::String(s) => rust_raw_string(s),
905                other => {
906                    let s = serde_json::to_string(other).unwrap_or_default();
907                    rust_raw_string(&s)
908                }
909            };
910            let _ = writeln!(out, "            {chunk_str}.to_string(),");
911        }
912        let _ = writeln!(out, "        ],");
913        render_headers(out);
914        let _ = writeln!(out, "    }};");
915    } else {
916        // Non-streaming JSON response.
917        let body_str = match &mock.body {
918            Some(b) => {
919                let s = serde_json::to_string(b).unwrap_or_default();
920                rust_raw_string(&s)
921            }
922            None => rust_raw_string("{}"),
923        };
924        let _ = writeln!(out, "    let mock_route = MockRoute {{");
925        let _ = writeln!(out, "        path: \"{path}\",");
926        let _ = writeln!(out, "        method: \"{method}\",");
927        let _ = writeln!(out, "        status: {status},");
928        let _ = writeln!(out, "        body: {body_str}.to_string(),");
929        let _ = writeln!(out, "        stream_chunks: vec![],");
930        render_headers(out);
931        let _ = writeln!(out, "    }};");
932    }
933
934    let _ = writeln!(out, "    let mock_server = MockServer::start(vec![mock_route]).await;");
935}
936
937/// Generate the complete `mock_server.rs` module source.
938pub fn render_mock_server_module() -> String {
939    // This is parameterized Axum mock server code identical in structure to
940    // liter-llm's mock_server.rs but without any project-specific imports.
941    hash::header(CommentStyle::DoubleSlash)
942        + r#"//
943// Minimal axum-based mock HTTP server for e2e tests.
944
945use std::net::SocketAddr;
946use std::sync::Arc;
947
948use axum::Router;
949use axum::body::Body;
950use axum::extract::State;
951use axum::http::{Request, StatusCode};
952use axum::response::{IntoResponse, Response};
953use tokio::net::TcpListener;
954
955/// A single mock route: match by path + method, return a configured response.
956#[derive(Clone, Debug)]
957pub struct MockRoute {
958    /// URL path to match, e.g. `"/v1/chat/completions"`.
959    pub path: &'static str,
960    /// HTTP method to match, e.g. `"POST"` or `"GET"`.
961    pub method: &'static str,
962    /// HTTP status code to return.
963    pub status: u16,
964    /// Response body JSON string (used when `stream_chunks` is empty).
965    pub body: String,
966    /// Ordered SSE data payloads for streaming responses.
967    /// Each entry becomes `data: <chunk>\n\n` in the response.
968    /// A final `data: [DONE]\n\n` is always appended.
969    pub stream_chunks: Vec<String>,
970    /// Response headers to apply (name, value) pairs.
971    /// Multiple entries with the same name produce multiple header lines.
972    pub headers: Vec<(String, String)>,
973}
974
975struct ServerState {
976    routes: Vec<MockRoute>,
977}
978
979pub struct MockServer {
980    /// Base URL of the mock server, e.g. `"http://127.0.0.1:54321"`.
981    pub url: String,
982    handle: tokio::task::JoinHandle<()>,
983}
984
985impl MockServer {
986    /// Start a mock server with the given routes.  Binds to a random port on
987    /// localhost and returns immediately once the server is listening.
988    pub async fn start(routes: Vec<MockRoute>) -> Self {
989        let state = Arc::new(ServerState { routes });
990
991        let app = Router::new().fallback(handle_request).with_state(state);
992
993        let listener = TcpListener::bind("127.0.0.1:0")
994            .await
995            .expect("Failed to bind mock server port");
996        let addr: SocketAddr = listener.local_addr().expect("Failed to get local addr");
997        let url = format!("http://{addr}");
998
999        let handle = tokio::spawn(async move {
1000            axum::serve(listener, app).await.expect("Mock server failed");
1001        });
1002
1003        MockServer { url, handle }
1004    }
1005
1006    /// Stop the mock server.
1007    pub fn shutdown(self) {
1008        self.handle.abort();
1009    }
1010}
1011
1012impl Drop for MockServer {
1013    fn drop(&mut self) {
1014        self.handle.abort();
1015    }
1016}
1017
1018async fn handle_request(State(state): State<Arc<ServerState>>, req: Request<Body>) -> Response {
1019    let path = req.uri().path().to_owned();
1020    let method = req.method().as_str().to_uppercase();
1021
1022    for route in &state.routes {
1023        if route.path == path && route.method.to_uppercase() == method {
1024            let status =
1025                StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1026
1027            if !route.stream_chunks.is_empty() {
1028                // Build SSE body: data: <chunk>\n\n ... data: [DONE]\n\n
1029                let mut sse = String::new();
1030                for chunk in &route.stream_chunks {
1031                    sse.push_str("data: ");
1032                    sse.push_str(chunk);
1033                    sse.push_str("\n\n");
1034                }
1035                sse.push_str("data: [DONE]\n\n");
1036
1037                let mut builder = Response::builder()
1038                    .status(status)
1039                    .header("content-type", "text/event-stream")
1040                    .header("cache-control", "no-cache");
1041                for (name, value) in &route.headers {
1042                    builder = builder.header(name, value);
1043                }
1044                return builder.body(Body::from(sse)).unwrap().into_response();
1045            }
1046
1047            let mut builder =
1048                Response::builder().status(status).header("content-type", "application/json");
1049            for (name, value) in &route.headers {
1050                builder = builder.header(name, value);
1051            }
1052            return builder.body(Body::from(route.body.clone())).unwrap().into_response();
1053        }
1054    }
1055
1056    // No matching route → 404.
1057    Response::builder()
1058        .status(StatusCode::NOT_FOUND)
1059        .body(Body::from(format!("No mock route for {method} {path}")))
1060        .unwrap()
1061        .into_response()
1062}
1063"#
1064}
1065
1066/// Generate the `src/main.rs` for the standalone mock server binary.
1067///
1068/// The binary:
1069/// - Reads all `*.json` fixture files from a fixtures directory (default `../../fixtures`).
1070/// - For each fixture that has a `mock_response` field, registers a route at
1071///   `/fixtures/{fixture_id}` returning the configured status/body/SSE chunks.
1072/// - Binds to `127.0.0.1:0` (random port), prints `MOCK_SERVER_URL=http://...`
1073///   to stdout, then waits until stdin is closed for clean teardown.
1074///
1075/// This binary is intended for cross-language e2e suites (WASM, Node) that
1076/// spawn it as a child process and read the URL from its stdout.
1077pub fn render_mock_server_binary() -> String {
1078    hash::header(CommentStyle::DoubleSlash)
1079        + r#"//
1080// Standalone mock HTTP server binary for cross-language e2e tests.
1081// Reads fixture JSON files and serves mock responses on /fixtures/{fixture_id}.
1082//
1083// Usage: mock-server [fixtures-dir]
1084//   fixtures-dir defaults to "../../fixtures"
1085//
1086// Prints `MOCK_SERVER_URL=http://127.0.0.1:<port>` to stdout once listening,
1087// then blocks until stdin is closed (parent process exit triggers cleanup).
1088
1089use std::collections::HashMap;
1090use std::io::{self, BufRead};
1091use std::net::SocketAddr;
1092use std::path::Path;
1093use std::sync::Arc;
1094
1095use axum::Router;
1096use axum::body::Body;
1097use axum::extract::State;
1098use axum::http::{Request, StatusCode};
1099use axum::response::{IntoResponse, Response};
1100use serde::Deserialize;
1101use tokio::net::TcpListener;
1102
1103// ---------------------------------------------------------------------------
1104// Fixture types (mirrors alef-e2e's fixture.rs for runtime deserialization)
1105// Supports both schemas:
1106//   liter-llm: mock_response: { status, body, stream_chunks }
1107//   spikard:   http.expected_response: { status_code, body, headers }
1108// ---------------------------------------------------------------------------
1109
1110#[derive(Debug, Deserialize)]
1111struct MockResponse {
1112    status: u16,
1113    #[serde(default)]
1114    body: Option<serde_json::Value>,
1115    #[serde(default)]
1116    stream_chunks: Option<Vec<serde_json::Value>>,
1117    #[serde(default)]
1118    headers: HashMap<String, String>,
1119}
1120
1121#[derive(Debug, Deserialize)]
1122struct HttpExpectedResponse {
1123    status_code: u16,
1124    #[serde(default)]
1125    body: Option<serde_json::Value>,
1126    #[serde(default)]
1127    headers: HashMap<String, String>,
1128}
1129
1130#[derive(Debug, Deserialize)]
1131struct HttpFixture {
1132    expected_response: HttpExpectedResponse,
1133}
1134
1135#[derive(Debug, Deserialize)]
1136struct Fixture {
1137    id: String,
1138    #[serde(default)]
1139    mock_response: Option<MockResponse>,
1140    #[serde(default)]
1141    http: Option<HttpFixture>,
1142}
1143
1144impl Fixture {
1145    /// Bridge both schemas into a unified MockResponse.
1146    fn as_mock_response(&self) -> Option<MockResponse> {
1147        if let Some(mock) = &self.mock_response {
1148            return Some(MockResponse {
1149                status: mock.status,
1150                body: mock.body.clone(),
1151                stream_chunks: mock.stream_chunks.clone(),
1152                headers: mock.headers.clone(),
1153            });
1154        }
1155        if let Some(http) = &self.http {
1156            return Some(MockResponse {
1157                status: http.expected_response.status_code,
1158                body: http.expected_response.body.clone(),
1159                stream_chunks: None,
1160                headers: http.expected_response.headers.clone(),
1161            });
1162        }
1163        None
1164    }
1165}
1166
1167// ---------------------------------------------------------------------------
1168// Route table
1169// ---------------------------------------------------------------------------
1170
1171#[derive(Clone, Debug)]
1172struct MockRoute {
1173    status: u16,
1174    body: String,
1175    stream_chunks: Vec<String>,
1176    headers: Vec<(String, String)>,
1177}
1178
1179type RouteTable = Arc<HashMap<String, MockRoute>>;
1180
1181// ---------------------------------------------------------------------------
1182// Axum handler
1183// ---------------------------------------------------------------------------
1184
1185async fn handle_request(State(routes): State<RouteTable>, req: Request<Body>) -> Response {
1186    let path = req.uri().path().to_owned();
1187
1188    // Try exact match first
1189    if let Some(route) = routes.get(&path) {
1190        return serve_route(route);
1191    }
1192
1193    // Try prefix match: find a route that is a prefix of the request path
1194    // This allows /fixtures/basic_chat/v1/chat/completions to match /fixtures/basic_chat
1195    for (route_path, route) in routes.iter() {
1196        if path.starts_with(route_path) && (path.len() == route_path.len() || path.as_bytes()[route_path.len()] == b'/') {
1197            return serve_route(route);
1198        }
1199    }
1200
1201    Response::builder()
1202        .status(StatusCode::NOT_FOUND)
1203        .body(Body::from(format!("No mock route for {path}")))
1204        .unwrap()
1205        .into_response()
1206}
1207
1208fn serve_route(route: &MockRoute) -> Response {
1209    let status = StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1210
1211    if !route.stream_chunks.is_empty() {
1212        let mut sse = String::new();
1213        for chunk in &route.stream_chunks {
1214            sse.push_str("data: ");
1215            sse.push_str(chunk);
1216            sse.push_str("\n\n");
1217        }
1218        sse.push_str("data: [DONE]\n\n");
1219
1220        let mut builder = Response::builder()
1221            .status(status)
1222            .header("content-type", "text/event-stream")
1223            .header("cache-control", "no-cache");
1224        for (name, value) in &route.headers {
1225            builder = builder.header(name, value);
1226        }
1227        return builder.body(Body::from(sse)).unwrap().into_response();
1228    }
1229
1230    let mut builder = Response::builder().status(status).header("content-type", "application/json");
1231    for (name, value) in &route.headers {
1232        builder = builder.header(name, value);
1233    }
1234    builder.body(Body::from(route.body.clone())).unwrap().into_response()
1235}
1236
1237// ---------------------------------------------------------------------------
1238// Fixture loading
1239// ---------------------------------------------------------------------------
1240
1241fn load_routes(fixtures_dir: &Path) -> HashMap<String, MockRoute> {
1242    let mut routes = HashMap::new();
1243    load_routes_recursive(fixtures_dir, &mut routes);
1244    routes
1245}
1246
1247fn load_routes_recursive(dir: &Path, routes: &mut HashMap<String, MockRoute>) {
1248    let entries = match std::fs::read_dir(dir) {
1249        Ok(e) => e,
1250        Err(err) => {
1251            eprintln!("warning: cannot read directory {}: {err}", dir.display());
1252            return;
1253        }
1254    };
1255
1256    let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1257    paths.sort();
1258
1259    for path in paths {
1260        if path.is_dir() {
1261            load_routes_recursive(&path, routes);
1262        } else if path.extension().is_some_and(|ext| ext == "json") {
1263            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1264            if filename == "schema.json" || filename.starts_with('_') {
1265                continue;
1266            }
1267            let content = match std::fs::read_to_string(&path) {
1268                Ok(c) => c,
1269                Err(err) => {
1270                    eprintln!("warning: cannot read {}: {err}", path.display());
1271                    continue;
1272                }
1273            };
1274            let fixtures: Vec<Fixture> = if content.trim_start().starts_with('[') {
1275                match serde_json::from_str(&content) {
1276                    Ok(v) => v,
1277                    Err(err) => {
1278                        eprintln!("warning: cannot parse {}: {err}", path.display());
1279                        continue;
1280                    }
1281                }
1282            } else {
1283                match serde_json::from_str::<Fixture>(&content) {
1284                    Ok(f) => vec![f],
1285                    Err(err) => {
1286                        eprintln!("warning: cannot parse {}: {err}", path.display());
1287                        continue;
1288                    }
1289                }
1290            };
1291
1292            for fixture in fixtures {
1293                if let Some(mock) = fixture.as_mock_response() {
1294                    let route_path = format!("/fixtures/{}", fixture.id);
1295                    let body = mock
1296                        .body
1297                        .as_ref()
1298                        .map(|b| serde_json::to_string(b).unwrap_or_default())
1299                        .unwrap_or_default();
1300                    let stream_chunks = mock
1301                        .stream_chunks
1302                        .unwrap_or_default()
1303                        .into_iter()
1304                        .map(|c| match c {
1305                            serde_json::Value::String(s) => s,
1306                            other => serde_json::to_string(&other).unwrap_or_default(),
1307                        })
1308                        .collect();
1309                    let mut headers: Vec<(String, String)> =
1310                        mock.headers.into_iter().collect();
1311                    headers.sort_by(|a, b| a.0.cmp(&b.0));
1312                    routes.insert(route_path, MockRoute { status: mock.status, body, stream_chunks, headers });
1313                }
1314            }
1315        }
1316    }
1317}
1318
1319// ---------------------------------------------------------------------------
1320// Entry point
1321// ---------------------------------------------------------------------------
1322
1323#[tokio::main]
1324async fn main() {
1325    let fixtures_dir_arg = std::env::args().nth(1).unwrap_or_else(|| "../../fixtures".to_string());
1326    let fixtures_dir = Path::new(&fixtures_dir_arg);
1327
1328    let routes = load_routes(fixtures_dir);
1329    eprintln!("mock-server: loaded {} routes from {}", routes.len(), fixtures_dir.display());
1330
1331    let route_table: RouteTable = Arc::new(routes);
1332    let app = Router::new().fallback(handle_request).with_state(route_table);
1333
1334    let listener = TcpListener::bind("127.0.0.1:0")
1335        .await
1336        .expect("mock-server: failed to bind port");
1337    let addr: SocketAddr = listener.local_addr().expect("mock-server: failed to get local addr");
1338
1339    // Print the URL so the parent process can read it.
1340    println!("MOCK_SERVER_URL=http://{addr}");
1341    // Flush stdout explicitly so the parent does not block waiting.
1342    use std::io::Write;
1343    std::io::stdout().flush().expect("mock-server: failed to flush stdout");
1344
1345    // Spawn the server in the background.
1346    tokio::spawn(async move {
1347        axum::serve(listener, app).await.expect("mock-server: server error");
1348    });
1349
1350    // Block until stdin is closed — the parent process controls lifetime.
1351    let stdin = io::stdin();
1352    let mut lines = stdin.lock().lines();
1353    while lines.next().is_some() {}
1354}
1355"#
1356}
1357
1358// ---------------------------------------------------------------------------
1359// Assertion rendering
1360// ---------------------------------------------------------------------------
1361
1362#[allow(clippy::too_many_arguments)]
1363fn render_assertion(
1364    out: &mut String,
1365    assertion: &Assertion,
1366    result_var: &str,
1367    module: &str,
1368    dep_name: &str,
1369    is_error_context: bool,
1370    unwrapped_fields: &[(String, String)], // (fixture_field, local_var)
1371    field_resolver: &FieldResolver,
1372    result_is_tree: bool,
1373    result_is_simple: bool,
1374    result_is_vec: bool,
1375    result_is_option: bool,
1376) {
1377    // Vec<T> result: iterate per-element so each assertion checks every element.
1378    // Field-path assertions become `for r in &{result} { <assert using r> }`.
1379    // Length-style assertions on the Vec itself (no field path) operate on the
1380    // Vec directly.
1381    let has_field = assertion.field.as_ref().is_some_and(|f| !f.is_empty());
1382    if result_is_vec && has_field && !is_error_context {
1383        let _ = writeln!(out, "    for r in &{result_var} {{");
1384        render_assertion(
1385            out,
1386            assertion,
1387            "r",
1388            module,
1389            dep_name,
1390            is_error_context,
1391            unwrapped_fields,
1392            field_resolver,
1393            result_is_tree,
1394            result_is_simple,
1395            false, // already inside loop
1396            result_is_option,
1397        );
1398        let _ = writeln!(out, "    }}");
1399        return;
1400    }
1401    // Option<T> result: map `is_empty`/`not_empty` to `is_none()`/`is_some()`,
1402    // and unwrap the inner value before any other assertion runs.
1403    if result_is_option && !is_error_context {
1404        let assertion_type = assertion.assertion_type.as_str();
1405        if !has_field && (assertion_type == "is_empty" || assertion_type == "not_empty") {
1406            let check = if assertion_type == "is_empty" {
1407                "is_none"
1408            } else {
1409                "is_some"
1410            };
1411            let _ = writeln!(
1412                out,
1413                "    assert!({result_var}.{check}(), \"expected Option to be {check}\");"
1414            );
1415            return;
1416        }
1417        // For any other assertion shape, unwrap the Option and recurse with a
1418        // bare reference variable so the rest of the renderer treats the inner
1419        // value as the result.
1420        let _ = writeln!(
1421            out,
1422            "    let r = {result_var}.as_ref().expect(\"Option<T> should be Some\");"
1423        );
1424        render_assertion(
1425            out,
1426            assertion,
1427            "r",
1428            module,
1429            dep_name,
1430            is_error_context,
1431            unwrapped_fields,
1432            field_resolver,
1433            result_is_tree,
1434            result_is_simple,
1435            result_is_vec,
1436            false, // already unwrapped
1437        );
1438        return;
1439    }
1440    let _ = dep_name;
1441    // Handle synthetic fields like chunks_have_content (derived assertions)
1442    if let Some(f) = &assertion.field {
1443        if f == "chunks_have_content" {
1444            match assertion.assertion_type.as_str() {
1445                "is_true" => {
1446                    let _ = writeln!(
1447                        out,
1448                        "    assert!({result_var}.chunks.as_ref().is_some_and(|chunks| !chunks.is_empty() && chunks.iter().all(|c| !c.content.is_empty())), \"expected all chunks to have content\");"
1449                    );
1450                }
1451                "is_false" => {
1452                    let _ = writeln!(
1453                        out,
1454                        "    assert!({result_var}.chunks.as_ref().is_none() || {result_var}.chunks.as_ref().unwrap().iter().any(|c| c.content.is_empty()), \"expected some chunks to be empty\");"
1455                    );
1456                }
1457                _ => {
1458                    let _ = writeln!(
1459                        out,
1460                        "    // unsupported assertion type on synthetic field chunks_have_content"
1461                    );
1462                }
1463            }
1464            return;
1465        }
1466    }
1467
1468    // Skip assertions on fields that don't exist on the result type.
1469    if let Some(f) = &assertion.field {
1470        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1471            let _ = writeln!(out, "    // skipped: field '{f}' not available on result type");
1472            return;
1473        }
1474    }
1475
1476    // Determine field access expression:
1477    // 1. If the field was unwrapped to a local var, use that local var name.
1478    // 2. When result_is_simple, the function returns a plain type (String etc.) — use result_var.
1479    // 3. When the result is a Tree, map pseudo-field names to correct Rust expressions.
1480    // 4. Otherwise, use the field resolver to generate the accessor.
1481    let field_access = match &assertion.field {
1482        Some(f) if !f.is_empty() => {
1483            if let Some((_, local_var)) = unwrapped_fields.iter().find(|(ff, _)| ff == f) {
1484                local_var.clone()
1485            } else if result_is_simple {
1486                // Plain return type (String, Vec<T>, etc.) has no struct fields.
1487                // Use the result variable directly so assertions operate on the value itself.
1488                result_var.to_string()
1489            } else if result_is_tree {
1490                // Tree is an opaque type — its "fields" are accessed via root_node() or
1491                // free functions. Map known pseudo-field names to correct Rust expressions.
1492                tree_field_access_expr(f, result_var, module)
1493            } else {
1494                field_resolver.accessor(f, "rust", result_var)
1495            }
1496        }
1497        _ => result_var.to_string(),
1498    };
1499
1500    // Check if this field was unwrapped (i.e., it is optional and was bound to a local).
1501    let is_unwrapped = assertion
1502        .field
1503        .as_ref()
1504        .is_some_and(|f| unwrapped_fields.iter().any(|(ff, _)| ff == f));
1505
1506    match assertion.assertion_type.as_str() {
1507        "error" => {
1508            let _ = writeln!(out, "    assert!({result_var}.is_err(), \"expected call to fail\");");
1509            if let Some(serde_json::Value::String(msg)) = &assertion.value {
1510                let escaped = escape_rust(msg);
1511                let _ = writeln!(
1512                    out,
1513                    "    assert!({result_var}.as_ref().unwrap_err().to_string().contains(\"{escaped}\"), \"error message mismatch\");"
1514                );
1515            }
1516        }
1517        "not_error" => {
1518            // Handled at call site; nothing extra needed here.
1519        }
1520        "equals" => {
1521            if let Some(val) = &assertion.value {
1522                let expected = value_to_rust_string(val);
1523                if is_error_context {
1524                    return;
1525                }
1526                // For string equality, trim trailing whitespace to handle trailing newlines
1527                // from the converter.
1528                if val.is_string() {
1529                    let _ = writeln!(
1530                        out,
1531                        "    assert_eq!({field_access}.trim(), {expected}, \"equals assertion failed\");"
1532                    );
1533                } else if val.is_boolean() {
1534                    // Use assert!/assert!(!...) for booleans — clippy prefers this over assert_eq!(_, true/false).
1535                    if val.as_bool() == Some(true) {
1536                        let _ = writeln!(out, "    assert!({field_access}, \"equals assertion failed\");");
1537                    } else {
1538                        let _ = writeln!(out, "    assert!(!{field_access}, \"equals assertion failed\");");
1539                    }
1540                } else {
1541                    // Wrap expected value in Some() for optional fields.
1542                    let is_opt = assertion.field.as_ref().is_some_and(|f| {
1543                        let resolved = field_resolver.resolve(f);
1544                        field_resolver.is_optional(resolved)
1545                    });
1546                    if is_opt
1547                        && !unwrapped_fields
1548                            .iter()
1549                            .any(|(ff, _)| assertion.field.as_ref() == Some(ff))
1550                    {
1551                        let _ = writeln!(
1552                            out,
1553                            "    assert_eq!({field_access}, Some({expected}), \"equals assertion failed\");"
1554                        );
1555                    } else {
1556                        let _ = writeln!(
1557                            out,
1558                            "    assert_eq!({field_access}, {expected}, \"equals assertion failed\");"
1559                        );
1560                    }
1561                }
1562            }
1563        }
1564        "contains" => {
1565            if let Some(val) = &assertion.value {
1566                let expected = value_to_rust_string(val);
1567                let line = format!(
1568                    "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
1569                );
1570                let _ = writeln!(out, "{line}");
1571            }
1572        }
1573        "contains_all" => {
1574            if let Some(values) = &assertion.values {
1575                for val in values {
1576                    let expected = value_to_rust_string(val);
1577                    let line = format!(
1578                        "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
1579                    );
1580                    let _ = writeln!(out, "{line}");
1581                }
1582            }
1583        }
1584        "not_contains" => {
1585            if let Some(val) = &assertion.value {
1586                let expected = value_to_rust_string(val);
1587                let line = format!(
1588                    "    assert!(!format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected NOT to contain: {{}}\", {expected});"
1589                );
1590                let _ = writeln!(out, "{line}");
1591            }
1592        }
1593        "not_empty" => {
1594            if let Some(f) = &assertion.field {
1595                let resolved = field_resolver.resolve(f);
1596                if !is_unwrapped && field_resolver.is_optional(resolved) {
1597                    // Non-string optional field (e.g., Option<Struct>): use is_some()
1598                    let accessor = field_resolver.accessor(f, "rust", result_var);
1599                    let _ = writeln!(
1600                        out,
1601                        "    assert!({accessor}.is_some(), \"expected {f} to be present\");"
1602                    );
1603                } else {
1604                    let _ = writeln!(
1605                        out,
1606                        "    assert!(!{field_access}.is_empty(), \"expected non-empty value\");"
1607                    );
1608                }
1609            } else {
1610                // No field: assertion on the result itself. Use is_some() for Option types.
1611                let _ = writeln!(
1612                    out,
1613                    "    assert!({field_access}.is_some(), \"expected non-empty value\");"
1614                );
1615            }
1616        }
1617        "is_empty" => {
1618            if let Some(f) = &assertion.field {
1619                let resolved = field_resolver.resolve(f);
1620                if !is_unwrapped && field_resolver.is_optional(resolved) {
1621                    let accessor = field_resolver.accessor(f, "rust", result_var);
1622                    let _ = writeln!(out, "    assert!({accessor}.is_none(), \"expected {f} to be absent\");");
1623                } else {
1624                    let _ = writeln!(out, "    assert!({field_access}.is_empty(), \"expected empty value\");");
1625                }
1626            } else {
1627                // No field: assertion on the result itself. Use is_none() for Option types.
1628                let _ = writeln!(out, "    assert!({field_access}.is_none(), \"expected empty value\");");
1629            }
1630        }
1631        "contains_any" => {
1632            if let Some(values) = &assertion.values {
1633                let checks: Vec<String> = values
1634                    .iter()
1635                    .map(|v| {
1636                        let expected = value_to_rust_string(v);
1637                        format!("{field_access}.contains({expected})")
1638                    })
1639                    .collect();
1640                let joined = checks.join(" || ");
1641                let _ = writeln!(
1642                    out,
1643                    "    assert!({joined}, \"expected to contain at least one of the specified values\");"
1644                );
1645            }
1646        }
1647        "greater_than" => {
1648            if let Some(val) = &assertion.value {
1649                // Skip comparisons with negative values against unsigned types (.len() etc.)
1650                if val.as_f64().is_some_and(|n| n < 0.0) {
1651                    let _ = writeln!(
1652                        out,
1653                        "    // skipped: greater_than with negative value is always true for unsigned types"
1654                    );
1655                } else if val.as_u64() == Some(0) {
1656                    // Clippy prefers !is_empty() over len() > 0
1657                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1658                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected > 0\");");
1659                } else {
1660                    let lit = numeric_literal(val);
1661                    let _ = writeln!(out, "    assert!({field_access} > {lit}, \"expected > {lit}\");");
1662                }
1663            }
1664        }
1665        "less_than" => {
1666            if let Some(val) = &assertion.value {
1667                let lit = numeric_literal(val);
1668                let _ = writeln!(out, "    assert!({field_access} < {lit}, \"expected < {lit}\");");
1669            }
1670        }
1671        "greater_than_or_equal" => {
1672            if let Some(val) = &assertion.value {
1673                let lit = numeric_literal(val);
1674                if val.as_u64() == Some(1) && field_access.ends_with(".len()") {
1675                    // Clippy prefers !is_empty() over len() >= 1 for collections.
1676                    // Only apply when the expression is already a `.len()` call so we
1677                    // don't mistakenly call `.is_empty()` on numeric (usize) fields.
1678                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1679                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= 1\");");
1680                } else {
1681                    let _ = writeln!(out, "    assert!({field_access} >= {lit}, \"expected >= {lit}\");");
1682                }
1683            }
1684        }
1685        "less_than_or_equal" => {
1686            if let Some(val) = &assertion.value {
1687                let lit = numeric_literal(val);
1688                let _ = writeln!(out, "    assert!({field_access} <= {lit}, \"expected <= {lit}\");");
1689            }
1690        }
1691        "starts_with" => {
1692            if let Some(val) = &assertion.value {
1693                let expected = value_to_rust_string(val);
1694                let _ = writeln!(
1695                    out,
1696                    "    assert!({field_access}.starts_with({expected}), \"expected to start with: {{}}\", {expected});"
1697                );
1698            }
1699        }
1700        "ends_with" => {
1701            if let Some(val) = &assertion.value {
1702                let expected = value_to_rust_string(val);
1703                let _ = writeln!(
1704                    out,
1705                    "    assert!({field_access}.ends_with({expected}), \"expected to end with: {{}}\", {expected});"
1706                );
1707            }
1708        }
1709        "min_length" => {
1710            if let Some(val) = &assertion.value {
1711                if let Some(n) = val.as_u64() {
1712                    let _ = writeln!(
1713                        out,
1714                        "    assert!({field_access}.len() >= {n}, \"expected length >= {n}, got {{}}\", {field_access}.len());"
1715                    );
1716                }
1717            }
1718        }
1719        "max_length" => {
1720            if let Some(val) = &assertion.value {
1721                if let Some(n) = val.as_u64() {
1722                    let _ = writeln!(
1723                        out,
1724                        "    assert!({field_access}.len() <= {n}, \"expected length <= {n}, got {{}}\", {field_access}.len());"
1725                    );
1726                }
1727            }
1728        }
1729        "count_min" => {
1730            if let Some(val) = &assertion.value {
1731                if let Some(n) = val.as_u64() {
1732                    if n <= 1 {
1733                        // Clippy prefers !is_empty() over len() >= 1
1734                        let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1735                        let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= {n}\");");
1736                    } else {
1737                        let _ = writeln!(
1738                            out,
1739                            "    assert!({field_access}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {field_access}.len());"
1740                        );
1741                    }
1742                }
1743            }
1744        }
1745        "count_equals" => {
1746            if let Some(val) = &assertion.value {
1747                if let Some(n) = val.as_u64() {
1748                    let _ = writeln!(
1749                        out,
1750                        "    assert_eq!({field_access}.len(), {n}, \"expected exactly {n} elements, got {{}}\", {field_access}.len());"
1751                    );
1752                }
1753            }
1754        }
1755        "is_true" => {
1756            let _ = writeln!(out, "    assert!({field_access}, \"expected true\");");
1757        }
1758        "is_false" => {
1759            let _ = writeln!(out, "    assert!(!{field_access}, \"expected false\");");
1760        }
1761        "method_result" => {
1762            if let Some(method_name) = &assertion.method {
1763                // Build the call expression. When the result is a tree-sitter Tree (an opaque
1764                // type), methods like `root_child_count` do not exist on `Tree` directly —
1765                // they are free functions in the crate or are accessed via `root_node()`.
1766                let call_expr = if result_is_tree {
1767                    build_tree_call_expr(field_access.as_str(), method_name, assertion.args.as_ref(), module)
1768                } else if let Some(args) = &assertion.args {
1769                    let arg_lit = json_to_rust_literal(args, "");
1770                    format!("{field_access}.{method_name}({arg_lit})")
1771                } else {
1772                    format!("{field_access}.{method_name}()")
1773                };
1774
1775                // Determine whether the call expression returns a numeric type so we can
1776                // choose the right comparison strategy for `greater_than_or_equal`.
1777                let returns_numeric = result_is_tree && is_tree_numeric_method(method_name);
1778
1779                let check = assertion.check.as_deref().unwrap_or("is_true");
1780                match check {
1781                    "equals" => {
1782                        if let Some(val) = &assertion.value {
1783                            if val.is_boolean() {
1784                                if val.as_bool() == Some(true) {
1785                                    let _ = writeln!(
1786                                        out,
1787                                        "    assert!({call_expr}, \"method_result equals assertion failed\");"
1788                                    );
1789                                } else {
1790                                    let _ = writeln!(
1791                                        out,
1792                                        "    assert!(!{call_expr}, \"method_result equals assertion failed\");"
1793                                    );
1794                                }
1795                            } else {
1796                                let expected = value_to_rust_string(val);
1797                                let _ = writeln!(
1798                                    out,
1799                                    "    assert_eq!({call_expr}, {expected}, \"method_result equals assertion failed\");"
1800                                );
1801                            }
1802                        }
1803                    }
1804                    "is_true" => {
1805                        let _ = writeln!(
1806                            out,
1807                            "    assert!({call_expr}, \"method_result is_true assertion failed\");"
1808                        );
1809                    }
1810                    "is_false" => {
1811                        let _ = writeln!(
1812                            out,
1813                            "    assert!(!{call_expr}, \"method_result is_false assertion failed\");"
1814                        );
1815                    }
1816                    "greater_than_or_equal" => {
1817                        if let Some(val) = &assertion.value {
1818                            let lit = numeric_literal(val);
1819                            if returns_numeric {
1820                                // Numeric return (e.g., child_count()) — always use >= comparison.
1821                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
1822                            } else if val.as_u64() == Some(1) {
1823                                // Clippy prefers !is_empty() over len() >= 1 for collections.
1824                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= 1\");");
1825                            } else {
1826                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
1827                            }
1828                        }
1829                    }
1830                    "count_min" => {
1831                        if let Some(val) = &assertion.value {
1832                            let n = val.as_u64().unwrap_or(0);
1833                            if n <= 1 {
1834                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= {n}\");");
1835                            } else {
1836                                let _ = writeln!(
1837                                    out,
1838                                    "    assert!({call_expr}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {call_expr}.len());"
1839                                );
1840                            }
1841                        }
1842                    }
1843                    "is_error" => {
1844                        // For is_error we need the raw Result without .unwrap().
1845                        let raw_call = call_expr.strip_suffix(".unwrap()").unwrap_or(&call_expr);
1846                        let _ = writeln!(
1847                            out,
1848                            "    assert!({raw_call}.is_err(), \"expected method to return error\");"
1849                        );
1850                    }
1851                    "contains" => {
1852                        if let Some(val) = &assertion.value {
1853                            let expected = value_to_rust_string(val);
1854                            let _ = writeln!(
1855                                out,
1856                                "    assert!({call_expr}.contains({expected}), \"expected result to contain {{}}\", {expected});"
1857                            );
1858                        }
1859                    }
1860                    "not_empty" => {
1861                        let _ = writeln!(
1862                            out,
1863                            "    assert!(!{call_expr}.is_empty(), \"expected non-empty result\");"
1864                        );
1865                    }
1866                    "is_empty" => {
1867                        let _ = writeln!(out, "    assert!({call_expr}.is_empty(), \"expected empty result\");");
1868                    }
1869                    other_check => {
1870                        panic!("Rust e2e generator: unsupported method_result check type: {other_check}");
1871                    }
1872                }
1873            } else {
1874                panic!("Rust e2e generator: method_result assertion missing 'method' field");
1875            }
1876        }
1877        other => {
1878            panic!("Rust e2e generator: unsupported assertion type: {other}");
1879        }
1880    }
1881}
1882
1883/// Translate a fixture pseudo-field name on a `tree_sitter::Tree` into the
1884/// correct Rust accessor expression.
1885///
1886/// When an assertion uses `field: "root_child_count"` on a tree result, the
1887/// field resolver would naively emit `tree.root_child_count` — which is invalid
1888/// because `Tree` is an opaque type with no such field.  This function maps the
1889/// pseudo-field to the correct Rust expression instead.
1890fn tree_field_access_expr(field: &str, result_var: &str, module: &str) -> String {
1891    match field {
1892        "root_child_count" => format!("{result_var}.root_node().child_count()"),
1893        "root_node_type" => format!("{result_var}.root_node().kind()"),
1894        "named_children_count" => format!("{result_var}.root_node().named_child_count()"),
1895        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{result_var})"),
1896        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{result_var})"),
1897        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{result_var})"),
1898        // Unknown pseudo-field: fall back to direct field access (will likely fail to compile,
1899        // but gives the developer a useful error pointing to the fixture).
1900        other => format!("{result_var}.{other}"),
1901    }
1902}
1903
1904/// Build a Rust call expression for a logical "method" on a `tree_sitter::Tree`.
1905///
1906/// `Tree` is an opaque type — it does not expose methods like `root_child_count`.
1907/// Instead, these are either free functions in the crate or are accessed via
1908/// `tree.root_node().<method>()`. This function translates the fixture-level
1909/// method name into the correct Rust expression.
1910fn build_tree_call_expr(
1911    field_access: &str,
1912    method_name: &str,
1913    args: Option<&serde_json::Value>,
1914    module: &str,
1915) -> String {
1916    match method_name {
1917        "root_child_count" => format!("{field_access}.root_node().child_count()"),
1918        "root_node_type" => format!("{field_access}.root_node().kind()"),
1919        "named_children_count" => format!("{field_access}.root_node().named_child_count()"),
1920        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{field_access})"),
1921        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{field_access})"),
1922        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{field_access})"),
1923        "contains_node_type" => {
1924            let node_type = args
1925                .and_then(|a| a.get("node_type"))
1926                .and_then(|v| v.as_str())
1927                .unwrap_or("");
1928            format!("{module}::tree_contains_node_type(&{field_access}, \"{node_type}\")")
1929        }
1930        "find_nodes_by_type" => {
1931            let node_type = args
1932                .and_then(|a| a.get("node_type"))
1933                .and_then(|v| v.as_str())
1934                .unwrap_or("");
1935            format!("{module}::find_nodes_by_type(&{field_access}, \"{node_type}\")")
1936        }
1937        "run_query" => {
1938            let query_source = args
1939                .and_then(|a| a.get("query_source"))
1940                .and_then(|v| v.as_str())
1941                .unwrap_or("");
1942            let language = args
1943                .and_then(|a| a.get("language"))
1944                .and_then(|v| v.as_str())
1945                .unwrap_or("");
1946            // Use a raw string for the query to avoid escaping issues.
1947            // run_query returns Result — unwrap it for assertion access.
1948            format!(
1949                "{module}::run_query(&{field_access}, \"{language}\", r#\"{query_source}\"#, source.as_bytes()).unwrap()"
1950            )
1951        }
1952        // Fallback: try as a plain method call.
1953        _ => {
1954            if let Some(args) = args {
1955                let arg_lit = json_to_rust_literal(args, "");
1956                format!("{field_access}.{method_name}({arg_lit})")
1957            } else {
1958                format!("{field_access}.{method_name}()")
1959            }
1960        }
1961    }
1962}
1963
1964/// Returns `true` when the tree method name produces a numeric result (usize/u64),
1965/// meaning `>= N` comparisons should use direct numeric comparison rather than
1966/// `.is_empty()` (which only works for collections).
1967fn is_tree_numeric_method(method_name: &str) -> bool {
1968    matches!(
1969        method_name,
1970        "root_child_count" | "named_children_count" | "error_count" | "tree_error_count"
1971    )
1972}
1973
1974/// Convert a JSON numeric value to a Rust literal suitable for comparisons.
1975///
1976/// Whole numbers (no fractional part) are emitted as bare integer literals so
1977/// they are compatible with `usize`, `u64`, etc. (e.g., `.len()` results).
1978/// Numbers with a fractional component get the `_f64` suffix.
1979fn numeric_literal(value: &serde_json::Value) -> String {
1980    if let Some(n) = value.as_f64() {
1981        if n.fract() == 0.0 {
1982            // Whole number — emit without a type suffix so Rust can infer the
1983            // correct integer type from context (usize, u64, i64, …).
1984            return format!("{}", n as i64);
1985        }
1986        return format!("{n}_f64");
1987    }
1988    // Fallback: use the raw JSON representation.
1989    value.to_string()
1990}
1991
1992fn value_to_rust_string(value: &serde_json::Value) -> String {
1993    match value {
1994        serde_json::Value::String(s) => rust_raw_string(s),
1995        serde_json::Value::Bool(b) => format!("{b}"),
1996        serde_json::Value::Number(n) => n.to_string(),
1997        other => {
1998            let s = other.to_string();
1999            format!("\"{s}\"")
2000        }
2001    }
2002}
2003
2004// ---------------------------------------------------------------------------
2005// Visitor generation
2006// ---------------------------------------------------------------------------
2007
2008/// Resolve the visitor trait name based on module.
2009fn resolve_visitor_trait(module: &str) -> String {
2010    // For html_to_markdown modules, use HtmlVisitor
2011    if module.contains("html_to_markdown") {
2012        "HtmlVisitor".to_string()
2013    } else {
2014        // Default fallback for other modules
2015        "Visitor".to_string()
2016    }
2017}
2018
2019/// Emit a Rust visitor method for a callback action.
2020///
2021/// The parameter type list mirrors the `HtmlVisitor` trait in
2022/// `kreuzberg-dev/html-to-markdown`. Param names are bound to `_` because the
2023/// generated visitor body never references them — the body always returns a
2024/// fixed `VisitResult` variant — so we'd otherwise hit `unused_variables`
2025/// warnings that fail prek's `cargo clippy -D warnings` hook.
2026fn emit_rust_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
2027    // Each entry: parameters typed exactly as `HtmlVisitor` expects them,
2028    // bound to `_` patterns so the generated body needn't introduce unused
2029    // bindings. Receiver is `&mut self` to match the trait.
2030    let params = match method_name {
2031        "visit_link" => "_: &NodeContext, _: &str, _: &str, _: &str",
2032        "visit_image" => "_: &NodeContext, _: &str, _: &str, _: &str",
2033        "visit_heading" => "_: &NodeContext, _: u8, _: &str, _: Option<&str>",
2034        "visit_code_block" => "_: &NodeContext, _: Option<&str>, _: &str",
2035        "visit_code_inline"
2036        | "visit_strong"
2037        | "visit_emphasis"
2038        | "visit_strikethrough"
2039        | "visit_underline"
2040        | "visit_subscript"
2041        | "visit_superscript"
2042        | "visit_mark"
2043        | "visit_button"
2044        | "visit_summary"
2045        | "visit_figcaption"
2046        | "visit_definition_term"
2047        | "visit_definition_description" => "_: &NodeContext, _: &str",
2048        "visit_text" => "_: &NodeContext, _: &str",
2049        "visit_list_item" => "_: &NodeContext, _: bool, _: &str, _: &str",
2050        "visit_blockquote" => "_: &NodeContext, _: &str, _: u32",
2051        "visit_table_row" => "_: &NodeContext, _: &[String], _: bool",
2052        "visit_custom_element" => "_: &NodeContext, _: &str, _: &str",
2053        "visit_form" => "_: &NodeContext, _: &str, _: &str",
2054        "visit_input" => "_: &NodeContext, _: &str, _: &str, _: &str",
2055        "visit_audio" | "visit_video" | "visit_iframe" => "_: &NodeContext, _: &str",
2056        "visit_details" => "_: &NodeContext, _: bool",
2057        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2058            "_: &NodeContext, _: &str"
2059        }
2060        "visit_list_start" => "_: &NodeContext, _: bool",
2061        "visit_list_end" => "_: &NodeContext, _: bool, _: &str",
2062        _ => "_: &NodeContext",
2063    };
2064
2065    let _ = writeln!(out, "        fn {method_name}(&mut self, {params}) -> VisitResult {{");
2066    match action {
2067        CallbackAction::Skip => {
2068            let _ = writeln!(out, "            VisitResult::Skip");
2069        }
2070        CallbackAction::Continue => {
2071            let _ = writeln!(out, "            VisitResult::Continue");
2072        }
2073        CallbackAction::PreserveHtml => {
2074            let _ = writeln!(out, "            VisitResult::PreserveHtml");
2075        }
2076        CallbackAction::Custom { output } => {
2077            let escaped = escape_rust(output);
2078            let _ = writeln!(out, "            VisitResult::Custom(\"{escaped}\".to_string())");
2079        }
2080        CallbackAction::CustomTemplate { template } => {
2081            let escaped = escape_rust(template);
2082            let _ = writeln!(out, "            VisitResult::Custom(format!(\"{escaped}\"))");
2083        }
2084    }
2085    let _ = writeln!(out, "        }}");
2086}