Skip to main content

alef_e2e/codegen/
java.rs

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