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