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's Jackson @JsonProperty annotations expect camelCase keys, so
1079                        // transform the canonical snake_case fixture keys before emitting.
1080                        let normalized = super::transform_json_keys_for_language(val, "camelCase");
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    // For streaming fixtures, add the collect snippet after the stream call.
1256    // Also trigger when any assertion references a streaming virtual field
1257    // (e.g. empty_stream has stream_chunks:[] so is_streaming_mock() returns
1258    // false, but assertions still reference `chunks`/`stream_content` which
1259    // require the collect snippet).
1260    let is_streaming = fixture.is_streaming_mock()
1261        || fixture.assertions.iter().any(|a| {
1262            a.field
1263                .as_deref()
1264                .is_some_and(|f| !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f))
1265        });
1266    let collect_snippet = if is_streaming && !expects_error {
1267        crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("java", result_var, "chunks")
1268            .unwrap_or_default()
1269    } else {
1270        String::new()
1271    };
1272
1273    let rendered = crate::template_env::render(
1274        "java/test_method.jinja",
1275        minijinja::context! {
1276            method_name => method_name,
1277            description => description,
1278            builder_expressions => builder_expressions,
1279            setup_lines => combined_setup,
1280            throws_clause => throws_clause,
1281            expects_error => expects_error,
1282            call_expr => call_expr,
1283            result_var => result_var,
1284            collect_snippet => collect_snippet,
1285            assertions_body => assertions_body,
1286        },
1287    );
1288    out.push_str(&rendered);
1289}
1290
1291/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1292///
1293/// Returns `(setup_lines, args_string)`.
1294fn build_args_and_setup(
1295    input: &serde_json::Value,
1296    args: &[crate::config::ArgMapping],
1297    class_name: &str,
1298    options_type: Option<&str>,
1299    fixture: &crate::fixture::Fixture,
1300) -> (Vec<String>, String) {
1301    let fixture_id = &fixture.id;
1302    if args.is_empty() {
1303        return (Vec::new(), String::new());
1304    }
1305
1306    let mut setup_lines: Vec<String> = Vec::new();
1307    let mut parts: Vec<String> = Vec::new();
1308
1309    for arg in args {
1310        if arg.arg_type == "mock_url" {
1311            if fixture.has_host_root_route() {
1312                setup_lines.push(format!(
1313                    "String {} = System.getProperty(\"mockServer.{fixture_id}\", System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\");",
1314                    arg.name,
1315                ));
1316            } else {
1317                setup_lines.push(format!(
1318                    "String {} = System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";",
1319                    arg.name,
1320                ));
1321            }
1322            parts.push(arg.name.clone());
1323            continue;
1324        }
1325
1326        if arg.arg_type == "handle" {
1327            // Generate a createEngine (or equivalent) call and pass the variable.
1328            let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1329            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1330            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1331            if config_value.is_null()
1332                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1333            {
1334                setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1335            } else {
1336                let json_str = serde_json::to_string(config_value).unwrap_or_default();
1337                let name = &arg.name;
1338                setup_lines.push(format!(
1339                    "var {name}Config = MAPPER.readValue(\"{}\", CrawlConfig.class);",
1340                    escape_java(&json_str),
1341                ));
1342                setup_lines.push(format!(
1343                    "var {} = {class_name}.{constructor_name}({name}Config);",
1344                    arg.name,
1345                    name = name,
1346                ));
1347            }
1348            parts.push(arg.name.clone());
1349            continue;
1350        }
1351
1352        let resolved = super::resolve_field(input, &arg.field);
1353        let val = if resolved.is_null() { None } else { Some(resolved) };
1354        match val {
1355            None | Some(serde_json::Value::Null) if arg.optional => {
1356                // Optional arg with no fixture value: emit positional null/default so the call
1357                // has the right arity. For json_object optional args, build an empty default object
1358                // so we get the right type rather than a raw null.
1359                if arg.arg_type == "json_object" {
1360                    if let Some(opts_type) = options_type {
1361                        parts.push(format!("{opts_type}.builder().build()"));
1362                    } else {
1363                        parts.push("null".to_string());
1364                    }
1365                } else {
1366                    parts.push("null".to_string());
1367                }
1368            }
1369            None | Some(serde_json::Value::Null) => {
1370                // Required arg with no fixture value: pass a language-appropriate default.
1371                let default_val = match arg.arg_type.as_str() {
1372                    "string" | "file_path" => "\"\"".to_string(),
1373                    "int" | "integer" => "0".to_string(),
1374                    "float" | "number" => "0.0d".to_string(),
1375                    "bool" | "boolean" => "false".to_string(),
1376                    _ => "null".to_string(),
1377                };
1378                parts.push(default_val);
1379            }
1380            Some(v) => {
1381                if arg.arg_type == "json_object" {
1382                    // Array json_object args: emit inline Java list expression.
1383                    // Check for batch item arrays first (element_type = BatchBytesItem/BatchFileItem).
1384                    if v.is_array() {
1385                        if let Some(elem_type) = &arg.element_type {
1386                            if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
1387                                parts.push(emit_java_batch_item_array(v, elem_type));
1388                                continue;
1389                            }
1390                        }
1391                        // Otherwise use element_type to emit the correct numeric literal suffix (f vs d).
1392                        let elem_type = arg.element_type.as_deref();
1393                        parts.push(json_to_java_typed(v, elem_type));
1394                        continue;
1395                    }
1396                    // Object json_object args with options_type: use pre-deserialized variable.
1397                    if options_type.is_some() {
1398                        parts.push(arg.name.clone());
1399                        continue;
1400                    }
1401                    parts.push(json_to_java(v));
1402                    continue;
1403                }
1404                // bytes args must be passed as byte[], not String.
1405                if arg.arg_type == "bytes" {
1406                    let val = json_to_java(v);
1407                    parts.push(format!("{val}.getBytes()"));
1408                    continue;
1409                }
1410                // file_path args must be wrapped in java.nio.file.Path.of().
1411                if arg.arg_type == "file_path" {
1412                    let val = json_to_java(v);
1413                    parts.push(format!("java.nio.file.Path.of({val})"));
1414                    continue;
1415                }
1416                parts.push(json_to_java(v));
1417            }
1418        }
1419    }
1420
1421    (setup_lines, parts.join(", "))
1422}
1423
1424#[allow(clippy::too_many_arguments)]
1425fn render_assertion(
1426    out: &mut String,
1427    assertion: &Assertion,
1428    result_var: &str,
1429    class_name: &str,
1430    field_resolver: &FieldResolver,
1431    result_is_simple: bool,
1432    result_is_bytes: bool,
1433    enum_fields: &std::collections::HashSet<String>,
1434) {
1435    // Byte-buffer returns: emit length-based assertions instead of struct-field
1436    // accessors. The result is `byte[]`, which has no `isEmpty()`/struct-field methods.
1437    // Field paths on byte-buffer results (e.g. `audio`, `content`) are pseudo-fields
1438    // referencing the buffer itself — treat them the same as no-field assertions.
1439    if result_is_bytes {
1440        match assertion.assertion_type.as_str() {
1441            "not_empty" => {
1442                out.push_str(&format!(
1443                    "        assertTrue({result_var}.length > 0, \"expected non-empty value\");\n"
1444                ));
1445                return;
1446            }
1447            "is_empty" => {
1448                out.push_str(&format!(
1449                    "        assertEquals(0, {result_var}.length, \"expected empty value\");\n"
1450                ));
1451                return;
1452            }
1453            "count_equals" | "length_equals" => {
1454                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1455                    out.push_str(&format!("        assertEquals({n}, {result_var}.length);\n"));
1456                }
1457                return;
1458            }
1459            "count_min" | "length_min" => {
1460                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1461                    out.push_str(&format!(
1462                        "        assertTrue({result_var}.length >= {n}, \"expected length >= {n}\");\n"
1463                    ));
1464                }
1465                return;
1466            }
1467            "not_error" => {
1468                // Use the statically-imported assertion (org.junit.jupiter.api.Assertions.*)
1469                // so we don't need a separate FQN import of the `Assertions` class.
1470                out.push_str(&format!(
1471                    "        assertNotNull({result_var}, \"expected non-null byte[] response\");\n"
1472                ));
1473                return;
1474            }
1475            _ => {
1476                out.push_str(&format!(
1477                    "        // skipped: assertion type '{}' not supported on byte[] result\n",
1478                    assertion.assertion_type
1479                ));
1480                return;
1481            }
1482        }
1483    }
1484
1485    // Handle synthetic/virtual fields that are computed rather than direct record accessors.
1486    if let Some(f) = &assertion.field {
1487        match f.as_str() {
1488            // ---- ExtractionResult chunk-level computed predicates ----
1489            "chunks_have_content" => {
1490                let pred = format!(
1491                    "{result_var}.chunks().orElse(java.util.List.of()).stream().allMatch(c -> c.content() != null && !c.content().isBlank())"
1492                );
1493                out.push_str(&crate::template_env::render(
1494                    "java/synthetic_assertion.jinja",
1495                    minijinja::context! {
1496                        assertion_kind => "chunks_content",
1497                        assertion_type => assertion.assertion_type.as_str(),
1498                        pred => pred,
1499                        field_name => f,
1500                    },
1501                ));
1502                return;
1503            }
1504            "chunks_have_heading_context" => {
1505                let pred = format!(
1506                    "{result_var}.chunks().orElse(java.util.List.of()).stream().allMatch(c -> c.metadata().headingContext().isPresent())"
1507                );
1508                out.push_str(&crate::template_env::render(
1509                    "java/synthetic_assertion.jinja",
1510                    minijinja::context! {
1511                        assertion_kind => "chunks_heading_context",
1512                        assertion_type => assertion.assertion_type.as_str(),
1513                        pred => pred,
1514                        field_name => f,
1515                    },
1516                ));
1517                return;
1518            }
1519            "chunks_have_embeddings" => {
1520                let pred = format!(
1521                    "{result_var}.chunks().orElse(java.util.List.of()).stream().allMatch(c -> c.embedding() != null && !c.embedding().isEmpty())"
1522                );
1523                out.push_str(&crate::template_env::render(
1524                    "java/synthetic_assertion.jinja",
1525                    minijinja::context! {
1526                        assertion_kind => "chunks_embeddings",
1527                        assertion_type => assertion.assertion_type.as_str(),
1528                        pred => pred,
1529                        field_name => f,
1530                    },
1531                ));
1532                return;
1533            }
1534            "first_chunk_starts_with_heading" => {
1535                let pred = format!(
1536                    "{result_var}.chunks().orElse(java.util.List.of()).stream().findFirst().map(c -> c.metadata().headingContext().isPresent()).orElse(false)"
1537                );
1538                out.push_str(&crate::template_env::render(
1539                    "java/synthetic_assertion.jinja",
1540                    minijinja::context! {
1541                        assertion_kind => "first_chunk_heading",
1542                        assertion_type => assertion.assertion_type.as_str(),
1543                        pred => pred,
1544                        field_name => f,
1545                    },
1546                ));
1547                return;
1548            }
1549            // ---- EmbedResponse virtual fields ----
1550            // When result_is_simple=true the result IS List<List<Float>> (the raw embeddings list).
1551            // When result_is_simple=false the result has an .embeddings() accessor.
1552            "embedding_dimensions" => {
1553                // Dimension = size of the first embedding vector in the list.
1554                let embed_list = if result_is_simple {
1555                    result_var.to_string()
1556                } else {
1557                    format!("{result_var}.embeddings()")
1558                };
1559                let expr = format!("({embed_list}.isEmpty() ? 0 : {embed_list}.get(0).size())");
1560                let java_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1561                out.push_str(&crate::template_env::render(
1562                    "java/synthetic_assertion.jinja",
1563                    minijinja::context! {
1564                        assertion_kind => "embedding_dimensions",
1565                        assertion_type => assertion.assertion_type.as_str(),
1566                        expr => expr,
1567                        java_val => java_val,
1568                        field_name => f,
1569                    },
1570                ));
1571                return;
1572            }
1573            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1574                // These are validation predicates that require iterating the embedding matrix.
1575                let embed_list = if result_is_simple {
1576                    result_var.to_string()
1577                } else {
1578                    format!("{result_var}.embeddings()")
1579                };
1580                let pred = match f.as_str() {
1581                    "embeddings_valid" => {
1582                        format!("{embed_list}.stream().allMatch(e -> e != null && !e.isEmpty())")
1583                    }
1584                    "embeddings_finite" => {
1585                        format!("{embed_list}.stream().flatMap(java.util.Collection::stream).allMatch(Float::isFinite)")
1586                    }
1587                    "embeddings_non_zero" => {
1588                        format!("{embed_list}.stream().allMatch(e -> e.stream().anyMatch(v -> v != 0.0f))")
1589                    }
1590                    "embeddings_normalized" => format!(
1591                        "{embed_list}.stream().allMatch(e -> {{ double n = e.stream().mapToDouble(v -> v * v).sum(); return Math.abs(n - 1.0) < 1e-3; }})"
1592                    ),
1593                    _ => unreachable!(),
1594                };
1595                let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1596                out.push_str(&crate::template_env::render(
1597                    "java/synthetic_assertion.jinja",
1598                    minijinja::context! {
1599                        assertion_kind => assertion_kind,
1600                        assertion_type => assertion.assertion_type.as_str(),
1601                        pred => pred,
1602                        field_name => f,
1603                    },
1604                ));
1605                return;
1606            }
1607            // ---- Fields not present on the Java ExtractionResult ----
1608            "keywords" | "keywords_count" => {
1609                out.push_str(&crate::template_env::render(
1610                    "java/synthetic_assertion.jinja",
1611                    minijinja::context! {
1612                        assertion_kind => "keywords",
1613                        field_name => f,
1614                    },
1615                ));
1616                return;
1617            }
1618            // ---- metadata not_empty / is_empty: Metadata is a required record, not Optional ----
1619            // Metadata has no .isEmpty() method; check that at least one optional field is present.
1620            "metadata" => {
1621                match assertion.assertion_type.as_str() {
1622                    "not_empty" | "is_empty" => {
1623                        out.push_str(&crate::template_env::render(
1624                            "java/synthetic_assertion.jinja",
1625                            minijinja::context! {
1626                                assertion_kind => "metadata",
1627                                assertion_type => assertion.assertion_type.as_str(),
1628                                result_var => result_var,
1629                            },
1630                        ));
1631                        return;
1632                    }
1633                    _ => {} // fall through to normal handling
1634                }
1635            }
1636            _ => {}
1637        }
1638    }
1639
1640    // Streaming virtual fields: intercept before is_valid_for_result so they are
1641    // never skipped.  These fields resolve against the `chunks` collected-list variable.
1642    if let Some(f) = &assertion.field {
1643        if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1644            if let Some(expr) =
1645                crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "java", "chunks")
1646            {
1647                let line = match assertion.assertion_type.as_str() {
1648                    "count_min" => {
1649                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1650                            format!("        assertTrue({expr}.size() >= {n}, \"expected >= {n} chunks\");\n")
1651                        } else {
1652                            String::new()
1653                        }
1654                    }
1655                    "count_equals" => {
1656                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1657                            format!("        assertEquals({n}, {expr}.size());\n")
1658                        } else {
1659                            String::new()
1660                        }
1661                    }
1662                    "equals" => {
1663                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1664                            let escaped = crate::escape::escape_java(s);
1665                            format!("        assertEquals(\"{escaped}\", {expr});\n")
1666                        } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1667                            format!("        assertEquals({n}, {expr});\n")
1668                        } else {
1669                            String::new()
1670                        }
1671                    }
1672                    "not_empty" => format!("        assertFalse({expr}.isEmpty(), \"expected non-empty\");\n"),
1673                    "is_empty" => format!("        assertTrue({expr}.isEmpty(), \"expected empty\");\n"),
1674                    "is_true" => format!("        assertTrue({expr}, \"expected true\");\n"),
1675                    "is_false" => format!("        assertFalse({expr}, \"expected false\");\n"),
1676                    "greater_than" => {
1677                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1678                            format!("        assertTrue({expr} > {n}, \"expected > {n}\");\n")
1679                        } else {
1680                            String::new()
1681                        }
1682                    }
1683                    "greater_than_or_equal" => {
1684                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1685                            format!("        assertTrue({expr} >= {n}, \"expected >= {n}\");\n")
1686                        } else {
1687                            String::new()
1688                        }
1689                    }
1690                    "contains" => {
1691                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1692                            let escaped = crate::escape::escape_java(s);
1693                            format!(
1694                                "        assertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\");\n"
1695                            )
1696                        } else {
1697                            String::new()
1698                        }
1699                    }
1700                    _ => format!(
1701                        "        // streaming field '{f}': assertion type '{}' not rendered\n",
1702                        assertion.assertion_type
1703                    ),
1704                };
1705                if !line.is_empty() {
1706                    out.push_str(&line);
1707                }
1708            }
1709            return;
1710        }
1711    }
1712
1713    // Skip assertions on fields that don't exist on the result type.
1714    if let Some(f) = &assertion.field {
1715        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1716            out.push_str(&crate::template_env::render(
1717                "java/synthetic_assertion.jinja",
1718                minijinja::context! {
1719                    assertion_kind => "skipped",
1720                    field_name => f,
1721                },
1722            ));
1723            return;
1724        }
1725    }
1726
1727    // Determine if this field is an enum type (no `.contains()` on enums in Java).
1728    // Check both the raw fixture field path and the resolved (aliased) path so that
1729    // `fields_enum` entries can use either form (e.g., `"assets[].category"` or the
1730    // resolved `"assets[].asset_category"`).
1731    let field_is_enum = assertion
1732        .field
1733        .as_deref()
1734        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1735
1736    // Determine if this field is an array (List<T>) — needed to choose .toString() for
1737    // contains assertions, since List.contains(Object) uses equals() which won't match
1738    // strings against complex record types like StructureItem.
1739    let field_is_array = assertion
1740        .field
1741        .as_deref()
1742        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1743
1744    let field_expr = if result_is_simple {
1745        result_var.to_string()
1746    } else {
1747        match &assertion.field {
1748            Some(f) if !f.is_empty() => {
1749                let accessor = field_resolver.accessor(f, "java", result_var);
1750                let resolved = field_resolver.resolve(f);
1751                // Unwrap Optional fields with a type-appropriate fallback.
1752                // Map.get() returns nullable, not Optional, so skip .orElse() for map access.
1753                // NOTE: is_optional() means the field is in optional_fields, but that doesn't
1754                // guarantee it returns Optional<T> in Java — nested fields like metadata.twitterCard
1755                // return @Nullable String, not Optional<String>. We detect this by checking
1756                // if the field path contains a dot (nested access).
1757                if field_resolver.is_optional(resolved) && !field_resolver.has_map_access(f) {
1758                    // All nullable fields in the Java binding return @Nullable types, not Optional<T>.
1759                    // Wrap them in Optional.ofNullable() so e2e tests can use .orElse() fallbacks.
1760                    let optional_expr = format!("java.util.Optional.ofNullable({accessor})");
1761                    // Enum-typed optional fields need .map(v -> v.getValue()) to coerce to String
1762                    // before the orElse("") fallback can type-check (Optional<Enum>.orElse("") would
1763                    // be a type mismatch — Optional<String>.orElse("") is the only safe form).
1764                    if field_is_enum {
1765                        match assertion.assertion_type.as_str() {
1766                            "not_empty" | "is_empty" => optional_expr,
1767                            _ => format!("{optional_expr}.map(v -> v.getValue()).orElse(\"\")"),
1768                        }
1769                    } else {
1770                        match assertion.assertion_type.as_str() {
1771                            // For not_empty / is_empty on Optional fields, return the raw Optional
1772                            // so the assertion arms can call isPresent()/isEmpty().
1773                            "not_empty" | "is_empty" => optional_expr,
1774                            // For size/count assertions on Optional<List<T>> fields, use List.of() fallback.
1775                            "count_min" | "count_equals" => {
1776                                format!("{optional_expr}.orElse(java.util.List.of())")
1777                            }
1778                            // For numeric comparisons on Optional<Long/Integer> fields, use 0L.
1779                            "greater_than" | "less_than" | "greater_than_or_equal" | "less_than_or_equal" => {
1780                                if field_resolver.is_array(resolved) {
1781                                    format!("{optional_expr}.orElse(java.util.List.of())")
1782                                } else {
1783                                    format!("{optional_expr}.orElse(0L)")
1784                                }
1785                            }
1786                            // For equals on Optional fields, determine fallback based on whether value is numeric.
1787                            // If the fixture value is a number, use 0L; otherwise use "".
1788                            "equals" => {
1789                                if let Some(expected) = &assertion.value {
1790                                    if expected.is_number() {
1791                                        format!("{optional_expr}.orElse(0L)")
1792                                    } else {
1793                                        format!("{optional_expr}.orElse(\"\")")
1794                                    }
1795                                } else {
1796                                    format!("{optional_expr}.orElse(\"\")")
1797                                }
1798                            }
1799                            _ if field_resolver.is_array(resolved) => {
1800                                format!("{optional_expr}.orElse(java.util.List.of())")
1801                            }
1802                            _ => format!("{optional_expr}.orElse(\"\")"),
1803                        }
1804                    }
1805                } else {
1806                    accessor
1807                }
1808            }
1809            _ => result_var.to_string(),
1810        }
1811    };
1812
1813    // For enum fields, string-based assertions need .getValue() to convert the enum to
1814    // its serde-serialized lowercase string value (e.g., AssetCategory.Image -> "image").
1815    // All alef-generated Java enums expose a getValue() method annotated with @JsonValue.
1816    // Optional enum fields are already coerced to String via `.map(v -> v.getValue()).orElse("")`
1817    // upstream in field_expr; in that case the value is already a String and we must not
1818    // call .getValue() again. Detect by looking for `.map(v -> v.getValue())` in the expr.
1819    let string_expr = if field_is_enum && !field_expr.contains(".map(v -> v.getValue())") {
1820        format!("{field_expr}.getValue()")
1821    } else {
1822        field_expr.clone()
1823    };
1824
1825    // Pre-compute context for template
1826    let assertion_type = assertion.assertion_type.as_str();
1827    let java_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1828    let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1829    let is_numeric_val = assertion.value.as_ref().is_some_and(|v| v.is_number());
1830
1831    // values_java is consumed by `contains`, `contains_all`, `contains_any`, and
1832    // `not_contains` loops. Fall back to wrapping the singular `value` so single-entry
1833    // fixtures still emit one assertion call per value instead of an empty loop.
1834    let values_java: Vec<String> = assertion
1835        .values
1836        .as_ref()
1837        .map(|values| values.iter().map(json_to_java).collect::<Vec<_>>())
1838        .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_java(v)]))
1839        .unwrap_or_default();
1840
1841    let contains_any_expr = if !values_java.is_empty() {
1842        values_java
1843            .iter()
1844            .map(|v| format!("{string_expr}.contains({v})"))
1845            .collect::<Vec<_>>()
1846            .join(" || ")
1847    } else {
1848        String::new()
1849    };
1850
1851    let length_expr = if result_is_bytes {
1852        format!("{field_expr}.length")
1853    } else {
1854        format!("{field_expr}.length()")
1855    };
1856
1857    let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1858
1859    let call_expr = if let Some(method_name) = &assertion.method {
1860        build_java_method_call(result_var, method_name, assertion.args.as_ref(), class_name)
1861    } else {
1862        String::new()
1863    };
1864
1865    let check = assertion.check.as_deref().unwrap_or("is_true");
1866
1867    let java_check_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1868
1869    let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1870
1871    let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1872    let bool_is_true = assertion.value.as_ref().is_some_and(|v| v.as_bool() == Some(true));
1873
1874    let method_returns_collection = assertion
1875        .method
1876        .as_ref()
1877        .is_some_and(|m| matches!(m.as_str(), "find_nodes_by_type" | "findNodesByType"));
1878
1879    let rendered = crate::template_env::render(
1880        "java/assertion.jinja",
1881        minijinja::context! {
1882            assertion_type,
1883            java_val,
1884            string_expr,
1885            field_expr,
1886            field_is_enum,
1887            field_is_array,
1888            is_string_val,
1889            is_numeric_val,
1890            values_java => values_java,
1891            contains_any_expr,
1892            length_expr,
1893            n,
1894            call_expr,
1895            check,
1896            java_check_val,
1897            check_n,
1898            is_bool_val,
1899            bool_is_true,
1900            method_returns_collection,
1901        },
1902    );
1903    out.push_str(&rendered);
1904}
1905
1906/// Build a Java call expression for a `method_result` assertion on a tree-sitter Tree.
1907///
1908/// Maps method names to the appropriate Java static/instance method calls.
1909fn build_java_method_call(
1910    result_var: &str,
1911    method_name: &str,
1912    args: Option<&serde_json::Value>,
1913    class_name: &str,
1914) -> String {
1915    match method_name {
1916        "root_child_count" => format!("{result_var}.rootNode().childCount()"),
1917        "root_node_type" => format!("{result_var}.rootNode().kind()"),
1918        "named_children_count" => format!("{result_var}.rootNode().namedChildCount()"),
1919        "has_error_nodes" => format!("{class_name}.treeHasErrorNodes({result_var})"),
1920        "error_count" | "tree_error_count" => format!("{class_name}.treeErrorCount({result_var})"),
1921        "tree_to_sexp" => format!("{class_name}.treeToSexp({result_var})"),
1922        "contains_node_type" => {
1923            let node_type = args
1924                .and_then(|a| a.get("node_type"))
1925                .and_then(|v| v.as_str())
1926                .unwrap_or("");
1927            format!("{class_name}.treeContainsNodeType({result_var}, \"{node_type}\")")
1928        }
1929        "find_nodes_by_type" => {
1930            let node_type = args
1931                .and_then(|a| a.get("node_type"))
1932                .and_then(|v| v.as_str())
1933                .unwrap_or("");
1934            format!("{class_name}.findNodesByType({result_var}, \"{node_type}\")")
1935        }
1936        "run_query" => {
1937            let query_source = args
1938                .and_then(|a| a.get("query_source"))
1939                .and_then(|v| v.as_str())
1940                .unwrap_or("");
1941            let language = args
1942                .and_then(|a| a.get("language"))
1943                .and_then(|v| v.as_str())
1944                .unwrap_or("");
1945            let escaped_query = escape_java(query_source);
1946            format!("{class_name}.runQuery({result_var}, \"{language}\", \"{escaped_query}\", source)")
1947        }
1948        _ => {
1949            format!("{result_var}.{}()", method_name.to_lower_camel_case())
1950        }
1951    }
1952}
1953
1954/// Convert a `serde_json::Value` to a Java literal string.
1955fn json_to_java(value: &serde_json::Value) -> String {
1956    json_to_java_typed(value, None)
1957}
1958
1959/// Convert a JSON value to a Java literal, optionally overriding number type for array elements.
1960/// `element_type` controls how numeric array elements are emitted: "f32" → `1.0f`, otherwise `1.0d`.
1961/// Emit Java batch item constructors for BatchBytesItem or BatchFileItem arrays.
1962fn emit_java_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1963    if let Some(items) = arr.as_array() {
1964        let item_strs: Vec<String> = items
1965            .iter()
1966            .filter_map(|item| {
1967                if let Some(obj) = item.as_object() {
1968                    match elem_type {
1969                        "BatchBytesItem" => {
1970                            let content = obj.get("content").and_then(|v| v.as_array());
1971                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1972                            let content_code = if let Some(arr) = content {
1973                                let bytes: Vec<String> = arr
1974                                    .iter()
1975                                    .filter_map(|v| v.as_u64().map(|n| format!("(byte) {}", n)))
1976                                    .collect();
1977                                format!("new byte[] {{{}}}", bytes.join(", "))
1978                            } else {
1979                                "new byte[] {}".to_string()
1980                            };
1981                            Some(format!("new {}({}, \"{}\", null)", elem_type, content_code, mime_type))
1982                        }
1983                        "BatchFileItem" => {
1984                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1985                            Some(format!(
1986                                "new {}(java.nio.file.Paths.get(\"{}\"), null)",
1987                                elem_type, path
1988                            ))
1989                        }
1990                        _ => None,
1991                    }
1992                } else {
1993                    None
1994                }
1995            })
1996            .collect();
1997        format!("java.util.Arrays.asList({})", item_strs.join(", "))
1998    } else {
1999        "java.util.List.of()".to_string()
2000    }
2001}
2002
2003fn json_to_java_typed(value: &serde_json::Value, element_type: Option<&str>) -> String {
2004    match value {
2005        serde_json::Value::String(s) => format!("\"{}\"", escape_java(s)),
2006        serde_json::Value::Bool(b) => b.to_string(),
2007        serde_json::Value::Number(n) => {
2008            if n.is_f64() {
2009                match element_type {
2010                    Some("f32" | "float" | "Float") => format!("{}f", n),
2011                    _ => format!("{}d", n),
2012                }
2013            } else {
2014                n.to_string()
2015            }
2016        }
2017        serde_json::Value::Null => "null".to_string(),
2018        serde_json::Value::Array(arr) => {
2019            let items: Vec<String> = arr.iter().map(|v| json_to_java_typed(v, element_type)).collect();
2020            format!("java.util.List.of({})", items.join(", "))
2021        }
2022        serde_json::Value::Object(_) => {
2023            let json_str = serde_json::to_string(value).unwrap_or_default();
2024            format!("\"{}\"", escape_java(&json_str))
2025        }
2026    }
2027}
2028
2029/// Generate a Java builder expression for a JSON object.
2030/// E.g., `obj = {"language": "abl", "chunk_max_size": 50}`
2031/// becomes: `TypeName.builder().withLanguage("abl").withChunkMaxSize(50L).build()`
2032///
2033/// For enums: emit `EnumType.VariantName` (detected via camelCase lookup in enum_fields)
2034/// For strings and bools: use the value directly
2035/// For plain numbers: emit the literal with type suffix (long uses L, double uses d)
2036/// For nested objects: recurse with Options suffix
2037/// When `nested_types_optional` is false, nested builders are passed directly without
2038/// Optional.of() wrapping, allowing non-optional nested config types.
2039fn java_builder_expression(
2040    obj: &serde_json::Map<String, serde_json::Value>,
2041    type_name: &str,
2042    enum_fields: &std::collections::HashSet<String>,
2043    nested_types: &std::collections::HashMap<String, String>,
2044    nested_types_optional: bool,
2045    path_fields: &[String],
2046) -> String {
2047    let mut expr = format!("{}.builder()", type_name);
2048    for (key, val) in obj {
2049        // Convert snake_case key to camelCase for method name
2050        let camel_key = key.to_lower_camel_case();
2051        let method_name = format!("with{}", camel_key.to_upper_camel_case());
2052
2053        let java_val = match val {
2054            serde_json::Value::String(s) => {
2055                // Check if this field is an enum type by checking enum_fields.
2056                // Infer enum type name from camelCase field name by converting to UpperCamelCase.
2057                if enum_fields.contains(&camel_key) {
2058                    // Enum field: infer type name from field name (e.g., "codeBlockStyle" -> "CodeBlockStyle")
2059                    let enum_type_name = camel_key.to_upper_camel_case();
2060                    let variant_name = s.to_upper_camel_case();
2061                    format!("{}.{}", enum_type_name, variant_name)
2062                } else if camel_key == "preset" && type_name == "PreprocessingOptions" {
2063                    // Special case: preset field in PreprocessingOptions maps to PreprocessingPreset
2064                    let variant_name = s.to_upper_camel_case();
2065                    format!("PreprocessingPreset.{}", variant_name)
2066                } else if path_fields.contains(key) {
2067                    // Path field: wrap in Optional.of(java.nio.file.Path.of(...))
2068                    format!("Optional.of(java.nio.file.Path.of(\"{}\"))", escape_java(s))
2069                } else {
2070                    // String field: emit as a quoted literal
2071                    format!("\"{}\"", escape_java(s))
2072                }
2073            }
2074            serde_json::Value::Bool(b) => b.to_string(),
2075            serde_json::Value::Null => "null".to_string(),
2076            serde_json::Value::Number(n) => {
2077                // Number field: emit literal with type suffix.
2078                // Java records/classes use either `long` (primitive, not nullable) or
2079                // `Optional<Long>` (nullable). The codegen wraps in `Optional.of(...)`
2080                // by default since most options builder fields are Optional, but several
2081                // record types (e.g. SecurityLimits) use primitive `long` throughout.
2082                // Skip the wrap for: (a) known-primitive top-level fields and (b) any
2083                // method on a record type whose builder methods take primitives only.
2084                let camel_key = key.to_lower_camel_case();
2085                let is_plain_field = matches!(camel_key.as_str(), "listIndentWidth" | "wrapWidth");
2086                // Builders for typed-record nested config classes use primitives
2087                // throughout — they're not the optional-options pattern.
2088                let is_primitive_builder = matches!(type_name, "SecurityLimits" | "SecurityLimitsBuilder");
2089
2090                if is_plain_field || is_primitive_builder {
2091                    // Plain numeric field: no Optional wrapper
2092                    if n.is_f64() {
2093                        format!("{}d", n)
2094                    } else {
2095                        format!("{}L", n)
2096                    }
2097                } else {
2098                    // Optional numeric field: wrap in Optional.of()
2099                    if n.is_f64() {
2100                        format!("Optional.of({}d)", n)
2101                    } else {
2102                        format!("Optional.of({}L)", n)
2103                    }
2104                }
2105            }
2106            serde_json::Value::Array(arr) => {
2107                let items: Vec<String> = arr.iter().map(|v| json_to_java_typed(v, None)).collect();
2108                format!("java.util.List.of({})", items.join(", "))
2109            }
2110            serde_json::Value::Object(nested) => {
2111                // Recurse with the type from nested_types mapping, or default to snake_case → PascalCase + "Options".
2112                let nested_type = nested_types
2113                    .get(key.as_str())
2114                    .cloned()
2115                    .unwrap_or_else(|| format!("{}Options", key.to_upper_camel_case()));
2116                let inner = java_builder_expression(
2117                    nested,
2118                    &nested_type,
2119                    enum_fields,
2120                    nested_types,
2121                    nested_types_optional,
2122                    &[],
2123                );
2124                // Top-level config builders (e.g. ExtractionConfigBuilder) declare nested
2125                // record fields as `Optional<T>` (since they are nullable). Primitive-fields
2126                // builders (SecurityLimitsBuilder etc.) take the bare type directly.
2127                let is_primitive_builder = matches!(type_name, "SecurityLimits" | "SecurityLimitsBuilder");
2128                if is_primitive_builder || !nested_types_optional {
2129                    inner
2130                } else {
2131                    format!("Optional.of({inner})")
2132                }
2133            }
2134        };
2135        expr.push_str(&format!(".{}({})", method_name, java_val));
2136    }
2137    expr.push_str(".build()");
2138    expr
2139}
2140
2141/// Build default nested type mappings for Java extraction config types.
2142///
2143/// Maps known Kreuzberg/Kreuzcrawl config field names (in snake_case) to their
2144/// Java record type names (in PascalCase). These defaults allow e2e codegen to
2145/// automatically deserialize nested config objects without requiring explicit
2146/// configuration in alef.toml. User-provided overrides take precedence.
2147fn default_java_nested_types() -> std::collections::HashMap<String, String> {
2148    [
2149        ("chunking", "ChunkingConfig"),
2150        ("ocr", "OcrConfig"),
2151        ("images", "ImageExtractionConfig"),
2152        ("html_output", "HtmlOutputConfig"),
2153        ("language_detection", "LanguageDetectionConfig"),
2154        ("postprocessor", "PostProcessorConfig"),
2155        ("acceleration", "AccelerationConfig"),
2156        ("email", "EmailConfig"),
2157        ("pages", "PageConfig"),
2158        ("pdf_options", "PdfConfig"),
2159        ("layout", "LayoutDetectionConfig"),
2160        ("tree_sitter", "TreeSitterConfig"),
2161        ("structured_extraction", "StructuredExtractionConfig"),
2162        ("content_filter", "ContentFilterConfig"),
2163        ("token_reduction", "TokenReductionOptions"),
2164        ("security_limits", "SecurityLimits"),
2165    ]
2166    .iter()
2167    .map(|(k, v)| (k.to_string(), v.to_string()))
2168    .collect()
2169}
2170
2171// ---------------------------------------------------------------------------
2172// Import collection helpers
2173// ---------------------------------------------------------------------------
2174
2175/// Recursively collect enum types and nested option types used in a builder expression.
2176/// Enums are keyed in the enum_fields map by camelCase names (e.g., "codeBlockStyle" → "CodeBlockStyle").
2177#[allow(dead_code)]
2178fn collect_enum_and_nested_types(
2179    obj: &serde_json::Map<String, serde_json::Value>,
2180    enum_fields: &std::collections::HashMap<String, String>,
2181    types_out: &mut std::collections::BTreeSet<String>,
2182) {
2183    for (key, val) in obj {
2184        // enum_fields is keyed by camelCase, not snake_case.
2185        let camel_key = key.to_lower_camel_case();
2186        if let Some(enum_type) = enum_fields.get(&camel_key) {
2187            // Add the enum type from the mapping (e.g., "CodeBlockStyle").
2188            types_out.insert(enum_type.clone());
2189        } else if camel_key == "preset" {
2190            // Special case: preset field uses PreprocessingPreset enum.
2191            types_out.insert("PreprocessingPreset".to_string());
2192        }
2193        // Recurse into nested objects to find their nested enum types.
2194        if let Some(nested) = val.as_object() {
2195            collect_enum_and_nested_types(nested, enum_fields, types_out);
2196        }
2197    }
2198}
2199
2200fn collect_nested_type_names(
2201    obj: &serde_json::Map<String, serde_json::Value>,
2202    nested_types: &std::collections::HashMap<String, String>,
2203    types_out: &mut std::collections::BTreeSet<String>,
2204) {
2205    for (key, val) in obj {
2206        if let Some(type_name) = nested_types.get(key.as_str()) {
2207            types_out.insert(type_name.clone());
2208        }
2209        if let Some(nested) = val.as_object() {
2210            collect_nested_type_names(nested, nested_types, types_out);
2211        }
2212    }
2213}
2214
2215// ---------------------------------------------------------------------------
2216// Visitor generation
2217// ---------------------------------------------------------------------------
2218
2219/// Build a Java visitor class and add setup lines. Returns the visitor variable name.
2220fn build_java_visitor(
2221    setup_lines: &mut Vec<String>,
2222    visitor_spec: &crate::fixture::VisitorSpec,
2223    class_name: &str,
2224) -> String {
2225    setup_lines.push("class _TestVisitor implements Visitor {".to_string());
2226    for (method_name, action) in &visitor_spec.callbacks {
2227        emit_java_visitor_method(setup_lines, method_name, action, class_name);
2228    }
2229    setup_lines.push("}".to_string());
2230    setup_lines.push("var visitor = new _TestVisitor();".to_string());
2231    "visitor".to_string()
2232}
2233
2234/// Emit a Java visitor method for a callback action.
2235fn emit_java_visitor_method(
2236    setup_lines: &mut Vec<String>,
2237    method_name: &str,
2238    action: &CallbackAction,
2239    _class_name: &str,
2240) {
2241    let camel_method = method_to_camel(method_name);
2242    let params = match method_name {
2243        "visit_link" => "NodeContext ctx, String href, String text, String title",
2244        "visit_image" => "NodeContext ctx, String src, String alt, String title",
2245        "visit_heading" => "NodeContext ctx, int level, String text, String id",
2246        "visit_code_block" => "NodeContext ctx, String lang, String code",
2247        "visit_code_inline"
2248        | "visit_strong"
2249        | "visit_emphasis"
2250        | "visit_strikethrough"
2251        | "visit_underline"
2252        | "visit_subscript"
2253        | "visit_superscript"
2254        | "visit_mark"
2255        | "visit_button"
2256        | "visit_summary"
2257        | "visit_figcaption"
2258        | "visit_definition_term"
2259        | "visit_definition_description" => "NodeContext ctx, String text",
2260        "visit_text" => "NodeContext ctx, String text",
2261        "visit_list_item" => "NodeContext ctx, boolean ordered, String marker, String text",
2262        "visit_blockquote" => "NodeContext ctx, String content, long depth",
2263        "visit_table_row" => "NodeContext ctx, java.util.List<String> cells, boolean isHeader",
2264        "visit_custom_element" => "NodeContext ctx, String tagName, String html",
2265        "visit_form" => "NodeContext ctx, String actionUrl, String method",
2266        "visit_input" => "NodeContext ctx, String inputType, String name, String value",
2267        "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, String src",
2268        "visit_details" => "NodeContext ctx, boolean isOpen",
2269        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2270            "NodeContext ctx, String output"
2271        }
2272        "visit_list_start" => "NodeContext ctx, boolean ordered",
2273        "visit_list_end" => "NodeContext ctx, boolean ordered, String output",
2274        _ => "NodeContext ctx",
2275    };
2276
2277    // Determine action type and values for template
2278    let (action_type, action_value, format_args) = match action {
2279        CallbackAction::Skip => ("skip", String::new(), Vec::new()),
2280        CallbackAction::Continue => ("continue", String::new(), Vec::new()),
2281        CallbackAction::PreserveHtml => ("preserve_html", String::new(), Vec::new()),
2282        CallbackAction::Custom { output } => ("custom_literal", escape_java(output), Vec::new()),
2283        CallbackAction::CustomTemplate { template, .. } => {
2284            // Extract {placeholder} names from the template (in order of appearance).
2285            let mut format_str = String::with_capacity(template.len());
2286            let mut format_args: Vec<String> = Vec::new();
2287            let mut chars = template.chars().peekable();
2288            while let Some(ch) = chars.next() {
2289                if ch == '{' {
2290                    // Collect identifier chars until '}'.
2291                    let mut name = String::new();
2292                    let mut closed = false;
2293                    for inner in chars.by_ref() {
2294                        if inner == '}' {
2295                            closed = true;
2296                            break;
2297                        }
2298                        name.push(inner);
2299                    }
2300                    if closed && !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
2301                        let camel_name = name.as_str().to_lower_camel_case();
2302                        format_args.push(camel_name);
2303                        format_str.push_str("%s");
2304                    } else {
2305                        // Not a simple placeholder — emit literally.
2306                        format_str.push('{');
2307                        format_str.push_str(&name);
2308                        if closed {
2309                            format_str.push('}');
2310                        }
2311                    }
2312                } else {
2313                    format_str.push(ch);
2314                }
2315            }
2316            let escaped = escape_java(&format_str);
2317            if format_args.is_empty() {
2318                ("custom_literal", escaped, Vec::new())
2319            } else {
2320                ("custom_formatted", escaped, format_args)
2321            }
2322        }
2323    };
2324
2325    let params = params.to_string();
2326
2327    let rendered = crate::template_env::render(
2328        "java/visitor_method.jinja",
2329        minijinja::context! {
2330            camel_method,
2331            params,
2332            action_type,
2333            action_value,
2334            format_args => format_args,
2335        },
2336    );
2337    setup_lines.push(rendered);
2338}
2339
2340/// Convert snake_case method names to Java camelCase.
2341fn method_to_camel(snake: &str) -> String {
2342    snake.to_lower_camel_case()
2343}
2344
2345#[cfg(test)]
2346mod tests {
2347    use crate::config::{CallConfig, E2eConfig, SelectWhen};
2348    use crate::fixture::Fixture;
2349    use std::collections::HashMap;
2350
2351    fn make_fixture_with_input(id: &str, input: serde_json::Value) -> Fixture {
2352        Fixture {
2353            id: id.to_string(),
2354            category: None,
2355            description: "test fixture".to_string(),
2356            tags: vec![],
2357            skip: None,
2358            env: None,
2359            call: None,
2360            input,
2361            mock_response: None,
2362            source: String::new(),
2363            http: None,
2364            assertions: vec![],
2365            visitor: None,
2366        }
2367    }
2368
2369    /// Test that resolve_call_for_fixture correctly routes to batchScrape
2370    /// when input has batch_urls and select_when condition matches.
2371    #[test]
2372    fn test_java_select_when_routes_to_batch_scrape() {
2373        let mut calls = HashMap::new();
2374        calls.insert(
2375            "batch_scrape".to_string(),
2376            CallConfig {
2377                function: "batchScrape".to_string(),
2378                module: "com.example.kreuzcrawl".to_string(),
2379                select_when: Some(SelectWhen::InputHas("batch_urls".to_string())),
2380                ..CallConfig::default()
2381            },
2382        );
2383
2384        let e2e_config = E2eConfig {
2385            call: CallConfig {
2386                function: "scrape".to_string(),
2387                module: "com.example.kreuzcrawl".to_string(),
2388                ..CallConfig::default()
2389            },
2390            calls,
2391            ..E2eConfig::default()
2392        };
2393
2394        // Fixture with batch_urls but no explicit call field should route to batch_scrape
2395        let fixture = make_fixture_with_input("batch_empty_urls", serde_json::json!({ "batch_urls": [] }));
2396
2397        let resolved_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
2398        assert_eq!(resolved_call.function, "batchScrape");
2399
2400        // Fixture without batch_urls should fall back to default scrape
2401        let fixture_no_batch =
2402            make_fixture_with_input("simple_scrape", serde_json::json!({ "url": "https://example.com" }));
2403        let resolved_default =
2404            e2e_config.resolve_call_for_fixture(fixture_no_batch.call.as_deref(), &fixture_no_batch.input);
2405        assert_eq!(resolved_default.function, "scrape");
2406    }
2407}