Skip to main content

alef_e2e/codegen/
java.rs

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