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