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