Skip to main content

alef_e2e/codegen/
java.rs

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