Skip to main content

alef_e2e/codegen/
java.rs

1//! Java e2e test generator using JUnit 5.
2//!
3//! Generates `e2e/java/pom.xml` and `src/test/java/dev/kreuzberg/e2e/{Category}Test.java`
4//! files from JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::config::E2eConfig;
7use crate::escape::{escape_java, sanitize_filename};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::ResolvedCrateConfig;
12use alef_core::hash::{self, CommentStyle};
13use alef_core::template_versions as tv;
14use anyhow::Result;
15use heck::{ToLowerCamelCase, ToUpperCamelCase};
16use std::path::PathBuf;
17
18use super::E2eCodegen;
19use super::client;
20
21/// Java e2e code generator.
22pub struct JavaCodegen;
23
24impl E2eCodegen for JavaCodegen {
25    fn generate(
26        &self,
27        groups: &[FixtureGroup],
28        e2e_config: &E2eConfig,
29        config: &ResolvedCrateConfig,
30        _type_defs: &[alef_core::ir::TypeDef],
31    ) -> Result<Vec<GeneratedFile>> {
32        let lang = self.language_name();
33        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
34
35        let mut files = Vec::new();
36
37        // Resolve call config with overrides.
38        let call = &e2e_config.call;
39        let overrides = call.overrides.get(lang);
40        let _module_path = overrides
41            .and_then(|o| o.module.as_ref())
42            .cloned()
43            .unwrap_or_else(|| call.module.clone());
44        let function_name = overrides
45            .and_then(|o| o.function.as_ref())
46            .cloned()
47            .unwrap_or_else(|| call.function.clone());
48        let class_name = overrides
49            .and_then(|o| o.class.as_ref())
50            .cloned()
51            .unwrap_or_else(|| config.name.to_upper_camel_case());
52        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
53        let result_var = &call.result_var;
54
55        // Resolve package config.
56        let java_pkg = e2e_config.resolve_package("java");
57        let pkg_name = java_pkg
58            .as_ref()
59            .and_then(|p| p.name.as_ref())
60            .cloned()
61            .unwrap_or_else(|| config.name.clone());
62
63        // Resolve Java package info for the dependency.
64        let java_group_id = config.java_group_id();
65        let binding_pkg = config.java_package();
66        let pkg_version = config.resolved_version().unwrap_or_else(|| "0.1.0".to_string());
67
68        // Generate pom.xml.
69        files.push(GeneratedFile {
70            path: output_base.join("pom.xml"),
71            content: render_pom_xml(
72                &pkg_name,
73                &java_group_id,
74                &pkg_version,
75                e2e_config.dep_mode,
76                &e2e_config.test_documents_relative_from(0),
77            ),
78            generated_header: false,
79        });
80
81        // Detect whether any fixture needs the mock-server (HTTP fixtures or
82        // fixtures with a `mock_response`). When present, emit a
83        // JUnit Platform LauncherSessionListener that spawns the mock-server
84        // before any test runs and a META-INF/services SPI manifest registering
85        // it. Without this, every fixture-bound test failed with
86        // `LiterLlmRsException: error sending request for url` because
87        // `System.getenv("MOCK_SERVER_URL")` was null.
88        let needs_mock_server = groups
89            .iter()
90            .flat_map(|g| g.fixtures.iter())
91            .any(|f| f.needs_mock_server());
92
93        // Generate test files per category. Path mirrors the configured Java
94        // package — `dev.myorg` becomes `dev/myorg`, etc. — so the package
95        // declaration in each test file matches its filesystem location.
96        let mut test_base = output_base.join("src").join("test").join("java");
97        for segment in java_group_id.split('.') {
98            test_base = test_base.join(segment);
99        }
100        let test_base = test_base.join("e2e");
101
102        if needs_mock_server {
103            files.push(GeneratedFile {
104                path: test_base.join("MockServerListener.java"),
105                content: render_mock_server_listener(&java_group_id),
106                generated_header: true,
107            });
108            files.push(GeneratedFile {
109                path: output_base
110                    .join("src")
111                    .join("test")
112                    .join("resources")
113                    .join("META-INF")
114                    .join("services")
115                    .join("org.junit.platform.launcher.LauncherSessionListener"),
116                content: format!("{java_group_id}.e2e.MockServerListener\n"),
117                generated_header: false,
118            });
119        }
120
121        // Resolve options_type from override.
122        let options_type = overrides.and_then(|o| o.options_type.clone());
123
124        // Resolve enum_fields and nested_types from Java override config.
125        static EMPTY_ENUM_FIELDS: std::sync::LazyLock<std::collections::HashMap<String, String>> =
126            std::sync::LazyLock::new(std::collections::HashMap::new);
127        let _enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);
128
129        // Build effective nested_types by merging defaults with configured overrides.
130        let mut effective_nested_types = default_java_nested_types();
131        if let Some(overrides_map) = overrides.map(|o| &o.nested_types) {
132            effective_nested_types.extend(overrides_map.clone());
133        }
134
135        // Resolve nested_types_optional from override (defaults to true for backward compatibility).
136        let nested_types_optional = overrides.map(|o| o.nested_types_optional).unwrap_or(true);
137
138        let field_resolver = FieldResolver::new(
139            &e2e_config.fields,
140            &e2e_config.fields_optional,
141            &e2e_config.result_fields,
142            &e2e_config.fields_array,
143            &std::collections::HashSet::new(),
144        );
145
146        for group in groups {
147            let active: Vec<&Fixture> = group
148                .fixtures
149                .iter()
150                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
151                .collect();
152
153            if active.is_empty() {
154                continue;
155            }
156
157            let class_file_name = format!("{}Test.java", sanitize_filename(&group.category).to_upper_camel_case());
158            let content = render_test_file(
159                &group.category,
160                &active,
161                &class_name,
162                &function_name,
163                &java_group_id,
164                &binding_pkg,
165                result_var,
166                &e2e_config.call.args,
167                options_type.as_deref(),
168                &field_resolver,
169                result_is_simple,
170                &e2e_config.fields_enum,
171                e2e_config,
172                &effective_nested_types,
173                nested_types_optional,
174            );
175            files.push(GeneratedFile {
176                path: test_base.join(class_file_name),
177                content,
178                generated_header: true,
179            });
180        }
181
182        Ok(files)
183    }
184
185    fn language_name(&self) -> &'static str {
186        "java"
187    }
188}
189
190// ---------------------------------------------------------------------------
191// Rendering
192// ---------------------------------------------------------------------------
193
194fn render_pom_xml(
195    pkg_name: &str,
196    java_group_id: &str,
197    pkg_version: &str,
198    dep_mode: crate::config::DependencyMode,
199    test_documents_path: &str,
200) -> String {
201    // pkg_name may be in "groupId:artifactId" Maven format; split accordingly.
202    let (dep_group_id, dep_artifact_id) = if let Some((g, a)) = pkg_name.split_once(':') {
203        (g, a)
204    } else {
205        (java_group_id, pkg_name)
206    };
207    let artifact_id = format!("{dep_artifact_id}-e2e-java");
208    let dep_block = match dep_mode {
209        crate::config::DependencyMode::Registry => {
210            format!(
211                r#"        <dependency>
212            <groupId>{dep_group_id}</groupId>
213            <artifactId>{dep_artifact_id}</artifactId>
214            <version>{pkg_version}</version>
215        </dependency>"#
216            )
217        }
218        crate::config::DependencyMode::Local => {
219            format!(
220                r#"        <dependency>
221            <groupId>{dep_group_id}</groupId>
222            <artifactId>{dep_artifact_id}</artifactId>
223            <version>{pkg_version}</version>
224            <scope>system</scope>
225            <systemPath>${{project.basedir}}/../../packages/java/target/{dep_artifact_id}-{pkg_version}.jar</systemPath>
226        </dependency>"#
227            )
228        }
229    };
230    crate::template_env::render(
231        "java/pom.xml.jinja",
232        minijinja::context! {
233            artifact_id => artifact_id,
234            java_group_id => java_group_id,
235            dep_block => dep_block,
236            junit_version => tv::maven::JUNIT,
237            jackson_version => tv::maven::JACKSON_E2E,
238            build_helper_version => tv::maven::BUILD_HELPER_MAVEN_PLUGIN,
239            maven_surefire_version => tv::maven::MAVEN_SUREFIRE_PLUGIN_E2E,
240            test_documents_path => test_documents_path,
241        },
242    )
243}
244
245/// Render the JUnit Platform LauncherSessionListener that spawns the
246/// mock-server binary once per launcher session and tears it down on close.
247///
248/// Mirrors the Ruby `spec_helper.rb` and Python `conftest.py` patterns. The
249/// URL is exposed as a JVM system property `mockServerUrl`; generated test
250/// bodies prefer it over the `MOCK_SERVER_URL` env var so external overrides
251/// (e.g. CI exporting MOCK_SERVER_URL) still work without rerouting through
252/// JNI's lack of `setenv`.
253fn render_mock_server_listener(java_group_id: &str) -> String {
254    let header = hash::header(CommentStyle::DoubleSlash);
255    let mut out = header;
256    out.push_str(&format!("package {java_group_id}.e2e;\n\n"));
257    out.push_str("import java.io.BufferedReader;\n");
258    out.push_str("import java.io.File;\n");
259    out.push_str("import java.io.IOException;\n");
260    out.push_str("import java.io.InputStreamReader;\n");
261    out.push_str("import java.nio.charset.StandardCharsets;\n");
262    out.push_str("import java.nio.file.Path;\n");
263    out.push_str("import java.nio.file.Paths;\n");
264    out.push_str("import java.util.regex.Matcher;\n");
265    out.push_str("import java.util.regex.Pattern;\n");
266    out.push_str("import org.junit.platform.launcher.LauncherSession;\n");
267    out.push_str("import org.junit.platform.launcher.LauncherSessionListener;\n");
268    out.push('\n');
269    out.push_str("/**\n");
270    out.push_str(" * Spawns the mock-server binary once per JUnit launcher session and\n");
271    out.push_str(" * exposes its URL as the `mockServerUrl` system property. Generated\n");
272    out.push_str(" * test bodies read the property (with `MOCK_SERVER_URL` env-var\n");
273    out.push_str(" * fallback) so tests can run via plain `mvn test` without any external\n");
274    out.push_str(" * mock-server orchestration. Mirrors the Ruby spec_helper / Python\n");
275    out.push_str(" * conftest spawn pattern. Honors a pre-set MOCK_SERVER_URL by\n");
276    out.push_str(" * skipping the spawn entirely.\n");
277    out.push_str(" */\n");
278    out.push_str("public class MockServerListener implements LauncherSessionListener {\n");
279    out.push_str("    private Process mockServer;\n");
280    out.push('\n');
281    out.push_str("    @Override\n");
282    out.push_str("    public void launcherSessionOpened(LauncherSession session) {\n");
283    out.push_str("        String preset = System.getenv(\"MOCK_SERVER_URL\");\n");
284    out.push_str("        if (preset != null && !preset.isEmpty()) {\n");
285    out.push_str("            System.setProperty(\"mockServerUrl\", preset);\n");
286    out.push_str("            return;\n");
287    out.push_str("        }\n");
288    out.push_str("        Path repoRoot = locateRepoRoot();\n");
289    out.push_str("        if (repoRoot == null) {\n");
290    out.push_str("            throw new IllegalStateException(\"MockServerListener: could not locate repo root (looked for fixtures/ in ancestors of \" + System.getProperty(\"user.dir\") + \")\");\n");
291    out.push_str("        }\n");
292    out.push_str("        String binName = System.getProperty(\"os.name\", \"\").toLowerCase().contains(\"win\") ? \"mock-server.exe\" : \"mock-server\";\n");
293    out.push_str("        File bin = repoRoot.resolve(\"e2e\").resolve(\"rust\").resolve(\"target\").resolve(\"release\").resolve(binName).toFile();\n");
294    out.push_str("        File fixturesDir = repoRoot.resolve(\"fixtures\").toFile();\n");
295    out.push_str("        if (!bin.exists()) {\n");
296    out.push_str("            throw new IllegalStateException(\"MockServerListener: mock-server binary not found at \" + bin + \" — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release\");\n");
297    out.push_str("        }\n");
298    out.push_str(
299        "        ProcessBuilder pb = new ProcessBuilder(bin.getAbsolutePath(), fixturesDir.getAbsolutePath())\n",
300    );
301    out.push_str("            .redirectErrorStream(false);\n");
302    out.push_str("        try {\n");
303    out.push_str("            mockServer = pb.start();\n");
304    out.push_str("        } catch (IOException e) {\n");
305    out.push_str(
306        "            throw new IllegalStateException(\"MockServerListener: failed to start mock-server\", e);\n",
307    );
308    out.push_str("        }\n");
309    out.push_str("        // Read until we see MOCK_SERVER_URL= and optionally MOCK_SERVERS=.\n");
310    out.push_str("        // Cap the loop so a misbehaving mock-server cannot block indefinitely.\n");
311    out.push_str("        BufferedReader stdout = new BufferedReader(new InputStreamReader(mockServer.getInputStream(), StandardCharsets.UTF_8));\n");
312    out.push_str("        String url = null;\n");
313    out.push_str("        try {\n");
314    out.push_str("            for (int i = 0; i < 16; i++) {\n");
315    out.push_str("                String line = stdout.readLine();\n");
316    out.push_str("                if (line == null) break;\n");
317    out.push_str("                if (line.startsWith(\"MOCK_SERVER_URL=\")) {\n");
318    out.push_str("                    url = line.substring(\"MOCK_SERVER_URL=\".length()).trim();\n");
319    out.push_str("                } else if (line.startsWith(\"MOCK_SERVERS=\")) {\n");
320    out.push_str("                    String jsonVal = line.substring(\"MOCK_SERVERS=\".length()).trim();\n");
321    out.push_str("                    System.setProperty(\"mockServers\", jsonVal);\n");
322    out.push_str("                    // Parse JSON map of fixture_id -> url and expose as system properties.\n");
323    out.push_str("                    Pattern p = Pattern.compile(\"\\\"([^\\\"]+)\\\":\\\"([^\\\"]+)\\\"\");\n");
324    out.push_str("                    Matcher matcher = p.matcher(jsonVal);\n");
325    out.push_str("                    while (matcher.find()) {\n");
326    out.push_str("                        String fid = matcher.group(1);\n");
327    out.push_str("                        String furl = matcher.group(2);\n");
328    out.push_str("                        System.setProperty(\"mockServer.\" + fid, furl);\n");
329    out.push_str("                    }\n");
330    out.push_str("                    break;\n");
331    out.push_str("                } else if (url != null) {\n");
332    out.push_str("                    break;\n");
333    out.push_str("                }\n");
334    out.push_str("            }\n");
335    out.push_str("        } catch (IOException e) {\n");
336    out.push_str("            mockServer.destroyForcibly();\n");
337    out.push_str(
338        "            throw new IllegalStateException(\"MockServerListener: failed to read mock-server stdout\", e);\n",
339    );
340    out.push_str("        }\n");
341    out.push_str("        if (url == null || url.isEmpty()) {\n");
342    out.push_str("            mockServer.destroyForcibly();\n");
343    out.push_str("            throw new IllegalStateException(\"MockServerListener: mock-server did not emit MOCK_SERVER_URL\");\n");
344    out.push_str("        }\n");
345    out.push_str("        // TCP-readiness probe: ensure axum::serve is accepting before tests start.\n");
346    out.push_str("        // The mock-server binds the TcpListener synchronously then prints the URL\n");
347    out.push_str("        // before tokio::spawn(axum::serve(...)) is polled, so under Surefire\n");
348    out.push_str("        // parallel mode tests can race startup. Poll-connect (max 5s, 50ms backoff)\n");
349    out.push_str("        // until success.\n");
350    out.push_str("        java.net.URI healthUri = java.net.URI.create(url);\n");
351    out.push_str("        String host = healthUri.getHost();\n");
352    out.push_str("        int port = healthUri.getPort();\n");
353    out.push_str("        long deadline = System.nanoTime() + 5_000_000_000L;\n");
354    out.push_str("        while (System.nanoTime() < deadline) {\n");
355    out.push_str("            try (java.net.Socket s = new java.net.Socket()) {\n");
356    out.push_str("                s.connect(new java.net.InetSocketAddress(host, port), 100);\n");
357    out.push_str("                break;\n");
358    out.push_str("            } catch (java.io.IOException ignored) {\n");
359    out.push_str("                try { Thread.sleep(50); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); break; }\n");
360    out.push_str("            }\n");
361    out.push_str("        }\n");
362    out.push_str("        System.setProperty(\"mockServerUrl\", url);\n");
363    out.push_str("        // Drain remaining stdout/stderr in daemon threads so a full pipe\n");
364    out.push_str("        // does not block the child.\n");
365    out.push_str("        Process server = mockServer;\n");
366    out.push_str("        Thread drainOut = new Thread(() -> drain(stdout));\n");
367    out.push_str("        drainOut.setDaemon(true);\n");
368    out.push_str("        drainOut.start();\n");
369    out.push_str("        Thread drainErr = new Thread(() -> drain(new BufferedReader(new InputStreamReader(server.getErrorStream(), StandardCharsets.UTF_8))));\n");
370    out.push_str("        drainErr.setDaemon(true);\n");
371    out.push_str("        drainErr.start();\n");
372    out.push_str("    }\n");
373    out.push('\n');
374    out.push_str("    @Override\n");
375    out.push_str("    public void launcherSessionClosed(LauncherSession session) {\n");
376    out.push_str("        if (mockServer == null) return;\n");
377    out.push_str("        try { mockServer.getOutputStream().close(); } catch (IOException ignored) {}\n");
378    out.push_str("        try {\n");
379    out.push_str("            if (!mockServer.waitFor(2, java.util.concurrent.TimeUnit.SECONDS)) {\n");
380    out.push_str("                mockServer.destroyForcibly();\n");
381    out.push_str("            }\n");
382    out.push_str("        } catch (InterruptedException ignored) {\n");
383    out.push_str("            Thread.currentThread().interrupt();\n");
384    out.push_str("            mockServer.destroyForcibly();\n");
385    out.push_str("        }\n");
386    out.push_str("    }\n");
387    out.push('\n');
388    out.push_str("    private static Path locateRepoRoot() {\n");
389    out.push_str("        Path dir = Paths.get(\"\").toAbsolutePath();\n");
390    out.push_str("        while (dir != null) {\n");
391    out.push_str("            if (dir.resolve(\"fixtures\").toFile().isDirectory()\n");
392    out.push_str("                && dir.resolve(\"e2e\").toFile().isDirectory()) {\n");
393    out.push_str("                return dir;\n");
394    out.push_str("            }\n");
395    out.push_str("            dir = dir.getParent();\n");
396    out.push_str("        }\n");
397    out.push_str("        return null;\n");
398    out.push_str("    }\n");
399    out.push('\n');
400    out.push_str("    private static void drain(BufferedReader reader) {\n");
401    out.push_str("        try {\n");
402    out.push_str("            char[] buf = new char[1024];\n");
403    out.push_str("            while (reader.read(buf) >= 0) { /* drain */ }\n");
404    out.push_str("        } catch (IOException ignored) {}\n");
405    out.push_str("    }\n");
406    out.push_str("}\n");
407    out
408}
409
410#[allow(clippy::too_many_arguments)]
411fn render_test_file(
412    category: &str,
413    fixtures: &[&Fixture],
414    class_name: &str,
415    function_name: &str,
416    java_group_id: &str,
417    binding_pkg: &str,
418    result_var: &str,
419    args: &[crate::config::ArgMapping],
420    options_type: Option<&str>,
421    field_resolver: &FieldResolver,
422    result_is_simple: bool,
423    enum_fields: &std::collections::HashSet<String>,
424    e2e_config: &E2eConfig,
425    nested_types: &std::collections::HashMap<String, String>,
426    nested_types_optional: bool,
427) -> String {
428    let header = hash::header(CommentStyle::DoubleSlash);
429    let test_class_name = format!("{}Test", sanitize_filename(category).to_upper_camel_case());
430
431    // If the class_name is fully qualified (contains '.'), import it and use
432    // only the simple name for method calls.  Otherwise use it as-is.
433    let (import_path, simple_class) = if class_name.contains('.') {
434        let simple = class_name.rsplit('.').next().unwrap_or(class_name);
435        (class_name, simple)
436    } else {
437        ("", class_name)
438    };
439
440    // Check if any fixture (with its resolved call) will emit MAPPER usage.
441    let lang_for_om = "java";
442    let needs_object_mapper_for_handle = fixtures.iter().any(|f| {
443        args.iter().filter(|a| a.arg_type == "handle").any(|a| {
444            let v = f.input.get(&a.field).unwrap_or(&serde_json::Value::Null);
445            !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
446        })
447    });
448    // HTTP fixtures always need ObjectMapper for JSON body comparison.
449    let has_http_fixtures = fixtures.iter().any(|f| f.http.is_some());
450    let needs_object_mapper = needs_object_mapper_for_handle || has_http_fixtures;
451
452    // Collect all options_type values used (class-level + per-fixture call overrides).
453    let mut all_options_types: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
454    if let Some(t) = options_type {
455        all_options_types.insert(t.to_string());
456    }
457    for f in fixtures.iter() {
458        let call_cfg = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
459        if let Some(ov) = call_cfg.overrides.get(lang_for_om) {
460            if let Some(t) = &ov.options_type {
461                all_options_types.insert(t.clone());
462            }
463        }
464        // Auto-fallback: when the Java override does not declare an options_type
465        // but another non-prefixed binding (csharp/c/go/php/python) does, mirror
466        // that name into the import set so the auto-emitted `Type.fromJson(json)`
467        // expression compiles. The Java POJO class name matches the Rust source
468        // type name for these backends.
469        let java_has_type = call_cfg
470            .overrides
471            .get(lang_for_om)
472            .and_then(|o| o.options_type.as_deref())
473            .is_some();
474        if !java_has_type {
475            for cand in ["csharp", "c", "go", "php", "python"] {
476                if let Some(o) = call_cfg.overrides.get(cand) {
477                    if let Some(t) = &o.options_type {
478                        all_options_types.insert(t.clone());
479                        break;
480                    }
481                }
482            }
483        }
484        // Detect batch item types used in this fixture
485        for arg in &call_cfg.args {
486            if let Some(elem_type) = &arg.element_type {
487                if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
488                    all_options_types.insert(elem_type.clone());
489                }
490            }
491        }
492    }
493
494    // Collect nested config types actually referenced in fixture builder expressions.
495    // Note: enum types don't need explicit imports since they're in the same package.
496    let mut nested_types_used: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
497    for f in fixtures.iter() {
498        let call_cfg = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
499        for arg in &call_cfg.args {
500            if arg.arg_type == "json_object" {
501                let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
502                if let Some(val) = f.input.get(field) {
503                    if !val.is_null() && !val.is_array() {
504                        if let Some(obj) = val.as_object() {
505                            collect_nested_type_names(obj, nested_types, &mut nested_types_used);
506                        }
507                    }
508                }
509            }
510        }
511    }
512
513    // Effective binding package for FQN imports of binding types
514    // (ChatCompletionRequest, etc.). Prefer the explicit `[crates.java] package`
515    // wired in via `binding_pkg`; fall back to the package derived from a
516    // fully-qualified `class_name` when present.
517    let binding_pkg_for_imports: String = if !binding_pkg.is_empty() {
518        binding_pkg.to_string()
519    } else if !import_path.is_empty() {
520        import_path
521            .rsplit_once('.')
522            .map(|(p, _)| p.to_string())
523            .unwrap_or_default()
524    } else {
525        String::new()
526    };
527
528    // Build imports list
529    let mut imports: Vec<String> = Vec::new();
530    imports.push("import org.junit.jupiter.api.Test;".to_string());
531    imports.push("import static org.junit.jupiter.api.Assertions.*;".to_string());
532
533    // Import the test entry-point class itself when it is fully-qualified or
534    // when we know the binding package — emit the FQN so javac resolves it.
535    if !import_path.is_empty() {
536        imports.push(format!("import {import_path};"));
537    } else if !binding_pkg_for_imports.is_empty() && !class_name.is_empty() {
538        imports.push(format!("import {binding_pkg_for_imports}.{class_name};"));
539    }
540
541    if needs_object_mapper {
542        imports.push("import com.fasterxml.jackson.databind.ObjectMapper;".to_string());
543        imports.push("import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;".to_string());
544    }
545
546    // Import all options types used across fixtures (for builder expressions and MAPPER).
547    if !all_options_types.is_empty() {
548        for opts_type in &all_options_types {
549            let qualified = if binding_pkg_for_imports.is_empty() {
550                opts_type.clone()
551            } else {
552                format!("{binding_pkg_for_imports}.{opts_type}")
553            };
554            imports.push(format!("import {qualified};"));
555        }
556    }
557
558    // Import nested options types
559    if !nested_types_used.is_empty() && !binding_pkg_for_imports.is_empty() {
560        for type_name in &nested_types_used {
561            imports.push(format!("import {binding_pkg_for_imports}.{type_name};"));
562        }
563    }
564
565    // Import CrawlConfig when handle args need JSON deserialization.
566    if needs_object_mapper_for_handle && !binding_pkg_for_imports.is_empty() {
567        imports.push(format!("import {binding_pkg_for_imports}.CrawlConfig;"));
568    }
569
570    // Import visitor types when any fixture uses visitor callbacks.
571    let has_visitor_fixtures = fixtures.iter().any(|f| f.visitor.is_some());
572    if has_visitor_fixtures && !binding_pkg_for_imports.is_empty() {
573        imports.push(format!("import {binding_pkg_for_imports}.Visitor;"));
574        imports.push(format!("import {binding_pkg_for_imports}.NodeContext;"));
575        imports.push(format!("import {binding_pkg_for_imports}.VisitResult;"));
576    }
577
578    // Import Optional when using builder expressions with optional fields
579    if !all_options_types.is_empty() {
580        imports.push("import java.util.Optional;".to_string());
581    }
582
583    // Import ChatCompletionChunk when any fixture is streaming (uses chat_stream
584    // or references streaming-virtual fields like `chunks`/`stream_content`).
585    // The collect_snippet emits `new ArrayList<ChatCompletionChunk>()` so the
586    // class must be importable for type inference and method resolution.
587    let has_streaming_fixture = fixtures.iter().any(|f| {
588        f.is_streaming_mock()
589            || f.assertions.iter().any(|a| {
590                a.field.as_deref().is_some_and(|fld| {
591                    !fld.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(fld)
592                })
593            })
594    });
595    if has_streaming_fixture && !binding_pkg_for_imports.is_empty() {
596        imports.push(format!("import {binding_pkg_for_imports}.ChatCompletionChunk;"));
597    }
598
599    // Render all test methods
600    let mut fixtures_body = String::new();
601    for (i, fixture) in fixtures.iter().enumerate() {
602        render_test_method(
603            &mut fixtures_body,
604            fixture,
605            simple_class,
606            function_name,
607            result_var,
608            args,
609            options_type,
610            field_resolver,
611            result_is_simple,
612            enum_fields,
613            e2e_config,
614            nested_types,
615            nested_types_optional,
616        );
617        if i + 1 < fixtures.len() {
618            fixtures_body.push('\n');
619        }
620    }
621
622    // Render template
623    crate::template_env::render(
624        "java/test_file.jinja",
625        minijinja::context! {
626            header => header,
627            java_group_id => java_group_id,
628            test_class_name => test_class_name,
629            category => category,
630            imports => imports,
631            needs_object_mapper => needs_object_mapper,
632            fixtures_body => fixtures_body,
633        },
634    )
635}
636
637// ---------------------------------------------------------------------------
638// HTTP test rendering — shared-driver integration
639// ---------------------------------------------------------------------------
640
641/// Thin renderer that emits JUnit 5 test methods targeting a mock server via
642/// `java.net.http.HttpClient`. Satisfies [`client::TestClientRenderer`] so the
643/// shared [`client::http_call::render_http_test`] driver drives the call sequence.
644struct JavaTestClientRenderer;
645
646impl client::TestClientRenderer for JavaTestClientRenderer {
647    fn language_name(&self) -> &'static str {
648        "java"
649    }
650
651    /// Convert a fixture id to the UpperCamelCase suffix appended to `test`.
652    ///
653    /// The emitted method name is `test{fn_name}`, matching the pre-existing shape.
654    fn sanitize_test_name(&self, id: &str) -> String {
655        id.to_upper_camel_case()
656    }
657
658    /// Emit `@Test void test{fn_name}() throws Exception {`.
659    ///
660    /// When `skip_reason` is `Some`, the body is a single
661    /// `Assumptions.assumeTrue(false, ...)` call and `render_test_close` closes
662    /// the brace symmetrically.
663    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
664        let escaped_reason = skip_reason.map(escape_java);
665        let rendered = crate::template_env::render(
666            "java/http_test_open.jinja",
667            minijinja::context! {
668                fn_name => fn_name,
669                description => description,
670                skip_reason => escaped_reason,
671            },
672        );
673        out.push_str(&rendered);
674    }
675
676    /// Emit the closing `}` for a test method.
677    fn render_test_close(&self, out: &mut String) {
678        let rendered = crate::template_env::render("java/http_test_close.jinja", minijinja::context! {});
679        out.push_str(&rendered);
680    }
681
682    /// Emit a `java.net.http.HttpClient` request to `baseUrl + path`.
683    ///
684    /// Binds the response to `response` (the `ctx.response_var`). Java's
685    /// `HttpClient` disallows a fixed set of restricted headers; those are
686    /// silently dropped so the test compiles.
687    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
688        // Java's HttpClient throws IllegalArgumentException for these headers.
689        const JAVA_RESTRICTED_HEADERS: &[&str] = &["connection", "content-length", "expect", "host", "upgrade"];
690
691        let method = ctx.method.to_uppercase();
692
693        // Build the path, appending query params when present.
694        let path = if ctx.query_params.is_empty() {
695            ctx.path.to_string()
696        } else {
697            let pairs: Vec<String> = ctx
698                .query_params
699                .iter()
700                .map(|(k, v)| {
701                    let val_str = match v {
702                        serde_json::Value::String(s) => s.clone(),
703                        other => other.to_string(),
704                    };
705                    format!("{}={}", k, escape_java(&val_str))
706                })
707                .collect();
708            format!("{}?{}", ctx.path, pairs.join("&"))
709        };
710
711        let body_publisher = if let Some(body) = ctx.body {
712            let json = serde_json::to_string(body).unwrap_or_default();
713            let escaped = escape_java(&json);
714            format!("java.net.http.HttpRequest.BodyPublishers.ofString(\"{escaped}\")")
715        } else {
716            "java.net.http.HttpRequest.BodyPublishers.noBody()".to_string()
717        };
718
719        // Content-Type header — only when a body is present.
720        let content_type = if ctx.body.is_some() {
721            let ct = ctx.content_type.unwrap_or("application/json");
722            // Only emit when not already in ctx.headers (avoid duplicate Content-Type).
723            if !ctx.headers.keys().any(|k| k.to_lowercase() == "content-type") {
724                Some(ct.to_string())
725            } else {
726                None
727            }
728        } else {
729            None
730        };
731
732        // Build header lines — skip Java-restricted ones.
733        let mut headers_lines: Vec<String> = Vec::new();
734        for (name, value) in ctx.headers {
735            if JAVA_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
736                continue;
737            }
738            let escaped_name = escape_java(name);
739            let escaped_value = escape_java(value);
740            headers_lines.push(format!(
741                "builder = builder.header(\"{escaped_name}\", \"{escaped_value}\");"
742            ));
743        }
744
745        // Cookies as a single `Cookie` header.
746        let cookies_line = if !ctx.cookies.is_empty() {
747            let cookie_str: Vec<String> = ctx.cookies.iter().map(|(k, v)| format!("{k}={v}")).collect();
748            let cookie_header = escape_java(&cookie_str.join("; "));
749            Some(format!("builder = builder.header(\"Cookie\", \"{cookie_header}\");"))
750        } else {
751            None
752        };
753
754        let rendered = crate::template_env::render(
755            "java/http_request.jinja",
756            minijinja::context! {
757                method => method,
758                path => path,
759                body_publisher => body_publisher,
760                content_type => content_type,
761                headers_lines => headers_lines,
762                cookies_line => cookies_line,
763                response_var => ctx.response_var,
764            },
765        );
766        out.push_str(&rendered);
767    }
768
769    /// Emit `assertEquals(status, response.statusCode(), ...)`.
770    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
771        let rendered = crate::template_env::render(
772            "java/http_assertions.jinja",
773            minijinja::context! {
774                response_var => response_var,
775                status_code => status,
776                headers => Vec::<std::collections::HashMap<&str, String>>::new(),
777                body_assertion => String::new(),
778                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
779                validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
780            },
781        );
782        out.push_str(&rendered);
783    }
784
785    /// Emit a header assertion using `response.headers().firstValue(...)`.
786    ///
787    /// Handles special tokens: `<<present>>`, `<<absent>>`, `<<uuid>>`.
788    fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
789        let escaped_name = escape_java(name);
790        let assertion_code = match expected {
791            "<<present>>" => {
792                format!(
793                    "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").isPresent(), \"header {escaped_name} should be present\");"
794                )
795            }
796            "<<absent>>" => {
797                format!(
798                    "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").isEmpty(), \"header {escaped_name} should be absent\");"
799                )
800            }
801            "<<uuid>>" => {
802                format!(
803                    "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").orElse(\"\").matches(\"[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{12}}\"), \"header {escaped_name} should be a UUID\");"
804                )
805            }
806            literal => {
807                let escaped_value = escape_java(literal);
808                format!(
809                    "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").orElse(\"\").contains(\"{escaped_value}\"), \"header {escaped_name} mismatch\");"
810                )
811            }
812        };
813
814        let mut headers = vec![std::collections::HashMap::new()];
815        headers[0].insert("assertion_code", assertion_code);
816
817        let rendered = crate::template_env::render(
818            "java/http_assertions.jinja",
819            minijinja::context! {
820                response_var => response_var,
821                status_code => 0u16,
822                headers => headers,
823                body_assertion => String::new(),
824                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
825                validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
826            },
827        );
828        out.push_str(&rendered);
829    }
830
831    /// Emit a JSON body equality assertion using Jackson's `MAPPER.readTree`.
832    fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
833        let body_assertion = match expected {
834            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
835                let json_str = serde_json::to_string(expected).unwrap_or_default();
836                let escaped = escape_java(&json_str);
837                format!(
838                    "var bodyJson = MAPPER.readTree({response_var}.body());\n        var expectedJson = MAPPER.readTree(\"{escaped}\");\n        assertEquals(expectedJson, bodyJson, \"body mismatch\");"
839                )
840            }
841            serde_json::Value::String(s) => {
842                let escaped = escape_java(s);
843                format!("assertEquals(\"{escaped}\", {response_var}.body().trim(), \"body mismatch\");")
844            }
845            other => {
846                let escaped = escape_java(&other.to_string());
847                format!("assertEquals(\"{escaped}\", {response_var}.body().trim(), \"body mismatch\");")
848            }
849        };
850
851        let rendered = crate::template_env::render(
852            "java/http_assertions.jinja",
853            minijinja::context! {
854                response_var => response_var,
855                status_code => 0u16,
856                headers => Vec::<std::collections::HashMap<&str, String>>::new(),
857                body_assertion => body_assertion,
858                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
859                validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
860            },
861        );
862        out.push_str(&rendered);
863    }
864
865    /// Emit partial JSON body assertions: parse once, then assert each expected field.
866    fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
867        if let Some(obj) = expected.as_object() {
868            let mut partial_body: Vec<std::collections::HashMap<&str, String>> = Vec::new();
869            for (key, val) in obj {
870                let escaped_key = escape_java(key);
871                let json_str = serde_json::to_string(val).unwrap_or_default();
872                let escaped_val = escape_java(&json_str);
873                let assertion_code = format!(
874                    "assertEquals(MAPPER.readTree(\"{escaped_val}\"), partialJson.get(\"{escaped_key}\"), \"body field '{escaped_key}' mismatch\");"
875                );
876                let mut entry = std::collections::HashMap::new();
877                entry.insert("assertion_code", assertion_code);
878                partial_body.push(entry);
879            }
880
881            let rendered = crate::template_env::render(
882                "java/http_assertions.jinja",
883                minijinja::context! {
884                    response_var => response_var,
885                    status_code => 0u16,
886                    headers => Vec::<std::collections::HashMap<&str, String>>::new(),
887                    body_assertion => String::new(),
888                    partial_body => partial_body,
889                    validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
890                },
891            );
892            out.push_str(&rendered);
893        }
894    }
895
896    /// Emit validation-error assertions: parse the body and check each expected message.
897    fn render_assert_validation_errors(
898        &self,
899        out: &mut String,
900        response_var: &str,
901        errors: &[crate::fixture::ValidationErrorExpectation],
902    ) {
903        let mut validation_errors: Vec<std::collections::HashMap<&str, String>> = Vec::new();
904        for err in errors {
905            let escaped_msg = escape_java(&err.msg);
906            let assertion_code = format!(
907                "assertTrue(veBody.contains(\"{escaped_msg}\"), \"expected validation error message: {escaped_msg}\");"
908            );
909            let mut entry = std::collections::HashMap::new();
910            entry.insert("assertion_code", assertion_code);
911            validation_errors.push(entry);
912        }
913
914        let rendered = crate::template_env::render(
915            "java/http_assertions.jinja",
916            minijinja::context! {
917                response_var => response_var,
918                status_code => 0u16,
919                headers => Vec::<std::collections::HashMap<&str, String>>::new(),
920                body_assertion => String::new(),
921                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
922                validation_errors => validation_errors,
923            },
924        );
925        out.push_str(&rendered);
926    }
927}
928
929/// Render an HTTP server test method using `java.net.http.HttpClient` against
930/// `MOCK_SERVER_URL`. Delegates to the shared
931/// [`client::http_call::render_http_test`] driver via [`JavaTestClientRenderer`].
932///
933/// The one Java-specific pre-condition — HTTP 101 (WebSocket upgrade) causing an
934/// `EOFException` in `HttpClient` — is handled here before delegating.
935fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
936    // HTTP 101 (WebSocket upgrade) causes Java's HttpClient to throw EOFException.
937    // Emit an assumeTrue(false, ...) stub so the test is skipped rather than failing.
938    if http.expected_response.status_code == 101 {
939        let method_name = fixture.id.to_upper_camel_case();
940        let description = &fixture.description;
941        out.push_str(&crate::template_env::render(
942            "java/http_test_skip_101.jinja",
943            minijinja::context! {
944                method_name => method_name,
945                description => description,
946            },
947        ));
948        return;
949    }
950
951    client::http_call::render_http_test(out, &JavaTestClientRenderer, fixture);
952}
953
954#[allow(clippy::too_many_arguments)]
955fn render_test_method(
956    out: &mut String,
957    fixture: &Fixture,
958    class_name: &str,
959    _function_name: &str,
960    _result_var: &str,
961    _args: &[crate::config::ArgMapping],
962    options_type: Option<&str>,
963    field_resolver: &FieldResolver,
964    result_is_simple: bool,
965    enum_fields: &std::collections::HashSet<String>,
966    e2e_config: &E2eConfig,
967    nested_types: &std::collections::HashMap<String, String>,
968    nested_types_optional: bool,
969) {
970    // Delegate HTTP fixtures to the HTTP-specific renderer.
971    if let Some(http) = &fixture.http {
972        render_http_test_method(out, fixture, http);
973        return;
974    }
975
976    // Resolve per-fixture call config (supports named calls via fixture.call field).
977    // Use resolve_call_for_fixture to support auto-routing via select_when.
978    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
979    let lang = "java";
980    let call_overrides = call_config.overrides.get(lang);
981    let effective_function_name = call_overrides
982        .and_then(|o| o.function.as_ref())
983        .cloned()
984        .unwrap_or_else(|| call_config.function.to_lower_camel_case());
985    let effective_result_var = &call_config.result_var;
986    let effective_args = &call_config.args;
987    let function_name = effective_function_name.as_str();
988    let result_var = effective_result_var.as_str();
989    let args: &[crate::config::ArgMapping] = effective_args.as_slice();
990
991    let method_name = fixture.id.to_upper_camel_case();
992    let description = &fixture.description;
993    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
994
995    // Resolve per-fixture options_type: prefer the java call override, fall back to
996    // class-level, then to any other language's options_type for the same call (the
997    // generated Java POJO class name matches the Rust type name across bindings, so
998    // mirroring the C/csharp/go option lets us auto-emit `Type.fromJson(json)` without
999    // requiring an explicit Java override per call).
1000    let effective_options_type: Option<String> = call_overrides
1001        .and_then(|o| o.options_type.clone())
1002        .or_else(|| options_type.map(|s| s.to_string()))
1003        .or_else(|| {
1004            // Borrow from any other backend's options_type. Prefer non-language-prefixed
1005            // names (csharp/c/go/php/python) over wasm or ruby which use prefixed types
1006            // like `WasmCreateBatchRequest` or `LiterLlm::CreateBatchRequest`.
1007            for cand in ["csharp", "c", "go", "php", "python"] {
1008                if let Some(o) = call_config.overrides.get(cand) {
1009                    if let Some(t) = &o.options_type {
1010                        return Some(t.clone());
1011                    }
1012                }
1013            }
1014            None
1015        });
1016    let effective_options_type = effective_options_type.as_deref();
1017    // When options_type is resolvable but no explicit options_via is given for Java,
1018    // default to "from_json" so the typed-request arg is emitted as
1019    // `Type.fromJson(json)` rather than the raw JSON string. The Java backend exposes
1020    // a static `fromJson(String)` factory on every record type (Stage A).
1021    let auto_from_json = effective_options_type.is_some()
1022        && call_overrides.and_then(|o| o.options_via.as_deref()).is_none()
1023        && e2e_config
1024            .call
1025            .overrides
1026            .get(lang)
1027            .and_then(|o| o.options_via.as_deref())
1028            .is_none();
1029
1030    // Resolve client_factory: prefer call-level java override, fall back to file-level java override.
1031    let client_factory: Option<String> = call_overrides.and_then(|o| o.client_factory.clone()).or_else(|| {
1032        e2e_config
1033            .call
1034            .overrides
1035            .get(lang)
1036            .and_then(|o| o.client_factory.clone())
1037    });
1038
1039    // Resolve options_via: "kwargs" (default), "from_json", "json", "dict".
1040    // Auto-default to "from_json" when an options_type is resolvable and no explicit
1041    // options_via is configured — this lets typed-request args emit `Type.fromJson(json)`
1042    // even when alef.toml only declares the type in another binding's override block.
1043    let options_via: String = call_overrides
1044        .and_then(|o| o.options_via.clone())
1045        .or_else(|| e2e_config.call.overrides.get(lang).and_then(|o| o.options_via.clone()))
1046        .unwrap_or_else(|| {
1047            if auto_from_json {
1048                "from_json".to_string()
1049            } else {
1050                "kwargs".to_string()
1051            }
1052        });
1053
1054    // Resolve per-fixture result_is_simple and result_is_bytes from the call override.
1055    let effective_result_is_simple =
1056        call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple || result_is_simple;
1057    let effective_result_is_bytes = call_overrides.is_some_and(|o| o.result_is_bytes);
1058
1059    // Check if this test needs ObjectMapper deserialization for json_object args.
1060    let needs_deser = effective_options_type.is_some()
1061        && args.iter().any(|arg| {
1062            if arg.arg_type != "json_object" {
1063                return false;
1064            }
1065            let val = super::resolve_field(&fixture.input, &arg.field);
1066            !val.is_null() && !val.is_array()
1067        });
1068
1069    // Emit builder expressions for json_object args.
1070    let mut builder_expressions = String::new();
1071    if let (true, Some(opts_type)) = (needs_deser, effective_options_type) {
1072        for arg in args {
1073            if arg.arg_type == "json_object" {
1074                let val = super::resolve_field(&fixture.input, &arg.field);
1075                if !val.is_null() && !val.is_array() {
1076                    if options_via == "from_json" {
1077                        // Build the typed POJO via static fromJson(String) method.
1078                        // Java uses snake_case wire format (matches Rust's serde default),
1079                        // so pass through the canonical snake_case fixture keys as-is.
1080                        let normalized = super::transform_json_keys_for_language(val, "snake_case");
1081                        let json_str = serde_json::to_string(&normalized).unwrap_or_default();
1082                        let escaped = escape_java(&json_str);
1083                        let var_name = &arg.name;
1084                        builder_expressions.push_str(&format!(
1085                            "        var {var_name} = {opts_type}.fromJson(\"{escaped}\");\n",
1086                        ));
1087                    } else if let Some(obj) = val.as_object() {
1088                        // Generate builder expression: TypeName.builder().withFieldName(value)...build()
1089                        let empty_path_fields: Vec<String> = Vec::new();
1090                        let path_fields = call_overrides.map(|o| &o.path_fields).unwrap_or(&empty_path_fields);
1091                        let builder_expr = java_builder_expression(
1092                            obj,
1093                            opts_type,
1094                            enum_fields,
1095                            nested_types,
1096                            nested_types_optional,
1097                            path_fields,
1098                        );
1099                        let var_name = &arg.name;
1100                        builder_expressions.push_str(&format!("        var {} = {};\n", var_name, builder_expr));
1101                    }
1102                }
1103            }
1104        }
1105    }
1106
1107    let (mut setup_lines, args_str) =
1108        build_args_and_setup(&fixture.input, args, class_name, effective_options_type, fixture);
1109
1110    // Per-language `extra_args` from call overrides — verbatim trailing
1111    // expressions appended after the configured args (e.g. `null` for an
1112    // optional trailing parameter the fixture cannot supply). Mirrors the
1113    // TypeScript and C# implementations.
1114    let extra_args_slice: &[String] = call_overrides.map_or(&[], |o| o.extra_args.as_slice());
1115
1116    // Build visitor if present and add to setup
1117    let mut visitor_var = String::new();
1118    let mut has_visitor_fixture = false;
1119    if let Some(visitor_spec) = &fixture.visitor {
1120        visitor_var = build_java_visitor(&mut setup_lines, visitor_spec, class_name);
1121        has_visitor_fixture = true;
1122    }
1123
1124    // When visitor is present, attach it to the options parameter
1125    let mut final_args = if has_visitor_fixture {
1126        if args_str.is_empty() {
1127            format!("new ConversionOptions().withVisitor({})", visitor_var)
1128        } else if args_str.contains("new ConversionOptions")
1129            || args_str.contains("ConversionOptionsBuilder")
1130            || args_str.contains(".builder()")
1131        {
1132            // Options are being built (either new ConversionOptions(), builder pattern, or .builder().build())
1133            // append .withVisitor() call before .build() if present
1134            if args_str.contains(".build()") {
1135                let idx = args_str.rfind(".build()").unwrap();
1136                format!("{}.withVisitor({}){}", &args_str[..idx], visitor_var, &args_str[idx..])
1137            } else {
1138                format!("{}.withVisitor({})", args_str, visitor_var)
1139            }
1140        } else if args_str.ends_with(", null") {
1141            let base = &args_str[..args_str.len() - 6];
1142            format!("{}, new ConversionOptions().withVisitor({})", base, visitor_var)
1143        } else {
1144            format!("{}, new ConversionOptions().withVisitor({})", args_str, visitor_var)
1145        }
1146    } else {
1147        args_str
1148    };
1149
1150    if !extra_args_slice.is_empty() {
1151        let extra_str = extra_args_slice.join(", ");
1152        final_args = if final_args.is_empty() {
1153            extra_str
1154        } else {
1155            format!("{final_args}, {extra_str}")
1156        };
1157    }
1158
1159    // Render assertions_body
1160    let mut assertions_body = String::new();
1161
1162    // Emit a `source` variable for run_query assertions that need the raw bytes.
1163    let needs_source_var = fixture
1164        .assertions
1165        .iter()
1166        .any(|a| a.assertion_type == "method_result" && a.method.as_deref() == Some("run_query"));
1167    if needs_source_var {
1168        if let Some(source_arg) = args.iter().find(|a| a.field == "source_code") {
1169            let field = source_arg.field.strip_prefix("input.").unwrap_or(&source_arg.field);
1170            if let Some(val) = fixture.input.get(field) {
1171                let java_val = json_to_java(val);
1172                assertions_body.push_str(&format!("        var source = {}.getBytes();\n", java_val));
1173            }
1174        }
1175    }
1176
1177    // Merge per-call java enum_fields with the file-level java enum_fields so that
1178    // call-specific enum-typed result fields (e.g. `choices[0].finish_reason` for
1179    // chat) trigger Optional<Enum> coercion even when the global override block
1180    // does not list them. Per-call entries take precedence.
1181    // Combine global enum_fields (HashSet) with per-call overrides (HashMap).
1182    let mut effective_enum_fields: std::collections::HashSet<String> = enum_fields.clone();
1183    if let Some(co) = call_overrides {
1184        for k in co.enum_fields.keys() {
1185            effective_enum_fields.insert(k.clone());
1186        }
1187    }
1188
1189    for assertion in &fixture.assertions {
1190        render_assertion(
1191            &mut assertions_body,
1192            assertion,
1193            result_var,
1194            class_name,
1195            field_resolver,
1196            effective_result_is_simple,
1197            effective_result_is_bytes,
1198            &effective_enum_fields,
1199        );
1200    }
1201
1202    let throws_clause = " throws Exception";
1203
1204    // When client_factory is set, instantiate a client and dispatch the call as
1205    // a method on the client; otherwise call the static helper on `class_name`.
1206    let (client_setup_lines, call_target) = if let Some(factory) = client_factory.as_deref() {
1207        let factory_name = factory.to_lower_camel_case();
1208        let fixture_id = &fixture.id;
1209        let mut setup: Vec<String> = Vec::new();
1210        let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1211        let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1212        if let Some(var) = api_key_var.filter(|_| has_mock) {
1213            setup.push(format!("String apiKey = System.getenv(\"{var}\");"));
1214            setup.push(format!(
1215                "String baseUrl = (apiKey != null && !apiKey.isEmpty()) ? null : System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";"
1216            ));
1217            setup.push(format!(
1218                "System.out.println(\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({var} is set)\" : \"using mock server ({var} not set)\"));"
1219            ));
1220            setup.push(format!(
1221                "var client = {class_name}.{factory_name}(baseUrl == null ? apiKey : \"test-key\", baseUrl, null, null, null);"
1222            ));
1223        } else if has_mock {
1224            if fixture.has_host_root_route() {
1225                setup.push(format!(
1226                    "String mockUrl = System.getProperty(\"mockServer.{fixture_id}\", System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\");"
1227                ));
1228            } else {
1229                setup.push(format!(
1230                    "String mockUrl = System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";"
1231                ));
1232            }
1233            setup.push(format!(
1234                "var client = {class_name}.{factory_name}(\"test-key\", mockUrl, null, null, null);"
1235            ));
1236        } else if let Some(api_key_var) = api_key_var {
1237            setup.push(format!("String apiKey = System.getenv(\"{api_key_var}\");"));
1238            setup.push(format!(
1239                "org.junit.jupiter.api.Assumptions.assumeTrue(apiKey != null && !apiKey.isEmpty(), \"{api_key_var} not set\");"
1240            ));
1241            setup.push(format!("var client = {class_name}.{factory_name}(apiKey);"));
1242        } else {
1243            setup.push(format!("var client = {class_name}.{factory_name}(\"test-key\");"));
1244        }
1245        (setup, "client".to_string())
1246    } else {
1247        (Vec::new(), class_name.to_string())
1248    };
1249
1250    // Prepend client setup before any other setup_lines.
1251    let combined_setup: Vec<String> = client_setup_lines.into_iter().chain(setup_lines).collect();
1252
1253    let call_expr = format!("{call_target}.{function_name}({final_args})");
1254
1255    // Streaming detection (call-level `streaming` opt-out is honored).
1256    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
1257    let collect_snippet = if is_streaming && !expects_error {
1258        crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("java", result_var, "chunks")
1259            .unwrap_or_default()
1260    } else {
1261        String::new()
1262    };
1263
1264    let rendered = crate::template_env::render(
1265        "java/test_method.jinja",
1266        minijinja::context! {
1267            method_name => method_name,
1268            description => description,
1269            builder_expressions => builder_expressions,
1270            setup_lines => combined_setup,
1271            throws_clause => throws_clause,
1272            expects_error => expects_error,
1273            call_expr => call_expr,
1274            result_var => result_var,
1275            collect_snippet => collect_snippet,
1276            assertions_body => assertions_body,
1277        },
1278    );
1279    out.push_str(&rendered);
1280}
1281
1282/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1283///
1284/// Returns `(setup_lines, args_string)`.
1285fn build_args_and_setup(
1286    input: &serde_json::Value,
1287    args: &[crate::config::ArgMapping],
1288    class_name: &str,
1289    options_type: Option<&str>,
1290    fixture: &crate::fixture::Fixture,
1291) -> (Vec<String>, String) {
1292    let fixture_id = &fixture.id;
1293    if args.is_empty() {
1294        return (Vec::new(), String::new());
1295    }
1296
1297    let mut setup_lines: Vec<String> = Vec::new();
1298    let mut parts: Vec<String> = Vec::new();
1299
1300    for arg in args {
1301        if arg.arg_type == "mock_url" {
1302            if fixture.has_host_root_route() {
1303                setup_lines.push(format!(
1304                    "String {} = System.getProperty(\"mockServer.{fixture_id}\", System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\");",
1305                    arg.name,
1306                ));
1307            } else {
1308                setup_lines.push(format!(
1309                    "String {} = System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";",
1310                    arg.name,
1311                ));
1312            }
1313            parts.push(arg.name.clone());
1314            continue;
1315        }
1316
1317        if arg.arg_type == "handle" {
1318            // Generate a createEngine (or equivalent) call and pass the variable.
1319            let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1320            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1321            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1322            if config_value.is_null()
1323                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1324            {
1325                setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1326            } else {
1327                let json_str = serde_json::to_string(config_value).unwrap_or_default();
1328                let name = &arg.name;
1329                setup_lines.push(format!(
1330                    "var {name}Config = MAPPER.readValue(\"{}\", CrawlConfig.class);",
1331                    escape_java(&json_str),
1332                ));
1333                setup_lines.push(format!(
1334                    "var {} = {class_name}.{constructor_name}({name}Config);",
1335                    arg.name,
1336                    name = name,
1337                ));
1338            }
1339            parts.push(arg.name.clone());
1340            continue;
1341        }
1342
1343        let resolved = super::resolve_field(input, &arg.field);
1344        let val = if resolved.is_null() { None } else { Some(resolved) };
1345        match val {
1346            None | Some(serde_json::Value::Null) if arg.optional => {
1347                // Optional arg with no fixture value: emit positional null/default so the call
1348                // has the right arity. For json_object optional args, build an empty default object
1349                // so we get the right type rather than a raw null.
1350                if arg.arg_type == "json_object" {
1351                    if let Some(opts_type) = options_type {
1352                        parts.push(format!("{opts_type}.builder().build()"));
1353                    } else {
1354                        parts.push("null".to_string());
1355                    }
1356                } else {
1357                    parts.push("null".to_string());
1358                }
1359            }
1360            None | Some(serde_json::Value::Null) => {
1361                // Required arg with no fixture value: pass a language-appropriate default.
1362                let default_val = match arg.arg_type.as_str() {
1363                    "string" | "file_path" => "\"\"".to_string(),
1364                    "int" | "integer" => "0".to_string(),
1365                    "float" | "number" => "0.0d".to_string(),
1366                    "bool" | "boolean" => "false".to_string(),
1367                    _ => "null".to_string(),
1368                };
1369                parts.push(default_val);
1370            }
1371            Some(v) => {
1372                if arg.arg_type == "json_object" {
1373                    // Array json_object args: emit inline Java list expression.
1374                    // Check for batch item arrays first (element_type = BatchBytesItem/BatchFileItem).
1375                    if v.is_array() {
1376                        if let Some(elem_type) = &arg.element_type {
1377                            if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
1378                                parts.push(emit_java_batch_item_array(v, elem_type));
1379                                continue;
1380                            }
1381                        }
1382                        // Otherwise use element_type to emit the correct numeric literal suffix (f vs d).
1383                        let elem_type = arg.element_type.as_deref();
1384                        parts.push(json_to_java_typed(v, elem_type));
1385                        continue;
1386                    }
1387                    // Object json_object args with options_type: use pre-deserialized variable.
1388                    if options_type.is_some() {
1389                        parts.push(arg.name.clone());
1390                        continue;
1391                    }
1392                    parts.push(json_to_java(v));
1393                    continue;
1394                }
1395                // bytes args carry a relative file path (e.g. "docx/fake.docx") that the
1396                // e2e harness resolves against test_documents/. Read the file at runtime,
1397                // not the raw path string's UTF-8 bytes.
1398                if arg.arg_type == "bytes" {
1399                    let val = json_to_java(v);
1400                    parts.push(format!(
1401                        "java.nio.file.Files.readAllBytes(java.nio.file.Path.of({val}))"
1402                    ));
1403                    continue;
1404                }
1405                // file_path args must be wrapped in java.nio.file.Path.of().
1406                if arg.arg_type == "file_path" {
1407                    let val = json_to_java(v);
1408                    parts.push(format!("java.nio.file.Path.of({val})"));
1409                    continue;
1410                }
1411                parts.push(json_to_java(v));
1412            }
1413        }
1414    }
1415
1416    (setup_lines, parts.join(", "))
1417}
1418
1419#[allow(clippy::too_many_arguments)]
1420fn render_assertion(
1421    out: &mut String,
1422    assertion: &Assertion,
1423    result_var: &str,
1424    class_name: &str,
1425    field_resolver: &FieldResolver,
1426    result_is_simple: bool,
1427    result_is_bytes: bool,
1428    enum_fields: &std::collections::HashSet<String>,
1429) {
1430    // Byte-buffer returns: emit length-based assertions instead of struct-field
1431    // accessors. The result is `byte[]`, which has no `isEmpty()`/struct-field methods.
1432    // Field paths on byte-buffer results (e.g. `audio`, `content`) are pseudo-fields
1433    // referencing the buffer itself — treat them the same as no-field assertions.
1434    if result_is_bytes {
1435        match assertion.assertion_type.as_str() {
1436            "not_empty" => {
1437                out.push_str(&format!(
1438                    "        assertTrue({result_var}.length > 0, \"expected non-empty value\");\n"
1439                ));
1440                return;
1441            }
1442            "is_empty" => {
1443                out.push_str(&format!(
1444                    "        assertEquals(0, {result_var}.length, \"expected empty value\");\n"
1445                ));
1446                return;
1447            }
1448            "count_equals" | "length_equals" => {
1449                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1450                    out.push_str(&format!("        assertEquals({n}, {result_var}.length);\n"));
1451                }
1452                return;
1453            }
1454            "count_min" | "length_min" => {
1455                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1456                    out.push_str(&format!(
1457                        "        assertTrue({result_var}.length >= {n}, \"expected length >= {n}\");\n"
1458                    ));
1459                }
1460                return;
1461            }
1462            "not_error" => {
1463                // Use the statically-imported assertion (org.junit.jupiter.api.Assertions.*)
1464                // so we don't need a separate FQN import of the `Assertions` class.
1465                out.push_str(&format!(
1466                    "        assertNotNull({result_var}, \"expected non-null byte[] response\");\n"
1467                ));
1468                return;
1469            }
1470            _ => {
1471                out.push_str(&format!(
1472                    "        // skipped: assertion type '{}' not supported on byte[] result\n",
1473                    assertion.assertion_type
1474                ));
1475                return;
1476            }
1477        }
1478    }
1479
1480    // Handle synthetic/virtual fields that are computed rather than direct record accessors.
1481    if let Some(f) = &assertion.field {
1482        match f.as_str() {
1483            // ---- ExtractionResult chunk-level computed predicates ----
1484            "chunks_have_content" => {
1485                let pred = format!(
1486                    "{result_var}.chunks().orElse(java.util.List.of()).stream().allMatch(c -> c.content() != null && !c.content().isBlank())"
1487                );
1488                out.push_str(&crate::template_env::render(
1489                    "java/synthetic_assertion.jinja",
1490                    minijinja::context! {
1491                        assertion_kind => "chunks_content",
1492                        assertion_type => assertion.assertion_type.as_str(),
1493                        pred => pred,
1494                        field_name => f,
1495                    },
1496                ));
1497                return;
1498            }
1499            "chunks_have_heading_context" => {
1500                let pred = format!(
1501                    "{result_var}.chunks().orElse(java.util.List.of()).stream().allMatch(c -> c.metadata().headingContext().isPresent())"
1502                );
1503                out.push_str(&crate::template_env::render(
1504                    "java/synthetic_assertion.jinja",
1505                    minijinja::context! {
1506                        assertion_kind => "chunks_heading_context",
1507                        assertion_type => assertion.assertion_type.as_str(),
1508                        pred => pred,
1509                        field_name => f,
1510                    },
1511                ));
1512                return;
1513            }
1514            "chunks_have_embeddings" => {
1515                let pred = format!(
1516                    "{result_var}.chunks().orElse(java.util.List.of()).stream().allMatch(c -> c.embedding() != null && !c.embedding().isEmpty())"
1517                );
1518                out.push_str(&crate::template_env::render(
1519                    "java/synthetic_assertion.jinja",
1520                    minijinja::context! {
1521                        assertion_kind => "chunks_embeddings",
1522                        assertion_type => assertion.assertion_type.as_str(),
1523                        pred => pred,
1524                        field_name => f,
1525                    },
1526                ));
1527                return;
1528            }
1529            "first_chunk_starts_with_heading" => {
1530                let pred = format!(
1531                    "{result_var}.chunks().orElse(java.util.List.of()).stream().findFirst().map(c -> c.metadata().headingContext().isPresent()).orElse(false)"
1532                );
1533                out.push_str(&crate::template_env::render(
1534                    "java/synthetic_assertion.jinja",
1535                    minijinja::context! {
1536                        assertion_kind => "first_chunk_heading",
1537                        assertion_type => assertion.assertion_type.as_str(),
1538                        pred => pred,
1539                        field_name => f,
1540                    },
1541                ));
1542                return;
1543            }
1544            // ---- EmbedResponse virtual fields ----
1545            // When result_is_simple=true the result IS List<List<Float>> (the raw embeddings list).
1546            // When result_is_simple=false the result has an .embeddings() accessor.
1547            "embedding_dimensions" => {
1548                // Dimension = size of the first embedding vector in the list.
1549                let embed_list = if result_is_simple {
1550                    result_var.to_string()
1551                } else {
1552                    format!("{result_var}.embeddings()")
1553                };
1554                let expr = format!("({embed_list}.isEmpty() ? 0 : {embed_list}.get(0).size())");
1555                let java_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1556                out.push_str(&crate::template_env::render(
1557                    "java/synthetic_assertion.jinja",
1558                    minijinja::context! {
1559                        assertion_kind => "embedding_dimensions",
1560                        assertion_type => assertion.assertion_type.as_str(),
1561                        expr => expr,
1562                        java_val => java_val,
1563                        field_name => f,
1564                    },
1565                ));
1566                return;
1567            }
1568            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1569                // These are validation predicates that require iterating the embedding matrix.
1570                let embed_list = if result_is_simple {
1571                    result_var.to_string()
1572                } else {
1573                    format!("{result_var}.embeddings()")
1574                };
1575                let pred = match f.as_str() {
1576                    "embeddings_valid" => {
1577                        format!("{embed_list}.stream().allMatch(e -> e != null && !e.isEmpty())")
1578                    }
1579                    "embeddings_finite" => {
1580                        format!("{embed_list}.stream().flatMap(java.util.Collection::stream).allMatch(Float::isFinite)")
1581                    }
1582                    "embeddings_non_zero" => {
1583                        format!("{embed_list}.stream().allMatch(e -> e.stream().anyMatch(v -> v != 0.0f))")
1584                    }
1585                    "embeddings_normalized" => format!(
1586                        "{embed_list}.stream().allMatch(e -> {{ double n = e.stream().mapToDouble(v -> v * v).sum(); return Math.abs(n - 1.0) < 1e-3; }})"
1587                    ),
1588                    _ => unreachable!(),
1589                };
1590                let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1591                out.push_str(&crate::template_env::render(
1592                    "java/synthetic_assertion.jinja",
1593                    minijinja::context! {
1594                        assertion_kind => assertion_kind,
1595                        assertion_type => assertion.assertion_type.as_str(),
1596                        pred => pred,
1597                        field_name => f,
1598                    },
1599                ));
1600                return;
1601            }
1602            // ---- Fields not present on the Java ExtractionResult ----
1603            "keywords" | "keywords_count" => {
1604                out.push_str(&crate::template_env::render(
1605                    "java/synthetic_assertion.jinja",
1606                    minijinja::context! {
1607                        assertion_kind => "keywords",
1608                        field_name => f,
1609                    },
1610                ));
1611                return;
1612            }
1613            // ---- metadata not_empty / is_empty: Metadata is a required record, not Optional ----
1614            // Metadata has no .isEmpty() method; check that at least one optional field is present.
1615            "metadata" => {
1616                match assertion.assertion_type.as_str() {
1617                    "not_empty" | "is_empty" => {
1618                        out.push_str(&crate::template_env::render(
1619                            "java/synthetic_assertion.jinja",
1620                            minijinja::context! {
1621                                assertion_kind => "metadata",
1622                                assertion_type => assertion.assertion_type.as_str(),
1623                                result_var => result_var,
1624                            },
1625                        ));
1626                        return;
1627                    }
1628                    _ => {} // fall through to normal handling
1629                }
1630            }
1631            _ => {}
1632        }
1633    }
1634
1635    // Streaming virtual fields: intercept before is_valid_for_result so they are
1636    // never skipped.  These fields resolve against the `chunks` collected-list variable.
1637    if let Some(f) = &assertion.field {
1638        if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1639            if let Some(expr) =
1640                crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "java", "chunks")
1641            {
1642                let line = match assertion.assertion_type.as_str() {
1643                    "count_min" => {
1644                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1645                            format!("        assertTrue({expr}.size() >= {n}, \"expected >= {n} chunks\");\n")
1646                        } else {
1647                            String::new()
1648                        }
1649                    }
1650                    "count_equals" => {
1651                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1652                            format!("        assertEquals({n}, {expr}.size());\n")
1653                        } else {
1654                            String::new()
1655                        }
1656                    }
1657                    "equals" => {
1658                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1659                            let escaped = crate::escape::escape_java(s);
1660                            format!("        assertEquals(\"{escaped}\", {expr});\n")
1661                        } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1662                            format!("        assertEquals({n}, {expr});\n")
1663                        } else {
1664                            String::new()
1665                        }
1666                    }
1667                    "not_empty" => format!("        assertFalse({expr}.isEmpty(), \"expected non-empty\");\n"),
1668                    "is_empty" => format!("        assertTrue({expr}.isEmpty(), \"expected empty\");\n"),
1669                    "is_true" => format!("        assertTrue({expr}, \"expected true\");\n"),
1670                    "is_false" => format!("        assertFalse({expr}, \"expected false\");\n"),
1671                    "greater_than" => {
1672                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1673                            format!("        assertTrue({expr} > {n}, \"expected > {n}\");\n")
1674                        } else {
1675                            String::new()
1676                        }
1677                    }
1678                    "greater_than_or_equal" => {
1679                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1680                            format!("        assertTrue({expr} >= {n}, \"expected >= {n}\");\n")
1681                        } else {
1682                            String::new()
1683                        }
1684                    }
1685                    "contains" => {
1686                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1687                            let escaped = crate::escape::escape_java(s);
1688                            format!(
1689                                "        assertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\");\n"
1690                            )
1691                        } else {
1692                            String::new()
1693                        }
1694                    }
1695                    _ => format!(
1696                        "        // streaming field '{f}': assertion type '{}' not rendered\n",
1697                        assertion.assertion_type
1698                    ),
1699                };
1700                if !line.is_empty() {
1701                    out.push_str(&line);
1702                }
1703            }
1704            return;
1705        }
1706    }
1707
1708    // Skip assertions on fields that don't exist on the result type.
1709    if let Some(f) = &assertion.field {
1710        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1711            out.push_str(&crate::template_env::render(
1712                "java/synthetic_assertion.jinja",
1713                minijinja::context! {
1714                    assertion_kind => "skipped",
1715                    field_name => f,
1716                },
1717            ));
1718            return;
1719        }
1720    }
1721
1722    // Determine if this field is an enum type (no `.contains()` on enums in Java).
1723    // Check both the raw fixture field path and the resolved (aliased) path so that
1724    // `fields_enum` entries can use either form (e.g., `"assets[].category"` or the
1725    // resolved `"assets[].asset_category"`).
1726    let field_is_enum = assertion
1727        .field
1728        .as_deref()
1729        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1730
1731    // Determine if this field is an array (List<T>) — needed to choose .toString() for
1732    // contains assertions, since List.contains(Object) uses equals() which won't match
1733    // strings against complex record types like StructureItem.
1734    let field_is_array = assertion
1735        .field
1736        .as_deref()
1737        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1738
1739    let field_expr = if result_is_simple {
1740        result_var.to_string()
1741    } else {
1742        match &assertion.field {
1743            Some(f) if !f.is_empty() => {
1744                let accessor = field_resolver.accessor(f, "java", result_var);
1745                let resolved = field_resolver.resolve(f);
1746                // Unwrap Optional fields with a type-appropriate fallback.
1747                // Map.get() returns nullable, not Optional, so skip .orElse() for map access.
1748                // NOTE: is_optional() means the field is in optional_fields, but that doesn't
1749                // guarantee it returns Optional<T> in Java — nested fields like metadata.twitterCard
1750                // return @Nullable String, not Optional<String>. We detect this by checking
1751                // if the field path contains a dot (nested access).
1752                if field_resolver.is_optional(resolved) && !field_resolver.has_map_access(f) {
1753                    // All nullable fields in the Java binding return @Nullable types, not Optional<T>.
1754                    // Wrap them in Optional.ofNullable() so e2e tests can use .orElse() fallbacks.
1755                    let optional_expr = format!("java.util.Optional.ofNullable({accessor})");
1756                    // Enum-typed optional fields need .map(v -> v.getValue()) to coerce to String
1757                    // before the orElse("") fallback can type-check (Optional<Enum>.orElse("") would
1758                    // be a type mismatch — Optional<String>.orElse("") is the only safe form).
1759                    if field_is_enum {
1760                        match assertion.assertion_type.as_str() {
1761                            "not_empty" | "is_empty" => optional_expr,
1762                            _ => format!("{optional_expr}.map(v -> v.getValue()).orElse(\"\")"),
1763                        }
1764                    } else {
1765                        match assertion.assertion_type.as_str() {
1766                            // For not_empty / is_empty on Optional fields, return the raw Optional
1767                            // so the assertion arms can call isPresent()/isEmpty().
1768                            "not_empty" | "is_empty" => optional_expr,
1769                            // For size/count assertions on Optional<List<T>> fields, use List.of() fallback.
1770                            "count_min" | "count_equals" => {
1771                                format!("{optional_expr}.orElse(java.util.List.of())")
1772                            }
1773                            // For numeric comparisons on Optional<Long/Integer> fields, use 0L.
1774                            "greater_than" | "less_than" | "greater_than_or_equal" | "less_than_or_equal" => {
1775                                if field_resolver.is_array(resolved) {
1776                                    format!("{optional_expr}.orElse(java.util.List.of())")
1777                                } else {
1778                                    format!("{optional_expr}.orElse(0L)")
1779                                }
1780                            }
1781                            // For equals on Optional fields, determine fallback based on whether value is numeric.
1782                            // If the fixture value is a number, use 0L; otherwise use "".
1783                            "equals" => {
1784                                if let Some(expected) = &assertion.value {
1785                                    if expected.is_number() {
1786                                        format!("{optional_expr}.orElse(0L)")
1787                                    } else {
1788                                        format!("{optional_expr}.orElse(\"\")")
1789                                    }
1790                                } else {
1791                                    format!("{optional_expr}.orElse(\"\")")
1792                                }
1793                            }
1794                            _ if field_resolver.is_array(resolved) => {
1795                                format!("{optional_expr}.orElse(java.util.List.of())")
1796                            }
1797                            _ => format!("{optional_expr}.orElse(\"\")"),
1798                        }
1799                    }
1800                } else {
1801                    accessor
1802                }
1803            }
1804            _ => result_var.to_string(),
1805        }
1806    };
1807
1808    // For enum fields, string-based assertions need .getValue() to convert the enum to
1809    // its serde-serialized lowercase string value (e.g., AssetCategory.Image -> "image").
1810    // All alef-generated Java enums expose a getValue() method annotated with @JsonValue.
1811    // Optional enum fields are already coerced to String via `.map(v -> v.getValue()).orElse("")`
1812    // upstream in field_expr; in that case the value is already a String and we must not
1813    // call .getValue() again. Detect by looking for `.map(v -> v.getValue())` in the expr.
1814    let string_expr = if field_is_enum && !field_expr.contains(".map(v -> v.getValue())") {
1815        format!("{field_expr}.getValue()")
1816    } else {
1817        field_expr.clone()
1818    };
1819
1820    // Pre-compute context for template
1821    let assertion_type = assertion.assertion_type.as_str();
1822    let java_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1823    let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1824    let is_numeric_val = assertion.value.as_ref().is_some_and(|v| v.is_number());
1825
1826    // values_java is consumed by `contains`, `contains_all`, `contains_any`, and
1827    // `not_contains` loops. Fall back to wrapping the singular `value` so single-entry
1828    // fixtures still emit one assertion call per value instead of an empty loop.
1829    let values_java: Vec<String> = assertion
1830        .values
1831        .as_ref()
1832        .map(|values| values.iter().map(json_to_java).collect::<Vec<_>>())
1833        .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_java(v)]))
1834        .unwrap_or_default();
1835
1836    let contains_any_expr = if !values_java.is_empty() {
1837        values_java
1838            .iter()
1839            .map(|v| format!("{string_expr}.contains({v})"))
1840            .collect::<Vec<_>>()
1841            .join(" || ")
1842    } else {
1843        String::new()
1844    };
1845
1846    let length_expr = if result_is_bytes {
1847        format!("{field_expr}.length")
1848    } else {
1849        format!("{field_expr}.length()")
1850    };
1851
1852    let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1853
1854    let call_expr = if let Some(method_name) = &assertion.method {
1855        build_java_method_call(result_var, method_name, assertion.args.as_ref(), class_name)
1856    } else {
1857        String::new()
1858    };
1859
1860    let check = assertion.check.as_deref().unwrap_or("is_true");
1861
1862    let java_check_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1863
1864    let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1865
1866    let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1867    let bool_is_true = assertion.value.as_ref().is_some_and(|v| v.as_bool() == Some(true));
1868
1869    let method_returns_collection = assertion
1870        .method
1871        .as_ref()
1872        .is_some_and(|m| matches!(m.as_str(), "find_nodes_by_type" | "findNodesByType"));
1873
1874    let rendered = crate::template_env::render(
1875        "java/assertion.jinja",
1876        minijinja::context! {
1877            assertion_type,
1878            java_val,
1879            string_expr,
1880            field_expr,
1881            field_is_enum,
1882            field_is_array,
1883            is_string_val,
1884            is_numeric_val,
1885            values_java => values_java,
1886            contains_any_expr,
1887            length_expr,
1888            n,
1889            call_expr,
1890            check,
1891            java_check_val,
1892            check_n,
1893            is_bool_val,
1894            bool_is_true,
1895            method_returns_collection,
1896        },
1897    );
1898    out.push_str(&rendered);
1899}
1900
1901/// Build a Java call expression for a `method_result` assertion on a tree-sitter Tree.
1902///
1903/// Maps method names to the appropriate Java static/instance method calls.
1904fn build_java_method_call(
1905    result_var: &str,
1906    method_name: &str,
1907    args: Option<&serde_json::Value>,
1908    class_name: &str,
1909) -> String {
1910    match method_name {
1911        "root_child_count" => format!("{result_var}.rootNode().childCount()"),
1912        "root_node_type" => format!("{result_var}.rootNode().kind()"),
1913        "named_children_count" => format!("{result_var}.rootNode().namedChildCount()"),
1914        "has_error_nodes" => format!("{class_name}.treeHasErrorNodes({result_var})"),
1915        "error_count" | "tree_error_count" => format!("{class_name}.treeErrorCount({result_var})"),
1916        "tree_to_sexp" => format!("{class_name}.treeToSexp({result_var})"),
1917        "contains_node_type" => {
1918            let node_type = args
1919                .and_then(|a| a.get("node_type"))
1920                .and_then(|v| v.as_str())
1921                .unwrap_or("");
1922            format!("{class_name}.treeContainsNodeType({result_var}, \"{node_type}\")")
1923        }
1924        "find_nodes_by_type" => {
1925            let node_type = args
1926                .and_then(|a| a.get("node_type"))
1927                .and_then(|v| v.as_str())
1928                .unwrap_or("");
1929            format!("{class_name}.findNodesByType({result_var}, \"{node_type}\")")
1930        }
1931        "run_query" => {
1932            let query_source = args
1933                .and_then(|a| a.get("query_source"))
1934                .and_then(|v| v.as_str())
1935                .unwrap_or("");
1936            let language = args
1937                .and_then(|a| a.get("language"))
1938                .and_then(|v| v.as_str())
1939                .unwrap_or("");
1940            let escaped_query = escape_java(query_source);
1941            format!("{class_name}.runQuery({result_var}, \"{language}\", \"{escaped_query}\", source)")
1942        }
1943        _ => {
1944            format!("{result_var}.{}()", method_name.to_lower_camel_case())
1945        }
1946    }
1947}
1948
1949/// Convert a `serde_json::Value` to a Java literal string.
1950fn json_to_java(value: &serde_json::Value) -> String {
1951    json_to_java_typed(value, None)
1952}
1953
1954/// Convert a JSON value to a Java literal, optionally overriding number type for array elements.
1955/// `element_type` controls how numeric array elements are emitted: "f32" → `1.0f`, otherwise `1.0d`.
1956/// Emit Java batch item constructors for BatchBytesItem or BatchFileItem arrays.
1957fn emit_java_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1958    if let Some(items) = arr.as_array() {
1959        let item_strs: Vec<String> = items
1960            .iter()
1961            .filter_map(|item| {
1962                if let Some(obj) = item.as_object() {
1963                    match elem_type {
1964                        "BatchBytesItem" => {
1965                            let content = obj.get("content").and_then(|v| v.as_array());
1966                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1967                            let content_code = if let Some(arr) = content {
1968                                let bytes: Vec<String> = arr
1969                                    .iter()
1970                                    .filter_map(|v| v.as_u64().map(|n| format!("(byte) {}", n)))
1971                                    .collect();
1972                                format!("new byte[] {{{}}}", bytes.join(", "))
1973                            } else {
1974                                "new byte[] {}".to_string()
1975                            };
1976                            Some(format!("new {}({}, \"{}\", null)", elem_type, content_code, mime_type))
1977                        }
1978                        "BatchFileItem" => {
1979                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1980                            Some(format!(
1981                                "new {}(java.nio.file.Paths.get(\"{}\"), null)",
1982                                elem_type, path
1983                            ))
1984                        }
1985                        _ => None,
1986                    }
1987                } else {
1988                    None
1989                }
1990            })
1991            .collect();
1992        format!("java.util.Arrays.asList({})", item_strs.join(", "))
1993    } else {
1994        "java.util.List.of()".to_string()
1995    }
1996}
1997
1998fn json_to_java_typed(value: &serde_json::Value, element_type: Option<&str>) -> String {
1999    match value {
2000        serde_json::Value::String(s) => format!("\"{}\"", escape_java(s)),
2001        serde_json::Value::Bool(b) => b.to_string(),
2002        serde_json::Value::Number(n) => {
2003            if n.is_f64() {
2004                match element_type {
2005                    Some("f32" | "float" | "Float") => format!("{}f", n),
2006                    _ => format!("{}d", n),
2007                }
2008            } else {
2009                n.to_string()
2010            }
2011        }
2012        serde_json::Value::Null => "null".to_string(),
2013        serde_json::Value::Array(arr) => {
2014            let items: Vec<String> = arr.iter().map(|v| json_to_java_typed(v, element_type)).collect();
2015            format!("java.util.List.of({})", items.join(", "))
2016        }
2017        serde_json::Value::Object(_) => {
2018            let json_str = serde_json::to_string(value).unwrap_or_default();
2019            format!("\"{}\"", escape_java(&json_str))
2020        }
2021    }
2022}
2023
2024/// Generate a Java builder expression for a JSON object.
2025/// E.g., `obj = {"language": "abl", "chunk_max_size": 50}`
2026/// becomes: `TypeName.builder().withLanguage("abl").withChunkMaxSize(50L).build()`
2027///
2028/// For enums: emit `EnumType.VariantName` (detected via camelCase lookup in enum_fields)
2029/// For strings and bools: use the value directly
2030/// For plain numbers: emit the literal with type suffix (long uses L, double uses d)
2031/// For nested objects: recurse with Options suffix
2032/// When `nested_types_optional` is false, nested builders are passed directly without
2033/// Optional.of() wrapping, allowing non-optional nested config types.
2034fn java_builder_expression(
2035    obj: &serde_json::Map<String, serde_json::Value>,
2036    type_name: &str,
2037    enum_fields: &std::collections::HashSet<String>,
2038    nested_types: &std::collections::HashMap<String, String>,
2039    nested_types_optional: bool,
2040    path_fields: &[String],
2041) -> String {
2042    let mut expr = format!("{}.builder()", type_name);
2043    for (key, val) in obj {
2044        // Convert snake_case key to camelCase for method name
2045        let camel_key = key.to_lower_camel_case();
2046        let method_name = format!("with{}", camel_key.to_upper_camel_case());
2047
2048        let java_val = match val {
2049            serde_json::Value::String(s) => {
2050                // Check if this field is an enum type by checking enum_fields.
2051                // Infer enum type name from camelCase field name by converting to UpperCamelCase.
2052                if enum_fields.contains(&camel_key) {
2053                    // Enum field: infer type name from field name (e.g., "codeBlockStyle" -> "CodeBlockStyle")
2054                    let enum_type_name = camel_key.to_upper_camel_case();
2055                    let variant_name = s.to_upper_camel_case();
2056                    format!("{}.{}", enum_type_name, variant_name)
2057                } else if camel_key == "preset" && type_name == "PreprocessingOptions" {
2058                    // Special case: preset field in PreprocessingOptions maps to PreprocessingPreset
2059                    let variant_name = s.to_upper_camel_case();
2060                    format!("PreprocessingPreset.{}", variant_name)
2061                } else if path_fields.contains(key) {
2062                    // Path field: wrap in Optional.of(java.nio.file.Path.of(...))
2063                    format!("Optional.of(java.nio.file.Path.of(\"{}\"))", escape_java(s))
2064                } else {
2065                    // String field: emit as a quoted literal
2066                    format!("\"{}\"", escape_java(s))
2067                }
2068            }
2069            serde_json::Value::Bool(b) => b.to_string(),
2070            serde_json::Value::Null => "null".to_string(),
2071            serde_json::Value::Number(n) => {
2072                // Number field: emit literal with type suffix.
2073                // Java records/classes use either `long` (primitive, not nullable) or
2074                // `Optional<Long>` (nullable). The codegen wraps in `Optional.of(...)`
2075                // by default since most options builder fields are Optional, but several
2076                // record types (e.g. SecurityLimits) use primitive `long` throughout.
2077                // Skip the wrap for: (a) known-primitive top-level fields and (b) any
2078                // method on a record type whose builder methods take primitives only.
2079                let camel_key = key.to_lower_camel_case();
2080                let is_plain_field = matches!(camel_key.as_str(), "listIndentWidth" | "wrapWidth");
2081                // Builders for typed-record nested config classes use primitives
2082                // throughout — they're not the optional-options pattern.
2083                let is_primitive_builder = matches!(type_name, "SecurityLimits" | "SecurityLimitsBuilder");
2084
2085                if is_plain_field || is_primitive_builder {
2086                    // Plain numeric field: no Optional wrapper
2087                    if n.is_f64() {
2088                        format!("{}d", n)
2089                    } else {
2090                        format!("{}L", n)
2091                    }
2092                } else {
2093                    // Optional numeric field: wrap in Optional.of()
2094                    if n.is_f64() {
2095                        format!("Optional.of({}d)", n)
2096                    } else {
2097                        format!("Optional.of({}L)", n)
2098                    }
2099                }
2100            }
2101            serde_json::Value::Array(arr) => {
2102                let items: Vec<String> = arr.iter().map(|v| json_to_java_typed(v, None)).collect();
2103                format!("java.util.List.of({})", items.join(", "))
2104            }
2105            serde_json::Value::Object(nested) => {
2106                // Recurse with the type from nested_types mapping, or default to snake_case → PascalCase + "Options".
2107                let nested_type = nested_types
2108                    .get(key.as_str())
2109                    .cloned()
2110                    .unwrap_or_else(|| format!("{}Options", key.to_upper_camel_case()));
2111                let inner = java_builder_expression(
2112                    nested,
2113                    &nested_type,
2114                    enum_fields,
2115                    nested_types,
2116                    nested_types_optional,
2117                    &[],
2118                );
2119                // Top-level config builders (e.g. ExtractionConfigBuilder) declare nested
2120                // record fields as `Optional<T>` (since they are nullable). Primitive-fields
2121                // builders (SecurityLimitsBuilder etc.) take the bare type directly.
2122                let is_primitive_builder = matches!(type_name, "SecurityLimits" | "SecurityLimitsBuilder");
2123                if is_primitive_builder || !nested_types_optional {
2124                    inner
2125                } else {
2126                    format!("Optional.of({inner})")
2127                }
2128            }
2129        };
2130        expr.push_str(&format!(".{}({})", method_name, java_val));
2131    }
2132    expr.push_str(".build()");
2133    expr
2134}
2135
2136/// Build default nested type mappings for Java extraction config types.
2137///
2138/// Maps known Kreuzberg/Kreuzcrawl config field names (in snake_case) to their
2139/// Java record type names (in PascalCase). These defaults allow e2e codegen to
2140/// automatically deserialize nested config objects without requiring explicit
2141/// configuration in alef.toml. User-provided overrides take precedence.
2142fn default_java_nested_types() -> std::collections::HashMap<String, String> {
2143    [
2144        ("chunking", "ChunkingConfig"),
2145        ("ocr", "OcrConfig"),
2146        ("images", "ImageExtractionConfig"),
2147        ("html_output", "HtmlOutputConfig"),
2148        ("language_detection", "LanguageDetectionConfig"),
2149        ("postprocessor", "PostProcessorConfig"),
2150        ("acceleration", "AccelerationConfig"),
2151        ("email", "EmailConfig"),
2152        ("pages", "PageConfig"),
2153        ("pdf_options", "PdfConfig"),
2154        ("layout", "LayoutDetectionConfig"),
2155        ("tree_sitter", "TreeSitterConfig"),
2156        ("structured_extraction", "StructuredExtractionConfig"),
2157        ("content_filter", "ContentFilterConfig"),
2158        ("token_reduction", "TokenReductionOptions"),
2159        ("security_limits", "SecurityLimits"),
2160    ]
2161    .iter()
2162    .map(|(k, v)| (k.to_string(), v.to_string()))
2163    .collect()
2164}
2165
2166// ---------------------------------------------------------------------------
2167// Import collection helpers
2168// ---------------------------------------------------------------------------
2169
2170/// Recursively collect enum types and nested option types used in a builder expression.
2171/// Enums are keyed in the enum_fields map by camelCase names (e.g., "codeBlockStyle" → "CodeBlockStyle").
2172#[allow(dead_code)]
2173fn collect_enum_and_nested_types(
2174    obj: &serde_json::Map<String, serde_json::Value>,
2175    enum_fields: &std::collections::HashMap<String, String>,
2176    types_out: &mut std::collections::BTreeSet<String>,
2177) {
2178    for (key, val) in obj {
2179        // enum_fields is keyed by camelCase, not snake_case.
2180        let camel_key = key.to_lower_camel_case();
2181        if let Some(enum_type) = enum_fields.get(&camel_key) {
2182            // Add the enum type from the mapping (e.g., "CodeBlockStyle").
2183            types_out.insert(enum_type.clone());
2184        } else if camel_key == "preset" {
2185            // Special case: preset field uses PreprocessingPreset enum.
2186            types_out.insert("PreprocessingPreset".to_string());
2187        }
2188        // Recurse into nested objects to find their nested enum types.
2189        if let Some(nested) = val.as_object() {
2190            collect_enum_and_nested_types(nested, enum_fields, types_out);
2191        }
2192    }
2193}
2194
2195fn collect_nested_type_names(
2196    obj: &serde_json::Map<String, serde_json::Value>,
2197    nested_types: &std::collections::HashMap<String, String>,
2198    types_out: &mut std::collections::BTreeSet<String>,
2199) {
2200    for (key, val) in obj {
2201        if let Some(type_name) = nested_types.get(key.as_str()) {
2202            types_out.insert(type_name.clone());
2203        }
2204        if let Some(nested) = val.as_object() {
2205            collect_nested_type_names(nested, nested_types, types_out);
2206        }
2207    }
2208}
2209
2210// ---------------------------------------------------------------------------
2211// Visitor generation
2212// ---------------------------------------------------------------------------
2213
2214/// Build a Java visitor class and add setup lines. Returns the visitor variable name.
2215fn build_java_visitor(
2216    setup_lines: &mut Vec<String>,
2217    visitor_spec: &crate::fixture::VisitorSpec,
2218    class_name: &str,
2219) -> String {
2220    setup_lines.push("class _TestVisitor implements Visitor {".to_string());
2221    for (method_name, action) in &visitor_spec.callbacks {
2222        emit_java_visitor_method(setup_lines, method_name, action, class_name);
2223    }
2224    setup_lines.push("}".to_string());
2225    setup_lines.push("var visitor = new _TestVisitor();".to_string());
2226    "visitor".to_string()
2227}
2228
2229/// Emit a Java visitor method for a callback action.
2230fn emit_java_visitor_method(
2231    setup_lines: &mut Vec<String>,
2232    method_name: &str,
2233    action: &CallbackAction,
2234    _class_name: &str,
2235) {
2236    let camel_method = method_to_camel(method_name);
2237    let params = match method_name {
2238        "visit_link" => "NodeContext ctx, String href, String text, String title",
2239        "visit_image" => "NodeContext ctx, String src, String alt, String title",
2240        "visit_heading" => "NodeContext ctx, int level, String text, String id",
2241        "visit_code_block" => "NodeContext ctx, String lang, String code",
2242        "visit_code_inline"
2243        | "visit_strong"
2244        | "visit_emphasis"
2245        | "visit_strikethrough"
2246        | "visit_underline"
2247        | "visit_subscript"
2248        | "visit_superscript"
2249        | "visit_mark"
2250        | "visit_button"
2251        | "visit_summary"
2252        | "visit_figcaption"
2253        | "visit_definition_term"
2254        | "visit_definition_description" => "NodeContext ctx, String text",
2255        "visit_text" => "NodeContext ctx, String text",
2256        "visit_list_item" => "NodeContext ctx, boolean ordered, String marker, String text",
2257        "visit_blockquote" => "NodeContext ctx, String content, long depth",
2258        "visit_table_row" => "NodeContext ctx, java.util.List<String> cells, boolean isHeader",
2259        "visit_custom_element" => "NodeContext ctx, String tagName, String html",
2260        "visit_form" => "NodeContext ctx, String actionUrl, String method",
2261        "visit_input" => "NodeContext ctx, String inputType, String name, String value",
2262        "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, String src",
2263        "visit_details" => "NodeContext ctx, boolean isOpen",
2264        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2265            "NodeContext ctx, String output"
2266        }
2267        "visit_list_start" => "NodeContext ctx, boolean ordered",
2268        "visit_list_end" => "NodeContext ctx, boolean ordered, String output",
2269        _ => "NodeContext ctx",
2270    };
2271
2272    // Determine action type and values for template
2273    let (action_type, action_value, format_args) = match action {
2274        CallbackAction::Skip => ("skip", String::new(), Vec::new()),
2275        CallbackAction::Continue => ("continue", String::new(), Vec::new()),
2276        CallbackAction::PreserveHtml => ("preserve_html", String::new(), Vec::new()),
2277        CallbackAction::Custom { output } => ("custom_literal", escape_java(output), Vec::new()),
2278        CallbackAction::CustomTemplate { template, .. } => {
2279            // Extract {placeholder} names from the template (in order of appearance).
2280            let mut format_str = String::with_capacity(template.len());
2281            let mut format_args: Vec<String> = Vec::new();
2282            let mut chars = template.chars().peekable();
2283            while let Some(ch) = chars.next() {
2284                if ch == '{' {
2285                    // Collect identifier chars until '}'.
2286                    let mut name = String::new();
2287                    let mut closed = false;
2288                    for inner in chars.by_ref() {
2289                        if inner == '}' {
2290                            closed = true;
2291                            break;
2292                        }
2293                        name.push(inner);
2294                    }
2295                    if closed && !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
2296                        let camel_name = name.as_str().to_lower_camel_case();
2297                        format_args.push(camel_name);
2298                        format_str.push_str("%s");
2299                    } else {
2300                        // Not a simple placeholder — emit literally.
2301                        format_str.push('{');
2302                        format_str.push_str(&name);
2303                        if closed {
2304                            format_str.push('}');
2305                        }
2306                    }
2307                } else {
2308                    format_str.push(ch);
2309                }
2310            }
2311            let escaped = escape_java(&format_str);
2312            if format_args.is_empty() {
2313                ("custom_literal", escaped, Vec::new())
2314            } else {
2315                ("custom_formatted", escaped, format_args)
2316            }
2317        }
2318    };
2319
2320    let params = params.to_string();
2321
2322    let rendered = crate::template_env::render(
2323        "java/visitor_method.jinja",
2324        minijinja::context! {
2325            camel_method,
2326            params,
2327            action_type,
2328            action_value,
2329            format_args => format_args,
2330        },
2331    );
2332    setup_lines.push(rendered);
2333}
2334
2335/// Convert snake_case method names to Java camelCase.
2336fn method_to_camel(snake: &str) -> String {
2337    snake.to_lower_camel_case()
2338}
2339
2340#[cfg(test)]
2341mod tests {
2342    use crate::config::{CallConfig, E2eConfig, SelectWhen};
2343    use crate::fixture::Fixture;
2344    use std::collections::HashMap;
2345
2346    fn make_fixture_with_input(id: &str, input: serde_json::Value) -> Fixture {
2347        Fixture {
2348            id: id.to_string(),
2349            category: None,
2350            description: "test fixture".to_string(),
2351            tags: vec![],
2352            skip: None,
2353            env: None,
2354            call: None,
2355            input,
2356            mock_response: None,
2357            source: String::new(),
2358            http: None,
2359            assertions: vec![],
2360            visitor: None,
2361        }
2362    }
2363
2364    /// Test that resolve_call_for_fixture correctly routes to batchScrape
2365    /// when input has batch_urls and select_when condition matches.
2366    #[test]
2367    fn test_java_select_when_routes_to_batch_scrape() {
2368        let mut calls = HashMap::new();
2369        calls.insert(
2370            "batch_scrape".to_string(),
2371            CallConfig {
2372                function: "batchScrape".to_string(),
2373                module: "com.example.kreuzcrawl".to_string(),
2374                select_when: Some(SelectWhen::InputHas("batch_urls".to_string())),
2375                ..CallConfig::default()
2376            },
2377        );
2378
2379        let e2e_config = E2eConfig {
2380            call: CallConfig {
2381                function: "scrape".to_string(),
2382                module: "com.example.kreuzcrawl".to_string(),
2383                ..CallConfig::default()
2384            },
2385            calls,
2386            ..E2eConfig::default()
2387        };
2388
2389        // Fixture with batch_urls but no explicit call field should route to batch_scrape
2390        let fixture = make_fixture_with_input("batch_empty_urls", serde_json::json!({ "batch_urls": [] }));
2391
2392        let resolved_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
2393        assert_eq!(resolved_call.function, "batchScrape");
2394
2395        // Fixture without batch_urls should fall back to default scrape
2396        let fixture_no_batch =
2397            make_fixture_with_input("simple_scrape", serde_json::json!({ "url": "https://example.com" }));
2398        let resolved_default =
2399            e2e_config.resolve_call_for_fixture(fixture_no_batch.call.as_deref(), &fixture_no_batch.input);
2400        assert_eq!(resolved_default.function, "scrape");
2401    }
2402}