Skip to main content

alef_e2e/codegen/
csharp.rs

1//! C# e2e test generator using xUnit.
2//!
3//! Generates `e2e/csharp/E2eTests.csproj` and `tests/{Category}Tests.cs`
4//! files from JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::config::E2eConfig;
7use crate::escape::{escape_csharp, sanitize_filename, sanitize_ident};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
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::ToUpperCamelCase;
16use std::collections::HashMap;
17use std::fmt::Write as FmtWrite;
18use std::hash::{Hash, Hasher};
19use std::path::PathBuf;
20
21use super::E2eCodegen;
22use super::client;
23
24/// C# e2e code generator.
25pub struct CSharpCodegen;
26
27impl E2eCodegen for CSharpCodegen {
28    fn generate(
29        &self,
30        groups: &[FixtureGroup],
31        e2e_config: &E2eConfig,
32        config: &ResolvedCrateConfig,
33        _type_defs: &[alef_core::ir::TypeDef],
34    ) -> Result<Vec<GeneratedFile>> {
35        let lang = self.language_name();
36        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38        let mut files = Vec::new();
39
40        // Resolve call config with overrides.
41        let call = &e2e_config.call;
42        let overrides = call.overrides.get(lang);
43        let function_name = overrides
44            .and_then(|o| o.function.as_ref())
45            .cloned()
46            .unwrap_or_else(|| call.function.to_upper_camel_case());
47        let class_name = overrides
48            .and_then(|o| o.class.as_ref())
49            .cloned()
50            .unwrap_or_else(|| format!("{}Lib", config.name.to_upper_camel_case()));
51        // The exception class is always {CrateName}Exception, generated by the C# backend.
52        let exception_class = format!("{}Exception", config.name.to_upper_camel_case());
53        let namespace = overrides
54            .and_then(|o| o.module.as_ref())
55            .cloned()
56            .or_else(|| config.csharp.as_ref().and_then(|cs| cs.namespace.clone()))
57            .unwrap_or_else(|| {
58                if call.module.is_empty() {
59                    "Kreuzberg".to_string()
60                } else {
61                    call.module.to_upper_camel_case()
62                }
63            });
64        let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
65        let result_var = &call.result_var;
66        let is_async = call.r#async;
67
68        // Resolve package config.
69        let cs_pkg = e2e_config.resolve_package("csharp");
70        let pkg_name = cs_pkg
71            .as_ref()
72            .and_then(|p| p.name.as_ref())
73            .cloned()
74            .unwrap_or_else(|| config.name.to_upper_camel_case());
75        // Alef scaffolds C# packages as packages/csharp/<Namespace>/<Namespace>.csproj.
76        let pkg_path = cs_pkg
77            .as_ref()
78            .and_then(|p| p.path.as_ref())
79            .cloned()
80            .unwrap_or_else(|| format!("../../packages/csharp/{pkg_name}/{pkg_name}.csproj"));
81        let pkg_version = cs_pkg
82            .as_ref()
83            .and_then(|p| p.version.as_ref())
84            .cloned()
85            .or_else(|| config.resolved_version())
86            .unwrap_or_else(|| "0.1.0".to_string());
87
88        // Generate the .csproj using a unique name derived from the package name so
89        // it does not conflict with any hand-written project files in the same directory.
90        let csproj_name = format!("{pkg_name}.E2eTests.csproj");
91        files.push(GeneratedFile {
92            path: output_base.join(&csproj_name),
93            content: render_csproj(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
94            generated_header: false,
95        });
96
97        // Detect whether any fixture needs the mock-server (HTTP fixtures or
98        // fixtures with a `mock_response`). When present, the generated
99        // TestSetup.cs will spawn the mock-server via [ModuleInitializer]
100        // before any test loads — mirroring the Ruby spec_helper / Python
101        // conftest spawn pattern. Without this, every fixture-bound test
102        // failed with `LiterLlmException : builder error` because reqwest
103        // rejected the relative URL when MOCK_SERVER_URL was unset.
104        let needs_mock_server = groups
105            .iter()
106            .flat_map(|g| g.fixtures.iter())
107            .any(|f| f.needs_mock_server());
108
109        // Emit a TestSetup.cs whose ModuleInitializer chdirs to test_documents
110        // so fixture-relative paths like "docx/fake.docx" resolve correctly when
111        // dotnet test runs from bin/{Configuration}/{Tfm}, and (when fixtures
112        // need it) spawns the mock-server binary.
113        files.push(GeneratedFile {
114            path: output_base.join("TestSetup.cs"),
115            content: render_test_setup(needs_mock_server, &e2e_config.test_documents_dir),
116            generated_header: true,
117        });
118
119        // Generate test files per category.
120        let tests_base = output_base.join("tests");
121        let field_resolver = FieldResolver::new(
122            &e2e_config.fields,
123            &e2e_config.fields_optional,
124            &e2e_config.result_fields,
125            &e2e_config.fields_array,
126            &std::collections::HashSet::new(),
127        );
128
129        // Resolve enum_fields and nested_types from C# override config.
130        static EMPTY_ENUM_FIELDS: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
131        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);
132
133        // Build effective nested_types by merging defaults with configured overrides.
134        let mut effective_nested_types = default_csharp_nested_types();
135        if let Some(overrides_map) = overrides.map(|o| &o.nested_types) {
136            effective_nested_types.extend(overrides_map.clone());
137        }
138
139        for group in groups {
140            let active: Vec<&Fixture> = group
141                .fixtures
142                .iter()
143                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
144                .collect();
145
146            if active.is_empty() {
147                continue;
148            }
149
150            let test_class = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
151            let filename = format!("{test_class}.cs");
152            let content = render_test_file(
153                &group.category,
154                &active,
155                &namespace,
156                &class_name,
157                &function_name,
158                &exception_class,
159                result_var,
160                &test_class,
161                &e2e_config.call.args,
162                &field_resolver,
163                result_is_simple,
164                is_async,
165                e2e_config,
166                enum_fields,
167                &effective_nested_types,
168            );
169            files.push(GeneratedFile {
170                path: tests_base.join(filename),
171                content,
172                generated_header: true,
173            });
174        }
175
176        Ok(files)
177    }
178
179    fn language_name(&self) -> &'static str {
180        "csharp"
181    }
182}
183
184// ---------------------------------------------------------------------------
185// Rendering
186// ---------------------------------------------------------------------------
187
188fn render_csproj(pkg_name: &str, pkg_path: &str, pkg_version: &str, dep_mode: crate::config::DependencyMode) -> String {
189    let pkg_ref = match dep_mode {
190        crate::config::DependencyMode::Registry => {
191            format!("    <PackageReference Include=\"{pkg_name}\" Version=\"{pkg_version}\" />")
192        }
193        crate::config::DependencyMode::Local => {
194            format!("    <ProjectReference Include=\"{pkg_path}\" />")
195        }
196    };
197    crate::template_env::render(
198        "csharp/csproj.jinja",
199        minijinja::context! {
200            pkg_ref => pkg_ref,
201            microsoft_net_test_sdk_version => tv::nuget::MICROSOFT_NET_TEST_SDK,
202            xunit_version => tv::nuget::XUNIT,
203            xunit_runner_version => tv::nuget::XUNIT_RUNNER_VISUALSTUDIO,
204        },
205    )
206}
207
208fn render_test_setup(needs_mock_server: bool, test_documents_dir: &str) -> String {
209    let mut out = String::new();
210    out.push_str(&hash::header(CommentStyle::DoubleSlash));
211    out.push_str("using System;\n");
212    out.push_str("using System.IO;\n");
213    if needs_mock_server {
214        out.push_str("using System.Diagnostics;\n");
215    }
216    out.push_str("using System.Runtime.CompilerServices;\n\n");
217    out.push_str("namespace Kreuzberg.E2eTests;\n\n");
218    out.push_str("internal static class TestSetup\n");
219    out.push_str("{\n");
220    if needs_mock_server {
221        out.push_str("    private static Process? _mockServer;\n\n");
222    }
223    out.push_str("    [ModuleInitializer]\n");
224    out.push_str("    internal static void Init()\n");
225    out.push_str("    {\n");
226    let _ = writeln!(
227        out,
228        "        // Walk up from the assembly directory until we find the repo root"
229    );
230    let _ = writeln!(
231        out,
232        "        // (the directory containing {test_documents_dir}/) so that fixture paths"
233    );
234    out.push_str("        // like \"docx/fake.docx\" resolve regardless of where dotnet test\n");
235    out.push_str("        // launched the runner from.\n");
236    out.push_str("        var dir = new DirectoryInfo(AppContext.BaseDirectory);\n");
237    out.push_str("        DirectoryInfo? repoRoot = null;\n");
238    out.push_str("        while (dir != null)\n");
239    out.push_str("        {\n");
240    let _ = writeln!(
241        out,
242        "            var candidate = Path.Combine(dir.FullName, \"{test_documents_dir}\");"
243    );
244    out.push_str("            if (Directory.Exists(candidate))\n");
245    out.push_str("            {\n");
246    out.push_str("                repoRoot = dir;\n");
247    out.push_str("                Directory.SetCurrentDirectory(candidate);\n");
248    out.push_str("                break;\n");
249    out.push_str("            }\n");
250    out.push_str("            dir = dir.Parent;\n");
251    out.push_str("        }\n");
252    if needs_mock_server {
253        out.push('\n');
254        out.push_str("        // Spawn the mock-server binary before any test loads, mirroring the\n");
255        out.push_str("        // Ruby spec_helper / Python conftest pattern. Honors a pre-set\n");
256        out.push_str("        // MOCK_SERVER_URL (e.g. set by `task` or CI) by skipping the spawn.\n");
257        out.push_str("        // Without this, every fixture-bound test failed with\n");
258        out.push_str("        // `<Lib>Exception : builder error` because reqwest rejected the\n");
259        out.push_str("        // relative URL produced by `\"\" + \"/fixtures/<id>\"`.\n");
260        out.push_str("        var preset = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\");\n");
261        out.push_str("        if (!string.IsNullOrEmpty(preset))\n");
262        out.push_str("        {\n");
263        out.push_str("            return;\n");
264        out.push_str("        }\n");
265        out.push_str("        if (repoRoot == null)\n");
266        out.push_str("        {\n");
267        let _ = writeln!(
268            out,
269            "            throw new InvalidOperationException(\"TestSetup: could not locate repo root ({test_documents_dir}/ not found)\");"
270        );
271        out.push_str("        }\n");
272        out.push_str("        var bin = Path.Combine(\n");
273        out.push_str("            repoRoot.FullName,\n");
274        out.push_str("            \"e2e\", \"rust\", \"target\", \"release\", \"mock-server\");\n");
275        out.push_str("        if (OperatingSystem.IsWindows())\n");
276        out.push_str("        {\n");
277        out.push_str("            bin += \".exe\";\n");
278        out.push_str("        }\n");
279        out.push_str("        var fixturesDir = Path.Combine(repoRoot.FullName, \"fixtures\");\n");
280        out.push_str("        if (!File.Exists(bin))\n");
281        out.push_str("        {\n");
282        out.push_str("            throw new InvalidOperationException(\n");
283        out.push_str("                $\"TestSetup: mock-server binary not found at {bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release\");\n");
284        out.push_str("        }\n");
285        out.push_str("        var psi = new ProcessStartInfo\n");
286        out.push_str("        {\n");
287        out.push_str("            FileName = bin,\n");
288        out.push_str("            Arguments = $\"\\\"{fixturesDir}\\\"\",\n");
289        out.push_str("            RedirectStandardInput = true,\n");
290        out.push_str("            RedirectStandardOutput = true,\n");
291        out.push_str("            RedirectStandardError = true,\n");
292        out.push_str("            UseShellExecute = false,\n");
293        out.push_str("        };\n");
294        out.push_str("        _mockServer = Process.Start(psi)\n");
295        out.push_str(
296            "            ?? throw new InvalidOperationException(\"TestSetup: failed to start mock-server\");\n",
297        );
298        out.push_str("        // The mock-server prints MOCK_SERVER_URL=<url>, then optionally\n");
299        out.push_str("        // MOCK_SERVERS={...} for host-root fixtures. Read up to 16 lines.\n");
300        out.push_str("        string? url = null;\n");
301        out.push_str("        for (int i = 0; i < 16; i++)\n");
302        out.push_str("        {\n");
303        out.push_str("            var line = _mockServer.StandardOutput.ReadLine();\n");
304        out.push_str("            if (line == null)\n");
305        out.push_str("            {\n");
306        out.push_str("                break;\n");
307        out.push_str("            }\n");
308        out.push_str("            const string urlPrefix = \"MOCK_SERVER_URL=\";\n");
309        out.push_str("            const string serversPrefix = \"MOCK_SERVERS=\";\n");
310        out.push_str("            if (line.StartsWith(urlPrefix, StringComparison.Ordinal))\n");
311        out.push_str("            {\n");
312        out.push_str("                url = line.Substring(urlPrefix.Length).Trim();\n");
313        out.push_str("            }\n");
314        out.push_str("            else if (line.StartsWith(serversPrefix, StringComparison.Ordinal))\n");
315        out.push_str("            {\n");
316        out.push_str("                var jsonVal = line.Substring(serversPrefix.Length).Trim();\n");
317        out.push_str("                Environment.SetEnvironmentVariable(\"MOCK_SERVERS\", jsonVal);\n");
318        out.push_str("                // Parse JSON map and set per-fixture env vars (MOCK_SERVER_<FIXTURE_ID>).\n");
319        out.push_str("                var matches = System.Text.RegularExpressions.Regex.Matches(\n");
320        out.push_str("                    jsonVal, \"\\\"([^\\\"]+)\\\":\\\"([^\\\"]+)\\\"\");\n");
321        out.push_str("                foreach (System.Text.RegularExpressions.Match m in matches)\n");
322        out.push_str("                {\n");
323        out.push_str("                    Environment.SetEnvironmentVariable(\n");
324        out.push_str("                        \"MOCK_SERVER_\" + m.Groups[1].Value.ToUpperInvariant(),\n");
325        out.push_str("                        m.Groups[2].Value);\n");
326        out.push_str("                }\n");
327        out.push_str("                break;\n");
328        out.push_str("            }\n");
329        out.push_str("            else if (url != null)\n");
330        out.push_str("            {\n");
331        out.push_str("                break;\n");
332        out.push_str("            }\n");
333        out.push_str("        }\n");
334        out.push_str("        if (string.IsNullOrEmpty(url))\n");
335        out.push_str("        {\n");
336        out.push_str("            try { _mockServer.Kill(true); } catch { }\n");
337        out.push_str("            throw new InvalidOperationException(\"TestSetup: mock-server did not emit MOCK_SERVER_URL\");\n");
338        out.push_str("        }\n");
339        out.push_str("        Environment.SetEnvironmentVariable(\"MOCK_SERVER_URL\", url);\n");
340        out.push_str("        // TCP-readiness probe: ensure axum::serve is accepting before tests start.\n");
341        out.push_str("        // The mock-server binds the TcpListener synchronously then prints the URL\n");
342        out.push_str("        // before tokio::spawn(axum::serve(...)) is polled, so under xUnit\n");
343        out.push_str("        // class-parallel default tests can race startup. Poll-connect (max 5s,\n");
344        out.push_str("        // 50ms backoff) until success.\n");
345        out.push_str("        var healthUri = new System.Uri(url);\n");
346        out.push_str("        var deadline = System.Diagnostics.Stopwatch.StartNew();\n");
347        out.push_str("        while (deadline.ElapsedMilliseconds < 5000)\n");
348        out.push_str("        {\n");
349        out.push_str("            try\n");
350        out.push_str("            {\n");
351        out.push_str("                using var probe = new System.Net.Sockets.TcpClient();\n");
352        out.push_str("                var task = probe.ConnectAsync(healthUri.Host, healthUri.Port);\n");
353        out.push_str("                if (task.Wait(100) && probe.Connected) { break; }\n");
354        out.push_str("            }\n");
355        out.push_str("            catch (System.Exception) { }\n");
356        out.push_str("            System.Threading.Thread.Sleep(50);\n");
357        out.push_str("        }\n");
358        out.push_str("        // Drain stdout/stderr so the child does not block on a full pipe.\n");
359        out.push_str("        var server = _mockServer;\n");
360        out.push_str("        var stdoutThread = new System.Threading.Thread(() =>\n");
361        out.push_str("        {\n");
362        out.push_str("            try { server.StandardOutput.ReadToEnd(); } catch { }\n");
363        out.push_str("        }) { IsBackground = true };\n");
364        out.push_str("        stdoutThread.Start();\n");
365        out.push_str("        var stderrThread = new System.Threading.Thread(() =>\n");
366        out.push_str("        {\n");
367        out.push_str("            try { server.StandardError.ReadToEnd(); } catch { }\n");
368        out.push_str("        }) { IsBackground = true };\n");
369        out.push_str("        stderrThread.Start();\n");
370        out.push_str("        // Tear the child down on assembly unload / process exit by closing\n");
371        out.push_str("        // its stdin (the mock-server treats stdin EOF as a shutdown signal).\n");
372        out.push_str("        AppDomain.CurrentDomain.ProcessExit += (_, _) =>\n");
373        out.push_str("        {\n");
374        out.push_str("            try { _mockServer.StandardInput.Close(); } catch { }\n");
375        out.push_str("            try { if (!_mockServer.WaitForExit(2000)) { _mockServer.Kill(true); } } catch { }\n");
376        out.push_str("        };\n");
377    }
378    out.push_str("    }\n");
379    out.push_str("}\n");
380    out
381}
382
383#[allow(clippy::too_many_arguments)]
384fn render_test_file(
385    category: &str,
386    fixtures: &[&Fixture],
387    namespace: &str,
388    class_name: &str,
389    function_name: &str,
390    exception_class: &str,
391    result_var: &str,
392    test_class: &str,
393    args: &[crate::config::ArgMapping],
394    field_resolver: &FieldResolver,
395    result_is_simple: bool,
396    is_async: bool,
397    e2e_config: &E2eConfig,
398    enum_fields: &HashMap<String, String>,
399    nested_types: &HashMap<String, String>,
400) -> String {
401    // Collect using imports
402    let mut using_imports = String::new();
403    using_imports.push_str("using System;\n");
404    using_imports.push_str("using System.Collections.Generic;\n");
405    using_imports.push_str("using System.Linq;\n");
406    using_imports.push_str("using System.Net.Http;\n");
407    using_imports.push_str("using System.Text;\n");
408    using_imports.push_str("using System.Text.Json;\n");
409    using_imports.push_str("using System.Text.Json.Serialization;\n");
410    using_imports.push_str("using System.Threading.Tasks;\n");
411    using_imports.push_str("using Xunit;\n");
412    using_imports.push_str(&format!("using {namespace};\n"));
413    using_imports.push_str(&format!("using static {namespace}.{class_name};\n"));
414
415    // Shared options field
416    let config_options_field = "    private static readonly JsonSerializerOptions ConfigOptions = new() { Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault };";
417
418    // Visitor class declarations accumulated across all fixtures — emitted as
419    // private nested classes inside the test class but outside any method body.
420    // C# does not allow local class declarations inside method bodies.
421    let mut visitor_class_decls: Vec<String> = Vec::new();
422
423    // Build fixtures body
424    let mut fixtures_body = String::new();
425    for (i, fixture) in fixtures.iter().enumerate() {
426        render_test_method(
427            &mut fixtures_body,
428            &mut visitor_class_decls,
429            fixture,
430            class_name,
431            function_name,
432            exception_class,
433            result_var,
434            args,
435            field_resolver,
436            result_is_simple,
437            is_async,
438            e2e_config,
439            enum_fields,
440            nested_types,
441        );
442        if i + 1 < fixtures.len() {
443            fixtures_body.push('\n');
444        }
445    }
446
447    // Build visitor classes string
448    let mut visitor_classes_str = String::new();
449    for (i, decl) in visitor_class_decls.iter().enumerate() {
450        if i > 0 {
451            visitor_classes_str.push('\n');
452        }
453        visitor_classes_str.push('\n');
454        // Indent each line by 4 spaces to nest inside the test class
455        for line in decl.lines() {
456            visitor_classes_str.push_str("    ");
457            visitor_classes_str.push_str(line);
458            visitor_classes_str.push('\n');
459        }
460    }
461
462    let ctx = minijinja::context! {
463        header => hash::header(CommentStyle::DoubleSlash),
464        using_imports => using_imports,
465        category => category,
466        namespace => namespace,
467        test_class => test_class,
468        config_options_field => config_options_field,
469        fixtures_body => fixtures_body,
470        visitor_class_decls => visitor_classes_str,
471    };
472
473    crate::template_env::render("csharp/test_file.jinja", ctx)
474}
475
476// ---------------------------------------------------------------------------
477// HTTP test rendering — shared-driver integration
478// ---------------------------------------------------------------------------
479
480/// Renderer that emits xUnit `[Fact] public async Task Test_*()` methods using
481/// `System.Net.Http.HttpClient` against the mock server at `MOCK_SERVER_URL`.
482/// Satisfies [`client::TestClientRenderer`] so the shared
483/// [`client::http_call::render_http_test`] driver drives the call sequence.
484struct CSharpTestClientRenderer;
485
486/// C# HttpMethod static properties are PascalCase (Get, Post, Put, Delete, …).
487fn to_csharp_http_method(method: &str) -> String {
488    let lower = method.to_ascii_lowercase();
489    let mut chars = lower.chars();
490    match chars.next() {
491        Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
492        None => String::new(),
493    }
494}
495
496/// Headers that belong to `request.Content.Headers` rather than `request.Headers`.
497///
498/// Adding these to `request.Headers` causes .NET to throw "Misused header name".
499const CSHARP_RESTRICTED_REQUEST_HEADERS: &[&str] = &[
500    "content-length",
501    "host",
502    "connection",
503    "expect",
504    "transfer-encoding",
505    "upgrade",
506    // Content-Type is owned by request.Content.Headers and is set when
507    // StringContent is constructed; adding it to request.Headers throws.
508    "content-type",
509    // Other entity headers also belong to request.Content.Headers.
510    "content-encoding",
511    "content-language",
512    "content-location",
513    "content-md5",
514    "content-range",
515    "content-disposition",
516];
517
518/// Whether `name` (any case) belongs to `response.Content.Headers` rather than
519/// `response.Headers`. Picking the wrong collection causes .NET to throw
520/// "Misused header name".
521fn is_csharp_content_header(name: &str) -> bool {
522    matches!(
523        name.to_ascii_lowercase().as_str(),
524        "content-type"
525            | "content-length"
526            | "content-encoding"
527            | "content-language"
528            | "content-location"
529            | "content-md5"
530            | "content-range"
531            | "content-disposition"
532            | "expires"
533            | "last-modified"
534            | "allow"
535    )
536}
537
538impl client::TestClientRenderer for CSharpTestClientRenderer {
539    fn language_name(&self) -> &'static str {
540        "csharp"
541    }
542
543    /// Convert a fixture id to the PascalCase identifier used in `Test_{name}`.
544    fn sanitize_test_name(&self, id: &str) -> String {
545        id.to_upper_camel_case()
546    }
547
548    /// Emit `[Fact]` (or `[Fact(Skip = "…")]` for skipped tests), the method
549    /// signature, the opening brace, and the description comment.
550    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
551        let escaped_reason = skip_reason.map(escape_csharp);
552        let rendered = crate::template_env::render(
553            "csharp/http_test_open.jinja",
554            minijinja::context! {
555                fn_name => fn_name,
556                description => description,
557                skip_reason => escaped_reason,
558            },
559        );
560        out.push_str(&rendered);
561    }
562
563    /// Emit the closing `}` for a test method.
564    fn render_test_close(&self, out: &mut String) {
565        let rendered = crate::template_env::render("csharp/http_test_close.jinja", minijinja::context! {});
566        out.push_str(&rendered);
567    }
568
569    /// Emit the `HttpRequestMessage` construction, headers, cookies, body, and
570    /// `var response = await client.SendAsync(request)`.
571    ///
572    /// The fixture path follows the mock-server convention `/fixtures/<id>`.
573    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
574        let method = to_csharp_http_method(ctx.method);
575        let path = escape_csharp(ctx.path);
576
577        out.push_str("        var baseUrl = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? \"http://localhost:8080\";\n");
578        // Disable auto-follow so redirect-status fixtures (3xx) can assert the
579        // server's status code rather than the followed-target's status.
580        out.push_str(
581            "        using var handler = new System.Net.Http.HttpClientHandler { AllowAutoRedirect = false };\n",
582        );
583        out.push_str("        using var client = new System.Net.Http.HttpClient(handler);\n");
584        out.push_str(&format!("        var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.{method}, $\"{{baseUrl}}{path}\");\n"));
585
586        // Set body + Content-Type when a request body is present.
587        if let Some(body) = ctx.body {
588            let content_type = ctx.content_type.unwrap_or("application/json");
589            let json_str = serde_json::to_string(body).unwrap_or_default();
590            let escaped = escape_csharp(&json_str);
591            out.push_str(&format!("        request.Content = new System.Net.Http.StringContent(\"{escaped}\", System.Text.Encoding.UTF8, \"{content_type}\");\n"));
592        }
593
594        // Add request headers (skip restricted headers that belong to Content.Headers).
595        for (name, value) in ctx.headers {
596            if CSHARP_RESTRICTED_REQUEST_HEADERS.contains(&name.to_lowercase().as_str()) {
597                continue;
598            }
599            let escaped_name = escape_csharp(name);
600            let escaped_value = escape_csharp(value);
601            out.push_str(&format!(
602                "        request.Headers.Add(\"{escaped_name}\", \"{escaped_value}\");\n"
603            ));
604        }
605
606        // Combine cookies into a single `Cookie` header.
607        if !ctx.cookies.is_empty() {
608            let mut pairs: Vec<String> = ctx.cookies.iter().map(|(k, v)| format!("{k}={v}")).collect();
609            pairs.sort();
610            let cookie_header = escape_csharp(&pairs.join("; "));
611            out.push_str(&format!(
612                "        request.Headers.Add(\"Cookie\", \"{cookie_header}\");\n"
613            ));
614        }
615
616        out.push_str("        var response = await client.SendAsync(request);\n");
617    }
618
619    /// Emit `Assert.Equal(status, (int)response.StatusCode)`.
620    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
621        out.push_str(&format!("        Assert.Equal({status}, (int)response.StatusCode);\n"));
622    }
623
624    /// Emit a response-header assertion.
625    ///
626    /// Handles special tokens: `<<present>>`, `<<absent>>`, `<<uuid>>`.
627    /// Picks `response.Content.Headers` vs `response.Headers` based on the header name.
628    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
629        let target = if is_csharp_content_header(name) {
630            "response.Content.Headers"
631        } else {
632            "response.Headers"
633        };
634        let escaped_name = escape_csharp(name);
635        match expected {
636            "<<present>>" => {
637                out.push_str(&format!("        Assert.True({target}.Contains(\"{escaped_name}\"), \"expected header {escaped_name} to be present\");\n"));
638            }
639            "<<absent>>" => {
640                out.push_str(&format!("        Assert.False({target}.Contains(\"{escaped_name}\"), \"expected header {escaped_name} to be absent\");\n"));
641            }
642            "<<uuid>>" => {
643                // UUID regex: 8-4-4-4-12 hex groups.
644                out.push_str(&format!("        Assert.True({target}.TryGetValues(\"{escaped_name}\", out var _uuidHdr) && System.Text.RegularExpressions.Regex.IsMatch(string.Join(\", \", _uuidHdr), @\"^[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} is not a UUID\");\n"));
645            }
646            literal => {
647                // Use a deterministic local-variable name derived from the header name so
648                // multiple header assertions in the same method body do not redeclare.
649                let var_name = format!("hdr{}", sanitize_ident(name));
650                let escaped_value = escape_csharp(literal);
651                out.push_str(&format!("        Assert.True({target}.TryGetValues(\"{escaped_name}\", out var {var_name}) && {var_name}.Any(v => v.Contains(\"{escaped_value}\")), \"header {escaped_name} mismatch\");\n"));
652            }
653        }
654    }
655
656    /// Emit a JSON body equality assertion via `JsonDocument`.
657    ///
658    /// Plain-string bodies are compared with `Assert.Equal` after trimming.
659    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
660        match expected {
661            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
662                let json_str = serde_json::to_string(expected).unwrap_or_default();
663                let escaped = escape_csharp(&json_str);
664                out.push_str("        var bodyText = await response.Content.ReadAsStringAsync();\n");
665                out.push_str("        var body = JsonDocument.Parse(bodyText).RootElement;\n");
666                out.push_str(&format!(
667                    "        var expectedBody = JsonDocument.Parse(\"{escaped}\").RootElement;\n"
668                ));
669                out.push_str("        Assert.Equal(expectedBody.GetRawText(), body.GetRawText());\n");
670            }
671            serde_json::Value::String(s) => {
672                let escaped = escape_csharp(s);
673                out.push_str("        var bodyText = await response.Content.ReadAsStringAsync();\n");
674                out.push_str(&format!("        Assert.Equal(\"{escaped}\", bodyText.Trim());\n"));
675            }
676            other => {
677                let escaped = escape_csharp(&other.to_string());
678                out.push_str("        var bodyText = await response.Content.ReadAsStringAsync();\n");
679                out.push_str(&format!("        Assert.Equal(\"{escaped}\", bodyText.Trim());\n"));
680            }
681        }
682    }
683
684    /// Emit per-field equality assertions for a partial body match.
685    ///
686    /// Uses a separate `partialBodyText` local so it does not collide with
687    /// `bodyText` if `render_assert_json_body` was also called.
688    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
689        if let Some(obj) = expected.as_object() {
690            out.push_str("        var partialBodyText = await response.Content.ReadAsStringAsync();\n");
691            out.push_str("        var partialBody = JsonDocument.Parse(partialBodyText).RootElement;\n");
692            for (key, val) in obj {
693                let escaped_key = escape_csharp(key);
694                let json_str = serde_json::to_string(val).unwrap_or_default();
695                let escaped_val = escape_csharp(&json_str);
696                let var_name = format!("expected{}", key.to_upper_camel_case());
697                out.push_str(&format!(
698                    "        var {var_name} = JsonDocument.Parse(\"{escaped_val}\").RootElement;\n"
699                ));
700                out.push_str(&format!("        Assert.True(partialBody.TryGetProperty(\"{escaped_key}\", out var _partialProp{var_name}) && _partialProp{var_name}.GetRawText() == {var_name}.GetRawText(), \"partial body field '{escaped_key}' mismatch\");\n"));
701            }
702        }
703    }
704
705    /// Emit validation-error assertions by checking each expected `msg` string
706    /// appears in the JSON-encoded body.
707    fn render_assert_validation_errors(
708        &self,
709        out: &mut String,
710        _response_var: &str,
711        errors: &[ValidationErrorExpectation],
712    ) {
713        out.push_str("        var validationBodyText = await response.Content.ReadAsStringAsync();\n");
714        for err in errors {
715            let escaped_msg = escape_csharp(&err.msg);
716            out.push_str(&format!(
717                "        Assert.Contains(\"{escaped_msg}\", validationBodyText);\n"
718            ));
719        }
720    }
721}
722
723/// Render an HTTP server test method using the shared [`client::http_call::render_http_test`]
724/// driver via [`CSharpTestClientRenderer`].
725fn render_http_test_method(out: &mut String, fixture: &Fixture, _http: &HttpFixture) {
726    client::http_call::render_http_test(out, &CSharpTestClientRenderer, fixture);
727}
728
729#[allow(clippy::too_many_arguments)]
730fn render_test_method(
731    out: &mut String,
732    visitor_class_decls: &mut Vec<String>,
733    fixture: &Fixture,
734    class_name: &str,
735    _function_name: &str,
736    exception_class: &str,
737    _result_var: &str,
738    _args: &[crate::config::ArgMapping],
739    field_resolver: &FieldResolver,
740    result_is_simple: bool,
741    _is_async: bool,
742    e2e_config: &E2eConfig,
743    enum_fields: &HashMap<String, String>,
744    nested_types: &HashMap<String, String>,
745) {
746    let method_name = fixture.id.to_upper_camel_case();
747    let description = &fixture.description;
748
749    // HTTP fixtures: generate real HTTP client tests using System.Net.Http.
750    if let Some(http) = &fixture.http {
751        render_http_test_method(out, fixture, http);
752        return;
753    }
754
755    // Non-HTTP fixtures with no mock_response: skip only if the C# binding
756    // does not have a callable for this function via [e2e.call.overrides.csharp].
757    if fixture.mock_response.is_none() && !fixture_has_csharp_callable(fixture, e2e_config) {
758        let skip_reason =
759            "non-HTTP fixture: C# binding does not expose a callable for the configured `[e2e.call]` function";
760        let ctx = minijinja::context! {
761            is_skipped => true,
762            skip_reason => skip_reason,
763            description => description,
764            method_name => method_name,
765        };
766        let rendered = crate::template_env::render("csharp/test_method.jinja", ctx);
767        out.push_str(&rendered);
768        return;
769    }
770
771    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
772
773    // Resolve call config per-fixture so named calls (e.g. "parse") use the
774    // correct function name, result variable, and async flag.
775    // Use resolve_call_for_fixture to support auto-routing via select_when.
776    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
777    let lang = "csharp";
778    let cs_overrides = call_config.overrides.get(lang);
779
780    // Streaming branch: chat_stream returns IAsyncEnumerable<ChatCompletionChunk>,
781    // not Task<T>. Emit `await foreach` over the stream, building local
782    // aggregator vars (`chunks`, `streamContent`, `streamComplete`, ...) and
783    // asserting on those locals — never on response pseudo-fields.
784    let raw_function_name = cs_overrides
785        .and_then(|o| o.function.as_ref())
786        .cloned()
787        .unwrap_or_else(|| call_config.function.clone());
788    if raw_function_name == "chat_stream" {
789        render_chat_stream_test_method(
790            out,
791            fixture,
792            class_name,
793            call_config,
794            cs_overrides,
795            e2e_config,
796            enum_fields,
797            nested_types,
798            exception_class,
799        );
800        return;
801    }
802
803    let effective_function_name = cs_overrides
804        .and_then(|o| o.function.as_ref())
805        .cloned()
806        .unwrap_or_else(|| call_config.function.to_upper_camel_case());
807    let effective_result_var = &call_config.result_var;
808    let effective_is_async = call_config.r#async;
809    let function_name = effective_function_name.as_str();
810    let result_var = effective_result_var.as_str();
811    let is_async = effective_is_async;
812    let args = call_config.args.as_slice();
813
814    // Per-call overrides: result shape, void returns, extra trailing args.
815    // Pull `result_is_simple` from the per-call config first (call-level value
816    // wins, then per-language override, then the top-level call's value).
817    let per_call_result_is_simple = call_config.result_is_simple || cs_overrides.is_some_and(|o| o.result_is_simple);
818    // result_is_bytes: when set, the call returns a raw byte[] in C# (not a
819    // struct with named fields). Mirrors the C codegen flag added in 50e1d309.
820    // Treat byte-buffer returns like result_is_simple (no struct accessors) and
821    // emit byte-specific assertions for `not_empty`/`is_empty`.
822    let per_call_result_is_bytes = call_config.result_is_bytes || cs_overrides.is_some_and(|o| o.result_is_bytes);
823    let effective_result_is_simple = result_is_simple || per_call_result_is_simple || per_call_result_is_bytes;
824    let effective_result_is_bytes = per_call_result_is_bytes;
825    let returns_void = call_config.returns_void;
826    let extra_args_slice: &[String] = cs_overrides.map_or(&[], |o| o.extra_args.as_slice());
827    // options_type: prefer per-call override, fall back to top-level csharp override.
828    let top_level_options_type = e2e_config
829        .call
830        .overrides
831        .get("csharp")
832        .and_then(|o| o.options_type.as_deref());
833    let effective_options_type = cs_overrides
834        .and_then(|o| o.options_type.as_deref())
835        .or(top_level_options_type);
836
837    // options_via: how to construct the options object. Supported values:
838    //   "kwargs" (default) — emit a C# object initializer (`new T { ... }`).
839    //   "from_json"        — emit `JsonSerializer.Deserialize<T>(json, ConfigOptions)!`,
840    //                        sidestepping per-field type ambiguity for fields like
841    //                        `JsonElement?` (untagged unions) or `List<NamedRecord>`
842    //                        (where the codegen would otherwise default to `List<string>`).
843    let top_level_options_via = e2e_config
844        .call
845        .overrides
846        .get("csharp")
847        .and_then(|o| o.options_via.as_deref());
848    let effective_options_via = cs_overrides
849        .and_then(|o| o.options_via.as_deref())
850        .or(top_level_options_via);
851
852    let (mut setup_lines, args_str) = build_args_and_setup(
853        &fixture.input,
854        args,
855        class_name,
856        effective_options_type,
857        effective_options_via,
858        enum_fields,
859        nested_types,
860        fixture,
861    );
862
863    // Build visitor if present: instantiate in method body, declare class at file scope.
864    let mut visitor_arg = String::new();
865    let has_visitor = fixture.visitor.is_some();
866    if let Some(visitor_spec) = &fixture.visitor {
867        visitor_arg = build_csharp_visitor(&mut setup_lines, visitor_class_decls, &fixture.id, visitor_spec);
868    }
869
870    // When a visitor is present, embed it in the options object instead of passing as a separate arg.
871    // args_str should contain the function arguments with null for missing options (e.g., "html, null").
872    // We need to replace that null with a ConversionOptions instance that has Visitor set.
873    let final_args = if has_visitor && !visitor_arg.is_empty() {
874        let opts_type = effective_options_type.unwrap_or("ConversionOptions");
875        if args_str.contains("JsonSerializer.Deserialize") {
876            // Deserialize form: extract the deserialized object and set Visitor on it
877            setup_lines.push(format!("var options = {args_str};"));
878            setup_lines.push(format!("options.Visitor = {visitor_arg};"));
879            "options".to_string()
880        } else if args_str.ends_with(", null") {
881            // Replace trailing ", null" with options
882            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
883            let trimmed = args_str[..args_str.len() - 6].to_string(); // Remove ", null" (6 chars including space)
884            format!("{trimmed}, options")
885        } else if args_str.contains(", null,") {
886            // Options parameter is null in the middle; replace it
887            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
888            args_str.replace(", null,", ", options,")
889        } else if args_str.is_empty() {
890            // No options were provided; create new instance with Visitor
891            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
892            "options".to_string()
893        } else {
894            // Fall back to appending options
895            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
896            format!("{args_str}, options")
897        }
898    } else if extra_args_slice.is_empty() {
899        args_str
900    } else if args_str.is_empty() {
901        extra_args_slice.join(", ")
902    } else {
903        format!("{args_str}, {}", extra_args_slice.join(", "))
904    };
905
906    // Always use the base function name (Convert) regardless of visitor presence
907    // The visitor is now handled internally via options.Visitor
908    let effective_function_name = function_name.to_string();
909
910    let return_type = if is_async { "async Task" } else { "void" };
911    let await_kw = if is_async { "await " } else { "" };
912
913    // Client factory: when set, create a client instance and call methods on it
914    // rather than using static class calls.
915    let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
916        e2e_config
917            .call
918            .overrides
919            .get("csharp")
920            .and_then(|o| o.client_factory.as_deref())
921    });
922    let call_target = if client_factory.is_some() {
923        "client".to_string()
924    } else {
925        class_name.to_string()
926    };
927
928    // Build client factory setup code. For fixtures whose env block sets
929    // an `api_key_var` AND that have neither `mock_response` nor an `http`
930    // override (live-smoke tests against real provider APIs), prepend an
931    // early-return when the env var is unset so CI without API keys does
932    // not fail with `not found: No mock route for ...`. Mirrors the
933    // Elixir / Python skip pattern documented in CHANGELOG v0.15.9.
934    let mut client_factory_setup = String::new();
935    if let Some(factory) = client_factory {
936        let factory_name = factory.to_upper_camel_case();
937        let fixture_id = &fixture.id;
938        let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
939        let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
940        let is_live_smoke = !has_mock && api_key_var_opt.is_some();
941        if let Some(api_key_var) = api_key_var_opt.filter(|_| has_mock) {
942            client_factory_setup.push_str(&format!(
943                "        var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
944            ));
945            client_factory_setup.push_str(&format!(
946                "        var baseUrl = string.IsNullOrEmpty(apiKey)\n            ? (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\"\n            : null;\n"
947            ));
948            client_factory_setup.push_str(&format!(
949                "        Console.WriteLine($\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({api_key_var} is set)\" : \"using mock server ({api_key_var} not set)\"));\n"
950            ));
951            client_factory_setup.push_str(&format!(
952                "        var client = {class_name}.{factory_name}(string.IsNullOrEmpty(apiKey) ? \"test-key\" : apiKey, baseUrl, null, null, null);\n"
953            ));
954        } else if let Some(api_key_var) = api_key_var_opt.filter(|_| is_live_smoke) {
955            client_factory_setup.push_str(&format!(
956                "        var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
957            ));
958            client_factory_setup.push_str("        if (string.IsNullOrEmpty(apiKey)) { return; }\n");
959            client_factory_setup.push_str(&format!(
960                "        var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
961            ));
962        } else if fixture.has_host_root_route() {
963            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
964            client_factory_setup.push_str(&format!(
965                "        var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
966            ));
967            client_factory_setup.push_str(&format!("        var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
968            client_factory_setup.push_str(&format!(
969                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
970            ));
971        } else {
972            client_factory_setup.push_str(&format!("        var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
973            client_factory_setup.push_str(&format!(
974                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
975            ));
976        }
977    }
978
979    // Build call expression
980    let call_expr = format!("{}({})", effective_function_name, final_args);
981
982    // Merge per-call C# `enum_fields` keys with the global file-level
983    // `fields_enum` set so call-specific enum-typed result fields (e.g.
984    // BatchObject's `status` → BatchStatus) trigger enum coercion in
985    // assertions even when the global set does not list them. The
986    // file-level `enum_fields` argument carries the default-call's override;
987    // `cs_overrides.enum_fields` carries the per-fixture-call's override
988    // (e.g. retrieve_batch.overrides.csharp.enum_fields).
989    let mut effective_enum_fields: std::collections::HashSet<String> = e2e_config.fields_enum.clone();
990    for k in enum_fields.keys() {
991        effective_enum_fields.insert(k.clone());
992    }
993    if let Some(o) = cs_overrides {
994        for k in o.enum_fields.keys() {
995            effective_enum_fields.insert(k.clone());
996        }
997    }
998
999    // Build assertions body for non-error cases
1000    let mut assertions_body = String::new();
1001    if !expects_error && !returns_void {
1002        for assertion in &fixture.assertions {
1003            render_assertion(
1004                &mut assertions_body,
1005                assertion,
1006                result_var,
1007                class_name,
1008                exception_class,
1009                field_resolver,
1010                effective_result_is_simple,
1011                call_config.result_is_vec || cs_overrides.is_some_and(|o| o.result_is_vec),
1012                call_config.result_is_array,
1013                effective_result_is_bytes,
1014                &effective_enum_fields,
1015            );
1016        }
1017    }
1018
1019    let ctx = minijinja::context! {
1020        is_skipped => false,
1021        expects_error => expects_error,
1022        description => description,
1023        return_type => return_type,
1024        method_name => method_name,
1025        async_kw => await_kw,
1026        call_target => call_target,
1027        setup_lines => setup_lines.clone(),
1028        call_expr => call_expr,
1029        exception_class => exception_class,
1030        client_factory_setup => client_factory_setup,
1031        has_usable_assertion => !expects_error && !returns_void,
1032        result_var => result_var,
1033        assertions_body => assertions_body,
1034    };
1035
1036    let rendered = crate::template_env::render("csharp/test_method.jinja", ctx);
1037    // Indent each line by 4 spaces to nest inside the test class
1038    for line in rendered.lines() {
1039        out.push_str("    ");
1040        out.push_str(line);
1041        out.push('\n');
1042    }
1043}
1044
1045/// Render a `chat_stream` test method. The C# binding emits
1046/// `IAsyncEnumerable<ChatCompletionChunk> ChatStream(req)` (not `Task<T>`), so
1047/// the test body uses `await foreach` to drive the stream and aggregates
1048/// per-chunk data into local vars (`chunks`, `streamContent`, `streamComplete`,
1049/// optional `lastFinishReason`/`toolCallsJson`/`toolCalls0FunctionName`/`totalTokens`).
1050/// Assertions then run against those locals — never against pseudo-fields on a
1051/// response object.
1052#[allow(clippy::too_many_arguments)]
1053fn render_chat_stream_test_method(
1054    out: &mut String,
1055    fixture: &Fixture,
1056    class_name: &str,
1057    call_config: &crate::config::CallConfig,
1058    cs_overrides: Option<&crate::config::CallOverride>,
1059    e2e_config: &E2eConfig,
1060    enum_fields: &HashMap<String, String>,
1061    nested_types: &HashMap<String, String>,
1062    exception_class: &str,
1063) {
1064    let method_name = fixture.id.to_upper_camel_case();
1065    let description = &fixture.description;
1066    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1067
1068    let effective_function_name = cs_overrides
1069        .and_then(|o| o.function.as_ref())
1070        .cloned()
1071        .unwrap_or_else(|| call_config.function.to_upper_camel_case());
1072    let function_name = effective_function_name.as_str();
1073    let args = call_config.args.as_slice();
1074
1075    let top_level_options_type = e2e_config
1076        .call
1077        .overrides
1078        .get("csharp")
1079        .and_then(|o| o.options_type.as_deref());
1080    let effective_options_type = cs_overrides
1081        .and_then(|o| o.options_type.as_deref())
1082        .or(top_level_options_type);
1083    let top_level_options_via = e2e_config
1084        .call
1085        .overrides
1086        .get("csharp")
1087        .and_then(|o| o.options_via.as_deref());
1088    let effective_options_via = cs_overrides
1089        .and_then(|o| o.options_via.as_deref())
1090        .or(top_level_options_via);
1091
1092    let (setup_lines, args_str) = build_args_and_setup(
1093        &fixture.input,
1094        args,
1095        class_name,
1096        effective_options_type,
1097        effective_options_via,
1098        enum_fields,
1099        nested_types,
1100        fixture,
1101    );
1102
1103    let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
1104        e2e_config
1105            .call
1106            .overrides
1107            .get("csharp")
1108            .and_then(|o| o.client_factory.as_deref())
1109    });
1110    let mut client_factory_setup = String::new();
1111    if let Some(factory) = client_factory {
1112        let factory_name = factory.to_upper_camel_case();
1113        let fixture_id = &fixture.id;
1114        let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1115        let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1116        let is_live_smoke = !has_mock && api_key_var_opt.is_some();
1117        if let Some(api_key_var) = api_key_var_opt.filter(|_| has_mock) {
1118            client_factory_setup.push_str(&format!(
1119                "        var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1120            ));
1121            client_factory_setup.push_str(&format!(
1122                "        var baseUrl = string.IsNullOrEmpty(apiKey)\n            ? (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\"\n            : null;\n"
1123            ));
1124            client_factory_setup.push_str(&format!(
1125                "        Console.WriteLine($\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({api_key_var} is set)\" : \"using mock server ({api_key_var} not set)\"));\n"
1126            ));
1127            client_factory_setup.push_str(&format!(
1128                "        var client = {class_name}.{factory_name}(string.IsNullOrEmpty(apiKey) ? \"test-key\" : apiKey, baseUrl, null, null, null);\n"
1129            ));
1130        } else if let Some(api_key_var) = api_key_var_opt.filter(|_| is_live_smoke) {
1131            client_factory_setup.push_str(&format!(
1132                "        var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1133            ));
1134            client_factory_setup.push_str("        if (string.IsNullOrEmpty(apiKey)) { return; }\n");
1135            client_factory_setup.push_str(&format!(
1136                "        var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
1137            ));
1138        } else if fixture.has_host_root_route() {
1139            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1140            client_factory_setup.push_str(&format!(
1141                "        var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
1142            ));
1143            client_factory_setup.push_str(&format!("        var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1144            client_factory_setup.push_str(&format!(
1145                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1146            ));
1147        } else {
1148            client_factory_setup.push_str(&format!(
1149                "        var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"
1150            ));
1151            client_factory_setup.push_str(&format!(
1152                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1153            ));
1154        }
1155    }
1156
1157    let call_target = if client_factory.is_some() { "client" } else { class_name };
1158    let call_expr = format!("{call_target}.{function_name}({args_str})");
1159
1160    // Detect which aggregators a fixture's assertions actually need.
1161    let mut needs_finish_reason = false;
1162    let mut needs_tool_calls_json = false;
1163    let mut needs_tool_calls_0_function_name = false;
1164    let mut needs_total_tokens = false;
1165    for a in &fixture.assertions {
1166        if let Some(f) = a.field.as_deref() {
1167            match f {
1168                "finish_reason" => needs_finish_reason = true,
1169                "tool_calls" => needs_tool_calls_json = true,
1170                "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
1171                "usage.total_tokens" => needs_total_tokens = true,
1172                _ => {}
1173            }
1174        }
1175    }
1176
1177    let mut body = String::new();
1178    let _ = writeln!(body, "    [Fact]");
1179    let _ = writeln!(body, "    public async Task Test_{method_name}()");
1180    let _ = writeln!(body, "    {{");
1181    let _ = writeln!(body, "        // {description}");
1182    if !client_factory_setup.is_empty() {
1183        body.push_str(&client_factory_setup);
1184    }
1185    for line in &setup_lines {
1186        let _ = writeln!(body, "        {line}");
1187    }
1188
1189    if expects_error {
1190        // Wrap the foreach in a lambda so the IAsyncEnumerable is actually
1191        // consumed (otherwise the producer never runs and no exception is raised).
1192        let _ = writeln!(
1193            body,
1194            "        await Assert.ThrowsAnyAsync<{exception_class}>(async () => {{"
1195        );
1196        let _ = writeln!(body, "            await foreach (var _chunk in {call_expr}) {{ }}");
1197        body.push_str("        });\n");
1198        body.push_str("    }\n");
1199        for line in body.lines() {
1200            out.push_str("    ");
1201            out.push_str(line);
1202            out.push('\n');
1203        }
1204        return;
1205    }
1206
1207    body.push_str("        var chunks = new List<ChatCompletionChunk>();\n");
1208    body.push_str("        var streamContent = new System.Text.StringBuilder();\n");
1209    body.push_str("        var streamComplete = false;\n");
1210    if needs_finish_reason {
1211        body.push_str("        string? lastFinishReason = null;\n");
1212    }
1213    if needs_tool_calls_json {
1214        body.push_str("        string? toolCallsJson = null;\n");
1215    }
1216    if needs_tool_calls_0_function_name {
1217        body.push_str("        string? toolCalls0FunctionName = null;\n");
1218    }
1219    if needs_total_tokens {
1220        body.push_str("        long? totalTokens = null;\n");
1221    }
1222    let _ = writeln!(body, "        await foreach (var chunk in {call_expr})");
1223    body.push_str("        {\n");
1224    body.push_str("            chunks.Add(chunk);\n");
1225    body.push_str(
1226        "            var choice = chunk.Choices != null && chunk.Choices.Count > 0 ? chunk.Choices[0] : null;\n",
1227    );
1228    body.push_str("            if (choice != null)\n");
1229    body.push_str("            {\n");
1230    body.push_str("                var delta = choice.Delta;\n");
1231    body.push_str("                if (delta != null && !string.IsNullOrEmpty(delta.Content))\n");
1232    body.push_str("                {\n");
1233    body.push_str("                    streamContent.Append(delta.Content);\n");
1234    body.push_str("                }\n");
1235    if needs_finish_reason {
1236        // Streaming accumulator must use the wire-form snake_case representation
1237        // (e.g. `tool_calls`) so equality assertions against the fixture-side
1238        // string match. `.ToString().ToLower()` collapses compound PascalCase
1239        // names like `ToolCalls` to `toolcalls` (no underscore), causing
1240        // assertion failures. `JsonNamingPolicy.SnakeCaseLower.ConvertName`
1241        // mirrors the policy used by the global `JsonStringEnumConverter`,
1242        // matching exactly what serde would emit on the wire.
1243        body.push_str("                if (choice.FinishReason != null)\n");
1244        body.push_str("                {\n");
1245        body.push_str(
1246            "                    lastFinishReason = JsonNamingPolicy.SnakeCaseLower.ConvertName(choice.FinishReason.ToString()!);\n",
1247        );
1248        body.push_str("                }\n");
1249    }
1250    if needs_tool_calls_json || needs_tool_calls_0_function_name {
1251        body.push_str("                var tcs = delta?.ToolCalls;\n");
1252        body.push_str("                if (tcs != null && tcs.Count > 0)\n");
1253        body.push_str("                {\n");
1254        if needs_tool_calls_json {
1255            body.push_str(
1256                "                    toolCallsJson ??= JsonSerializer.Serialize(tcs.Select(tc => new { function = new { name = tc.Function?.Name } }));\n",
1257            );
1258        }
1259        if needs_tool_calls_0_function_name {
1260            body.push_str("                    toolCalls0FunctionName ??= tcs[0].Function?.Name;\n");
1261        }
1262        body.push_str("                }\n");
1263    }
1264    body.push_str("            }\n");
1265    if needs_total_tokens {
1266        body.push_str("            if (chunk.Usage != null)\n");
1267        body.push_str("            {\n");
1268        body.push_str("                totalTokens = chunk.Usage.TotalTokens;\n");
1269        body.push_str("            }\n");
1270    }
1271    body.push_str("        }\n");
1272    body.push_str("        streamComplete = true;\n");
1273
1274    // Emit assertions on local aggregator vars.
1275    let mut had_explicit_complete = false;
1276    for assertion in &fixture.assertions {
1277        if assertion.field.as_deref() == Some("stream_complete") {
1278            had_explicit_complete = true;
1279        }
1280        emit_chat_stream_assertion(&mut body, assertion);
1281    }
1282    if !had_explicit_complete {
1283        body.push_str("        Assert.True(streamComplete);\n");
1284    }
1285
1286    body.push_str("    }\n");
1287
1288    for line in body.lines() {
1289        out.push_str("    ");
1290        out.push_str(line);
1291        out.push('\n');
1292    }
1293}
1294
1295/// Map a streaming fixture assertion to an `Assert` call on the local aggregator
1296/// variable produced by `render_chat_stream_test_method`. Pseudo-fields like
1297/// `chunks` / `stream_content` / `stream_complete` resolve to in-method locals.
1298fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion) {
1299    let atype = assertion.assertion_type.as_str();
1300    if atype == "not_error" || atype == "error" {
1301        return;
1302    }
1303    let field = assertion.field.as_deref().unwrap_or("");
1304
1305    enum Kind {
1306        Chunks,
1307        Bool,
1308        Str,
1309        IntTokens,
1310        Json,
1311        Unsupported,
1312    }
1313
1314    let (expr, kind) = match field {
1315        "chunks" => ("chunks", Kind::Chunks),
1316        "stream_content" => ("streamContent.ToString()", Kind::Str),
1317        "stream_complete" => ("streamComplete", Kind::Bool),
1318        "no_chunks_after_done" => ("streamComplete", Kind::Bool),
1319        "finish_reason" => ("lastFinishReason", Kind::Str),
1320        "tool_calls" => ("toolCallsJson", Kind::Json),
1321        "tool_calls[0].function.name" => ("toolCalls0FunctionName", Kind::Str),
1322        "usage.total_tokens" => ("totalTokens", Kind::IntTokens),
1323        _ => ("", Kind::Unsupported),
1324    };
1325
1326    if matches!(kind, Kind::Unsupported) {
1327        let _ = writeln!(
1328            out,
1329            "        // skipped: streaming assertion on unsupported field '{field}'"
1330        );
1331        return;
1332    }
1333
1334    match (atype, &kind) {
1335        ("count_min", Kind::Chunks) => {
1336            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1337                let _ = writeln!(
1338                    out,
1339                    "        Assert.True(chunks.Count >= {n}, \"expected at least {n} chunks\");"
1340                );
1341            }
1342        }
1343        ("count_equals", Kind::Chunks) => {
1344            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1345                let _ = writeln!(out, "        Assert.Equal({n}, chunks.Count);");
1346            }
1347        }
1348        ("equals", Kind::Str) => {
1349            if let Some(val) = &assertion.value {
1350                let cs_val = json_to_csharp(val);
1351                let _ = writeln!(out, "        Assert.Equal({cs_val}, {expr});");
1352            }
1353        }
1354        ("contains", Kind::Str) => {
1355            if let Some(val) = &assertion.value {
1356                let cs_val = json_to_csharp(val);
1357                let _ = writeln!(out, "        Assert.Contains({cs_val}, {expr} ?? string.Empty);");
1358            }
1359        }
1360        ("not_empty", Kind::Str) => {
1361            let _ = writeln!(out, "        Assert.False(string.IsNullOrEmpty({expr}));");
1362        }
1363        ("not_empty", Kind::Json) => {
1364            let _ = writeln!(out, "        Assert.NotNull({expr});");
1365        }
1366        ("is_empty", Kind::Str) => {
1367            let _ = writeln!(out, "        Assert.True(string.IsNullOrEmpty({expr}));");
1368        }
1369        ("is_true", Kind::Bool) => {
1370            let _ = writeln!(out, "        Assert.True({expr});");
1371        }
1372        ("is_false", Kind::Bool) => {
1373            let _ = writeln!(out, "        Assert.False({expr});");
1374        }
1375        ("greater_than_or_equal", Kind::IntTokens) => {
1376            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1377                let _ = writeln!(out, "        Assert.True({expr} >= {n}, \"expected >= {n}\");");
1378            }
1379        }
1380        ("equals", Kind::IntTokens) => {
1381            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1382                let _ = writeln!(out, "        Assert.Equal((long?){n}, {expr});");
1383            }
1384        }
1385        _ => {
1386            let _ = writeln!(
1387                out,
1388                "        // skipped: streaming assertion '{atype}' on field '{field}' not supported"
1389            );
1390        }
1391    }
1392}
1393
1394/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1395///
1396/// Returns `(setup_lines, args_string)`.
1397#[allow(clippy::too_many_arguments)]
1398fn build_args_and_setup(
1399    input: &serde_json::Value,
1400    args: &[crate::config::ArgMapping],
1401    class_name: &str,
1402    options_type: Option<&str>,
1403    options_via: Option<&str>,
1404    enum_fields: &HashMap<String, String>,
1405    nested_types: &HashMap<String, String>,
1406    fixture: &crate::fixture::Fixture,
1407) -> (Vec<String>, String) {
1408    let fixture_id = &fixture.id;
1409    if args.is_empty() {
1410        return (Vec::new(), String::new());
1411    }
1412
1413    let mut setup_lines: Vec<String> = Vec::new();
1414    let mut parts: Vec<String> = Vec::new();
1415
1416    for arg in args {
1417        if arg.arg_type == "bytes" {
1418            // bytes args must be passed as byte[] in C#.
1419            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1420            let val = input.get(field);
1421            match val {
1422                None | Some(serde_json::Value::Null) if arg.optional => {
1423                    parts.push("null".to_string());
1424                }
1425                None | Some(serde_json::Value::Null) => {
1426                    parts.push("System.Array.Empty<byte>()".to_string());
1427                }
1428                Some(v) => {
1429                    // Classify the value to determine how to interpret it:
1430                    // - File paths (like "pdf/fake.pdf") → File.ReadAllBytes(path)
1431                    // - Inline text → System.Text.Encoding.UTF8.GetBytes()
1432                    // - Base64 → Convert.FromBase64String()
1433                    if let Some(s) = v.as_str() {
1434                        let bytes_code = classify_bytes_value_csharp(s);
1435                        parts.push(bytes_code);
1436                    } else {
1437                        // Literal arrays or other non-string types: use as-is
1438                        let cs_str = json_to_csharp(v);
1439                        parts.push(format!("System.Text.Encoding.UTF8.GetBytes({cs_str})"));
1440                    }
1441                }
1442            }
1443            continue;
1444        }
1445
1446        if arg.arg_type == "mock_url" {
1447            if fixture.has_host_root_route() {
1448                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1449                setup_lines.push(format!(
1450                    "var _pfUrl_{name} = Environment.GetEnvironmentVariable(\"{env_key}\");",
1451                    name = arg.name,
1452                ));
1453                setup_lines.push(format!(
1454                    "var {} = !string.IsNullOrEmpty(_pfUrl_{name}) ? _pfUrl_{name} : Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1455                    arg.name,
1456                    name = arg.name,
1457                ));
1458            } else {
1459                setup_lines.push(format!(
1460                    "var {} = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1461                    arg.name,
1462                ));
1463            }
1464            parts.push(arg.name.clone());
1465            continue;
1466        }
1467
1468        if arg.arg_type == "handle" {
1469            // Generate a CreateEngine (or equivalent) call and pass the variable.
1470            let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
1471            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1472            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1473            if config_value.is_null()
1474                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1475            {
1476                setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1477            } else {
1478                // Sort discriminator fields ("type") to appear first in nested objects so
1479                // System.Text.Json [JsonPolymorphic] can find the type discriminator before
1480                // reading other properties (a requirement as of .NET 8).
1481                let sorted = sort_discriminator_first(config_value.clone());
1482                let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1483                let name = &arg.name;
1484                setup_lines.push(format!(
1485                    "var {name}Config = JsonSerializer.Deserialize<CrawlConfig>(\"{}\", ConfigOptions)!;",
1486                    escape_csharp(&json_str),
1487                ));
1488                setup_lines.push(format!(
1489                    "var {} = {class_name}.{constructor_name}({name}Config);",
1490                    arg.name,
1491                    name = name,
1492                ));
1493            }
1494            parts.push(arg.name.clone());
1495            continue;
1496        }
1497
1498        // When field is exactly "input", treat the entire input object as the value.
1499        // This matches the convention used by other language generators (e.g. Go).
1500        let val: Option<&serde_json::Value> = if arg.field == "input" {
1501            Some(input)
1502        } else {
1503            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1504            input.get(field)
1505        };
1506        match val {
1507            None | Some(serde_json::Value::Null) if arg.optional => {
1508                // Optional arg with no fixture value: pass null explicitly since
1509                // C# nullable parameters still require an argument at the call site.
1510                parts.push("null".to_string());
1511                continue;
1512            }
1513            None | Some(serde_json::Value::Null) => {
1514                // Required arg with no fixture value: pass a language-appropriate default.
1515                // For json_object args with a known options_type, use `new OptionsType()`
1516                // so the generated code compiles when the method parameter is non-nullable.
1517                let default_val = match arg.arg_type.as_str() {
1518                    "string" => "\"\"".to_string(),
1519                    "int" | "integer" => "0".to_string(),
1520                    "float" | "number" => "0.0d".to_string(),
1521                    "bool" | "boolean" => "false".to_string(),
1522                    "json_object" => {
1523                        if let Some(opts_type) = options_type {
1524                            format!("new {opts_type}()")
1525                        } else {
1526                            "null".to_string()
1527                        }
1528                    }
1529                    _ => "null".to_string(),
1530                };
1531                parts.push(default_val);
1532            }
1533            Some(v) => {
1534                if arg.arg_type == "json_object" {
1535                    // `options_via = "from_json"`: deserialize the entire value (object,
1536                    // array, or scalar) as the options type. This sidesteps per-field
1537                    // type ambiguity — e.g. `JsonElement?` (untagged unions) or
1538                    // `List<NamedRecord>` whose element type cannot be inferred from
1539                    // JSON shape alone — by delegating to System.Text.Json.
1540                    if options_via == Some("from_json")
1541                        && let Some(opts_type) = options_type
1542                    {
1543                        let sorted = sort_discriminator_first(v.clone());
1544                        let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1545                        let escaped = escape_csharp(&json_str);
1546                        // Use the binding-emitted `<Type>.FromJson(...)` factory so any
1547                        // System.Text.Json deserialization failure is wrapped in
1548                        // `<Crate>Exception`, allowing error fixtures asserting
1549                        // `Assert.ThrowsAny<<Crate>Exception>(...)` to catch the parse
1550                        // failure (e.g. `Unknown FilePurpose value: invalid-purpose`).
1551                        parts.push(format!("{opts_type}.FromJson(\"{escaped}\")",));
1552                        continue;
1553                    }
1554                    // Array value: generate a typed List<T> based on element_type.
1555                    if let Some(arr) = v.as_array() {
1556                        parts.push(json_array_to_csharp_list(arr, arg.element_type.as_deref()));
1557                        continue;
1558                    }
1559                    // Object value with known type: generate idiomatic C# object initializer.
1560                    if let Some(opts_type) = options_type {
1561                        if let Some(obj) = v.as_object() {
1562                            parts.push(csharp_object_initializer(obj, opts_type, enum_fields, nested_types));
1563                            continue;
1564                        }
1565                    }
1566                }
1567                parts.push(json_to_csharp(v));
1568            }
1569        }
1570    }
1571
1572    (setup_lines, parts.join(", "))
1573}
1574
1575/// Convert a JSON array to a typed C# `List<T>` expression.
1576///
1577/// Mapping from `ArgMapping::element_type`:
1578/// - `None` or any string type → `List<string>`
1579/// - `"f32"` → `List<float>` with `(float)` casts
1580/// - `"(String, String)"` → `List<List<string>>` for key-value pair arrays
1581/// - `"BatchBytesItem"` / `"BatchFileItem"` → array of batch item instances
1582fn json_array_to_csharp_list(arr: &[serde_json::Value], element_type: Option<&str>) -> String {
1583    match element_type {
1584        Some("BatchBytesItem") => {
1585            let items: Vec<String> = arr
1586                .iter()
1587                .filter_map(|v| v.as_object())
1588                .map(|obj| {
1589                    let content = obj.get("content").and_then(|v| v.as_array());
1590                    let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1591                    let content_code = if let Some(arr) = content {
1592                        let bytes: Vec<String> = arr
1593                            .iter()
1594                            .filter_map(|v| v.as_u64().map(|n| format!("(byte){}", n)))
1595                            .collect();
1596                        format!("new byte[] {{ {} }}", bytes.join(", "))
1597                    } else {
1598                        "new byte[] { }".to_string()
1599                    };
1600                    format!(
1601                        "new BatchBytesItem {{ Content = {}, MimeType = \"{}\" }}",
1602                        content_code, mime_type
1603                    )
1604                })
1605                .collect();
1606            format!("new List<BatchBytesItem>() {{ {} }}", items.join(", "))
1607        }
1608        Some("BatchFileItem") => {
1609            let items: Vec<String> = arr
1610                .iter()
1611                .filter_map(|v| v.as_object())
1612                .map(|obj| {
1613                    let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1614                    format!("new BatchFileItem {{ Path = \"{}\" }}", path)
1615                })
1616                .collect();
1617            format!("new List<BatchFileItem>() {{ {} }}", items.join(", "))
1618        }
1619        Some("f32") => {
1620            let items: Vec<String> = arr.iter().map(|v| format!("(float){}", json_to_csharp(v))).collect();
1621            format!("new List<float>() {{ {} }}", items.join(", "))
1622        }
1623        Some("(String, String)") => {
1624            let items: Vec<String> = arr
1625                .iter()
1626                .map(|v| {
1627                    let strs: Vec<String> = v
1628                        .as_array()
1629                        .map_or_else(Vec::new, |a| a.iter().map(json_to_csharp).collect());
1630                    format!("new List<string>() {{ {} }}", strs.join(", "))
1631                })
1632                .collect();
1633            format!("new List<List<string>>() {{ {} }}", items.join(", "))
1634        }
1635        Some(et)
1636            if et != "f32"
1637                && et != "(String, String)"
1638                && et != "string"
1639                && et != "BatchBytesItem"
1640                && et != "BatchFileItem" =>
1641        {
1642            // Class/record types: deserialize each element from JSON
1643            let items: Vec<String> = arr
1644                .iter()
1645                .map(|v| {
1646                    let json_str = serde_json::to_string(v).unwrap_or_default();
1647                    let escaped = escape_csharp(&json_str);
1648                    format!("JsonSerializer.Deserialize<{et}>(\"{escaped}\", ConfigOptions)!")
1649                })
1650                .collect();
1651            format!("new List<{et}>() {{ {} }}", items.join(", "))
1652        }
1653        _ => {
1654            let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
1655            format!("new List<string>() {{ {} }}", items.join(", "))
1656        }
1657    }
1658}
1659
1660/// Detect if a field path accesses a discriminated union variant in C#.
1661/// Pattern: `metadata.format.<variant_name>.<field_name>`
1662/// Returns: Some((accessor, variant_name, inner_field)) if matched, otherwise None
1663fn parse_discriminated_union_access(field: &str) -> Option<(String, String, String)> {
1664    let parts: Vec<&str> = field.split('.').collect();
1665    if parts.len() >= 3 && parts.len() <= 4 {
1666        // Check if this is metadata.format.{variant}.{field} pattern
1667        if parts[0] == "metadata" && parts[1] == "format" {
1668            let variant_name = parts[2];
1669            // Known C# discriminated union variants (lowercase in fixture paths)
1670            let known_variants = [
1671                "pdf",
1672                "docx",
1673                "excel",
1674                "email",
1675                "pptx",
1676                "archive",
1677                "image",
1678                "xml",
1679                "text",
1680                "html",
1681                "ocr",
1682                "csv",
1683                "bibtex",
1684                "citation",
1685                "fiction_book",
1686                "dbf",
1687                "jats",
1688                "epub",
1689                "pst",
1690                "code",
1691            ];
1692            if known_variants.contains(&variant_name) {
1693                let variant_pascal = variant_name.to_upper_camel_case();
1694                if parts.len() == 4 {
1695                    let inner_field = parts[3];
1696                    return Some((
1697                        format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1698                        variant_pascal,
1699                        inner_field.to_string(),
1700                    ));
1701                } else if parts.len() == 3 {
1702                    // Just accessing the variant itself (no inner field)
1703                    return Some((
1704                        format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1705                        variant_pascal,
1706                        String::new(),
1707                    ));
1708                }
1709            }
1710        }
1711    }
1712    None
1713}
1714
1715/// Render an assertion against a discriminated union variant's inner field.
1716/// `variant_var` is the unwrapped union variant (e.g., `variant` from pattern match).
1717/// `inner_field` is the field to access on the variant's Value (e.g., `sheet_count`).
1718fn render_discriminated_union_assertion(
1719    out: &mut String,
1720    assertion: &Assertion,
1721    variant_var: &str,
1722    inner_field: &str,
1723    _result_is_vec: bool,
1724) {
1725    if inner_field.is_empty() {
1726        return; // No field to assert on
1727    }
1728
1729    let field_pascal = inner_field.to_upper_camel_case();
1730    let field_expr = format!("{variant_var}.Value.{field_pascal}");
1731
1732    match assertion.assertion_type.as_str() {
1733        "equals" => {
1734            if let Some(expected) = &assertion.value {
1735                let cs_val = json_to_csharp(expected);
1736                if expected.is_string() {
1737                    let _ = writeln!(out, "            Assert.Equal({cs_val}, {field_expr}!.Trim());");
1738                } else if expected.as_bool() == Some(true) {
1739                    let _ = writeln!(out, "            Assert.True({field_expr});");
1740                } else if expected.as_bool() == Some(false) {
1741                    let _ = writeln!(out, "            Assert.False({field_expr});");
1742                } else if expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0) {
1743                    let _ = writeln!(out, "            Assert.True({field_expr} == {cs_val});");
1744                } else {
1745                    let _ = writeln!(out, "            Assert.Equal({cs_val}, {field_expr});");
1746                }
1747            }
1748        }
1749        "greater_than_or_equal" => {
1750            if let Some(val) = &assertion.value {
1751                let cs_val = json_to_csharp(val);
1752                let _ = writeln!(
1753                    out,
1754                    "            Assert.True({field_expr} >= {cs_val}, \"expected >= {cs_val}\");"
1755                );
1756            }
1757        }
1758        "contains_all" => {
1759            if let Some(values) = &assertion.values {
1760                let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1761                for val in values {
1762                    let lower_val = val.as_str().map(|s| s.to_lowercase());
1763                    let cs_val = lower_val
1764                        .as_deref()
1765                        .map(|s| format!("\"{}\"", escape_csharp(s)))
1766                        .unwrap_or_else(|| json_to_csharp(val));
1767                    let _ = writeln!(out, "            Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1768                }
1769            }
1770        }
1771        "contains" => {
1772            if let Some(expected) = &assertion.value {
1773                let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1774                let lower_expected = expected.as_str().map(|s| s.to_lowercase());
1775                let cs_val = lower_expected
1776                    .as_deref()
1777                    .map(|s| format!("\"{}\"", escape_csharp(s)))
1778                    .unwrap_or_else(|| json_to_csharp(expected));
1779                let _ = writeln!(out, "            Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1780            }
1781        }
1782        "not_empty" => {
1783            let _ = writeln!(out, "            Assert.NotEmpty({field_expr});");
1784        }
1785        "is_empty" => {
1786            let _ = writeln!(out, "            Assert.Empty({field_expr});");
1787        }
1788        _ => {
1789            let _ = writeln!(
1790                out,
1791                "            // skipped: assertion type '{}' not yet supported for discriminated union fields",
1792                assertion.assertion_type
1793            );
1794        }
1795    }
1796}
1797
1798#[allow(clippy::too_many_arguments)]
1799fn render_assertion(
1800    out: &mut String,
1801    assertion: &Assertion,
1802    result_var: &str,
1803    class_name: &str,
1804    exception_class: &str,
1805    field_resolver: &FieldResolver,
1806    result_is_simple: bool,
1807    result_is_vec: bool,
1808    result_is_array: bool,
1809    result_is_bytes: bool,
1810    fields_enum: &std::collections::HashSet<String>,
1811) {
1812    // Byte-buffer returns: emit length-based assertions instead of struct-field
1813    // accessors. The result is a `byte[]` and has no named fields like
1814    // `result.Audio` or `result.Content`.
1815    if result_is_bytes {
1816        match assertion.assertion_type.as_str() {
1817            "not_empty" => {
1818                let _ = writeln!(out, "        Assert.NotEmpty({result_var});");
1819                return;
1820            }
1821            "is_empty" => {
1822                let _ = writeln!(out, "        Assert.Empty({result_var});");
1823                return;
1824            }
1825            "count_equals" | "length_equals" => {
1826                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1827                    let _ = writeln!(out, "        Assert.Equal({n}, {result_var}.Length);");
1828                }
1829                return;
1830            }
1831            "count_min" | "length_min" => {
1832                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1833                    let _ = writeln!(out, "        Assert.True({result_var}.Length >= {n});");
1834                }
1835                return;
1836            }
1837            _ => {
1838                // Other assertion types are not meaningful on raw byte buffers;
1839                // emit a comment so the test still compiles but flags unsupported
1840                // assertion types for fixture authors.
1841                let _ = writeln!(
1842                    out,
1843                    "        // skipped: assertion type '{}' not supported on byte[] result",
1844                    assertion.assertion_type
1845                );
1846                return;
1847            }
1848        }
1849    }
1850    // Handle synthetic / derived fields before the is_valid_for_result check
1851    // so they are never treated as struct property accesses on the result.
1852    if let Some(f) = &assertion.field {
1853        match f.as_str() {
1854            "chunks_have_content" => {
1855                let synthetic_pred =
1856                    format!("({result_var}.Chunks ?? new()).All(c => !string.IsNullOrEmpty(c.Content))");
1857                let synthetic_pred_type = match assertion.assertion_type.as_str() {
1858                    "is_true" => "is_true",
1859                    "is_false" => "is_false",
1860                    _ => {
1861                        out.push_str(&format!(
1862                            "        // skipped: unsupported assertion type on synthetic field '{f}'\n"
1863                        ));
1864                        return;
1865                    }
1866                };
1867                let rendered = crate::template_env::render(
1868                    "csharp/assertion.jinja",
1869                    minijinja::context! {
1870                        assertion_type => "synthetic_assertion",
1871                        synthetic_pred => synthetic_pred,
1872                        synthetic_pred_type => synthetic_pred_type,
1873                    },
1874                );
1875                out.push_str(&rendered);
1876                return;
1877            }
1878            "chunks_have_embeddings" => {
1879                let synthetic_pred =
1880                    format!("({result_var}.Chunks ?? new()).All(c => c.Embedding != null && c.Embedding.Count > 0)");
1881                let synthetic_pred_type = match assertion.assertion_type.as_str() {
1882                    "is_true" => "is_true",
1883                    "is_false" => "is_false",
1884                    _ => {
1885                        out.push_str(&format!(
1886                            "        // skipped: unsupported assertion type on synthetic field '{f}'\n"
1887                        ));
1888                        return;
1889                    }
1890                };
1891                let rendered = crate::template_env::render(
1892                    "csharp/assertion.jinja",
1893                    minijinja::context! {
1894                        assertion_type => "synthetic_assertion",
1895                        synthetic_pred => synthetic_pred,
1896                        synthetic_pred_type => synthetic_pred_type,
1897                    },
1898                );
1899                out.push_str(&rendered);
1900                return;
1901            }
1902            // ---- EmbedResponse virtual fields ----
1903            // embed_texts returns List<List<float>> in C# — no wrapper object.
1904            // result_var is the embedding matrix; use it directly.
1905            "embeddings" => {
1906                match assertion.assertion_type.as_str() {
1907                    "count_equals" => {
1908                        if let Some(val) = &assertion.value {
1909                            if let Some(n) = val.as_u64() {
1910                                let rendered = crate::template_env::render(
1911                                    "csharp/assertion.jinja",
1912                                    minijinja::context! {
1913                                        assertion_type => "synthetic_embeddings_count_equals",
1914                                        synthetic_pred => format!("{result_var}.Count"),
1915                                        n => n,
1916                                    },
1917                                );
1918                                out.push_str(&rendered);
1919                            }
1920                        }
1921                    }
1922                    "count_min" => {
1923                        if let Some(val) = &assertion.value {
1924                            if let Some(n) = val.as_u64() {
1925                                let rendered = crate::template_env::render(
1926                                    "csharp/assertion.jinja",
1927                                    minijinja::context! {
1928                                        assertion_type => "synthetic_embeddings_count_min",
1929                                        synthetic_pred => format!("{result_var}.Count"),
1930                                        n => n,
1931                                    },
1932                                );
1933                                out.push_str(&rendered);
1934                            }
1935                        }
1936                    }
1937                    "not_empty" => {
1938                        let rendered = crate::template_env::render(
1939                            "csharp/assertion.jinja",
1940                            minijinja::context! {
1941                                assertion_type => "synthetic_embeddings_not_empty",
1942                                synthetic_pred => result_var.to_string(),
1943                            },
1944                        );
1945                        out.push_str(&rendered);
1946                    }
1947                    "is_empty" => {
1948                        let rendered = crate::template_env::render(
1949                            "csharp/assertion.jinja",
1950                            minijinja::context! {
1951                                assertion_type => "synthetic_embeddings_is_empty",
1952                                synthetic_pred => result_var.to_string(),
1953                            },
1954                        );
1955                        out.push_str(&rendered);
1956                    }
1957                    _ => {
1958                        out.push_str(
1959                            "        // skipped: unsupported assertion type on synthetic field 'embeddings'\n",
1960                        );
1961                    }
1962                }
1963                return;
1964            }
1965            "embedding_dimensions" => {
1966                let expr = format!("({result_var}.Count > 0 ? {result_var}[0].Count : 0)");
1967                match assertion.assertion_type.as_str() {
1968                    "equals" => {
1969                        if let Some(val) = &assertion.value {
1970                            if let Some(n) = val.as_u64() {
1971                                let rendered = crate::template_env::render(
1972                                    "csharp/assertion.jinja",
1973                                    minijinja::context! {
1974                                        assertion_type => "synthetic_embedding_dimensions_equals",
1975                                        synthetic_pred => expr,
1976                                        n => n,
1977                                    },
1978                                );
1979                                out.push_str(&rendered);
1980                            }
1981                        }
1982                    }
1983                    "greater_than" => {
1984                        if let Some(val) = &assertion.value {
1985                            if let Some(n) = val.as_u64() {
1986                                let rendered = crate::template_env::render(
1987                                    "csharp/assertion.jinja",
1988                                    minijinja::context! {
1989                                        assertion_type => "synthetic_embedding_dimensions_greater_than",
1990                                        synthetic_pred => expr,
1991                                        n => n,
1992                                    },
1993                                );
1994                                out.push_str(&rendered);
1995                            }
1996                        }
1997                    }
1998                    _ => {
1999                        out.push_str("        // skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n");
2000                    }
2001                }
2002                return;
2003            }
2004            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
2005                let synthetic_pred = match f.as_str() {
2006                    "embeddings_valid" => {
2007                        format!("{result_var}.All(e => e.Count > 0)")
2008                    }
2009                    "embeddings_finite" => {
2010                        format!("{result_var}.All(e => e.All(v => !float.IsInfinity(v) && !float.IsNaN(v)))")
2011                    }
2012                    "embeddings_non_zero" => {
2013                        format!("{result_var}.All(e => e.Any(v => v != 0.0f))")
2014                    }
2015                    "embeddings_normalized" => {
2016                        format!(
2017                            "{result_var}.All(e => {{ var n = e.Sum(v => (double)v * v); return Math.Abs(n - 1.0) < 1e-3; }})"
2018                        )
2019                    }
2020                    _ => unreachable!(),
2021                };
2022                let synthetic_pred_type = match assertion.assertion_type.as_str() {
2023                    "is_true" => "is_true",
2024                    "is_false" => "is_false",
2025                    _ => {
2026                        out.push_str(&format!(
2027                            "        // skipped: unsupported assertion type on synthetic field '{f}'\n"
2028                        ));
2029                        return;
2030                    }
2031                };
2032                let rendered = crate::template_env::render(
2033                    "csharp/assertion.jinja",
2034                    minijinja::context! {
2035                        assertion_type => "synthetic_assertion",
2036                        synthetic_pred => synthetic_pred,
2037                        synthetic_pred_type => synthetic_pred_type,
2038                    },
2039                );
2040                out.push_str(&rendered);
2041                return;
2042            }
2043            // ---- keywords / keywords_count ----
2044            // C# ExtractionResult does not expose extracted_keywords; skip.
2045            "keywords" | "keywords_count" => {
2046                let skipped_reason = format!("field '{f}' not available on C# ExtractionResult");
2047                let rendered = crate::template_env::render(
2048                    "csharp/assertion.jinja",
2049                    minijinja::context! {
2050                        skipped_reason => skipped_reason,
2051                    },
2052                );
2053                out.push_str(&rendered);
2054                return;
2055            }
2056            _ => {}
2057        }
2058    }
2059
2060    // Skip assertions on fields that don't exist on the result type.
2061    if let Some(f) = &assertion.field {
2062        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
2063            let skipped_reason = format!("field '{f}' not available on result type");
2064            let rendered = crate::template_env::render(
2065                "csharp/assertion.jinja",
2066                minijinja::context! {
2067                    skipped_reason => skipped_reason,
2068                },
2069            );
2070            out.push_str(&rendered);
2071            return;
2072        }
2073    }
2074
2075    // For count assertions on list results with no field specified, use the list directly.
2076    // Otherwise, when the result is a List<T>, index into the first element for field access.
2077    let is_count_assertion = matches!(
2078        assertion.assertion_type.as_str(),
2079        "count_equals" | "count_min" | "count_max"
2080    );
2081    let is_no_field = assertion.field.is_none() || assertion.field.as_ref().is_some_and(|f| f.is_empty());
2082    let use_list_directly = result_is_vec && is_count_assertion && is_no_field;
2083
2084    let effective_result_var: String = if result_is_vec && !use_list_directly {
2085        format!("{result_var}[0]")
2086    } else {
2087        result_var.to_string()
2088    };
2089
2090    // Check if this is a discriminated union access (e.g., metadata.format.excel.sheet_count)
2091    let is_discriminated_union = assertion
2092        .field
2093        .as_ref()
2094        .is_some_and(|f| parse_discriminated_union_access(f).is_some());
2095
2096    // For discriminated union assertions, generate pattern-matching wrapper
2097    if is_discriminated_union {
2098        if let Some((_, variant_name, inner_field)) = assertion
2099            .field
2100            .as_ref()
2101            .and_then(|f| parse_discriminated_union_access(f))
2102        {
2103            // Use a unique variable name based on the field hash to avoid shadowing
2104            let mut hasher = std::collections::hash_map::DefaultHasher::new();
2105            inner_field.hash(&mut hasher);
2106            let var_hash = format!("{:x}", hasher.finish());
2107            let variant_var = format!("variant_{}", &var_hash[..8]);
2108            let _ = writeln!(
2109                out,
2110                "        if ({effective_result_var}.Metadata.Format is FormatMetadata.{} {})",
2111                variant_name, &variant_var
2112            );
2113            let _ = writeln!(out, "        {{");
2114            render_discriminated_union_assertion(out, assertion, &variant_var, &inner_field, result_is_vec);
2115            let _ = writeln!(out, "        }}");
2116            let _ = writeln!(out, "        else");
2117            let _ = writeln!(out, "        {{");
2118            let _ = writeln!(
2119                out,
2120                "            Assert.Fail(\"Expected {} format metadata\");",
2121                variant_name.to_lowercase()
2122            );
2123            let _ = writeln!(out, "        }}");
2124            return;
2125        }
2126    }
2127
2128    let field_expr = if result_is_simple {
2129        effective_result_var.clone()
2130    } else {
2131        match &assertion.field {
2132            Some(f) if !f.is_empty() => field_resolver.accessor(f, "csharp", &effective_result_var),
2133            _ => effective_result_var.clone(),
2134        }
2135    };
2136
2137    // Determine if field_expr is a list or complex object that requires JSON serialization
2138    // for string-based assertions (contains, not_contains, etc.). List<T>.ToString() in C#
2139    // returns the type name, not the contents.
2140    let field_needs_json_serialize = if result_is_simple {
2141        // Simple results are scalars, but when they're also arrays (e.g., List<string>),
2142        // JSON-serialize so substring checks see actual content, not the type name.
2143        result_is_array
2144    } else {
2145        match &assertion.field {
2146            Some(f) if !f.is_empty() => field_resolver.is_array(f),
2147            // No field specified — the whole result object; needs serialization when complex.
2148            _ => !result_is_simple,
2149        }
2150    };
2151    // Build the string representation of field_expr for substring-based assertions.
2152    let field_as_str = if field_needs_json_serialize {
2153        format!("JsonSerializer.Serialize({field_expr})")
2154    } else {
2155        format!("{field_expr}.ToString()")
2156    };
2157
2158    // Detect enum-typed fields. C# emits typed enums (e.g. `FinishReason?`) for
2159    // these so the codegen must avoid `.Trim()` (string-only) and instead
2160    // compare via `?.ToString()?.ToLower()` to match snake_case JSON.
2161    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
2162        let resolved = field_resolver.resolve(f);
2163        fields_enum.contains(f) || fields_enum.contains(resolved)
2164    });
2165
2166    match assertion.assertion_type.as_str() {
2167        "equals" => {
2168            if let Some(expected) = &assertion.value {
2169                // Enum field equality bypasses the template (which would emit `.Trim()`,
2170                // a string-only API). Compare the snake-cased ToString() against the
2171                // expected value to match the wire JSON form (`InProgress` → `in_progress`,
2172                // `ContentFilter` → `content_filter`, etc.). `JsonNamingPolicy.SnakeCaseLower`
2173                // is the same policy used by the global JsonStringEnumConverter, so the
2174                // assertion compares against exactly what serde would emit.
2175                if field_is_enum && expected.is_string() {
2176                    let s_lower = expected.as_str().map(|s| s.to_lowercase()).unwrap_or_default();
2177                    let _ = writeln!(
2178                        out,
2179                        "        Assert.Equal(\"{}\", {field_expr} == null ? null : JsonNamingPolicy.SnakeCaseLower.ConvertName({field_expr}.ToString()!));",
2180                        escape_csharp(&s_lower)
2181                    );
2182                    return;
2183                }
2184                let cs_val = json_to_csharp(expected);
2185                let is_string_val = expected.is_string();
2186                let is_bool_true = expected.as_bool() == Some(true);
2187                let is_bool_false = expected.as_bool() == Some(false);
2188                let is_integer_val = expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0);
2189
2190                let rendered = crate::template_env::render(
2191                    "csharp/assertion.jinja",
2192                    minijinja::context! {
2193                        assertion_type => "equals",
2194                        field_expr => field_expr.clone(),
2195                        cs_val => cs_val,
2196                        is_string_val => is_string_val,
2197                        is_bool_true => is_bool_true,
2198                        is_bool_false => is_bool_false,
2199                        is_integer_val => is_integer_val,
2200                    },
2201                );
2202                out.push_str(&rendered);
2203            }
2204        }
2205        "contains" => {
2206            if let Some(expected) = &assertion.value {
2207                // Lowercase both expected and actual so that enum fields (where .ToString()
2208                // returns the PascalCase C# member name like "Anchor") correctly match
2209                // fixture snake_case values like "anchor".  String fields are unaffected
2210                // because lowercasing both sides preserves substring matches.
2211                // List/complex fields use JsonSerializer.Serialize() since List<T>.ToString()
2212                // returns the type name, not the contents.
2213                let lower_expected = expected.as_str().map(|s| s.to_lowercase());
2214                let cs_val = lower_expected
2215                    .as_deref()
2216                    .map(|s| format!("\"{}\"", escape_csharp(s)))
2217                    .unwrap_or_else(|| json_to_csharp(expected));
2218
2219                let rendered = crate::template_env::render(
2220                    "csharp/assertion.jinja",
2221                    minijinja::context! {
2222                        assertion_type => "contains",
2223                        field_as_str => field_as_str.clone(),
2224                        cs_val => cs_val,
2225                    },
2226                );
2227                out.push_str(&rendered);
2228            }
2229        }
2230        "contains_all" => {
2231            if let Some(values) = &assertion.values {
2232                let values_cs_lower: Vec<String> = values
2233                    .iter()
2234                    .map(|val| {
2235                        let lower_val = val.as_str().map(|s| s.to_lowercase());
2236                        lower_val
2237                            .as_deref()
2238                            .map(|s| format!("\"{}\"", escape_csharp(s)))
2239                            .unwrap_or_else(|| json_to_csharp(val))
2240                    })
2241                    .collect();
2242
2243                let rendered = crate::template_env::render(
2244                    "csharp/assertion.jinja",
2245                    minijinja::context! {
2246                        assertion_type => "contains_all",
2247                        field_as_str => field_as_str.clone(),
2248                        values_cs_lower => values_cs_lower,
2249                    },
2250                );
2251                out.push_str(&rendered);
2252            }
2253        }
2254        "not_contains" => {
2255            if let Some(expected) = &assertion.value {
2256                let cs_val = json_to_csharp(expected);
2257
2258                let rendered = crate::template_env::render(
2259                    "csharp/assertion.jinja",
2260                    minijinja::context! {
2261                        assertion_type => "not_contains",
2262                        field_as_str => field_as_str.clone(),
2263                        cs_val => cs_val,
2264                    },
2265                );
2266                out.push_str(&rendered);
2267            }
2268        }
2269        "not_empty" => {
2270            let rendered = crate::template_env::render(
2271                "csharp/assertion.jinja",
2272                minijinja::context! {
2273                    assertion_type => "not_empty",
2274                    field_expr => field_expr.clone(),
2275                    field_needs_json_serialize => field_needs_json_serialize,
2276                },
2277            );
2278            out.push_str(&rendered);
2279        }
2280        "is_empty" => {
2281            let rendered = crate::template_env::render(
2282                "csharp/assertion.jinja",
2283                minijinja::context! {
2284                    assertion_type => "is_empty",
2285                    field_expr => field_expr.clone(),
2286                    field_needs_json_serialize => field_needs_json_serialize,
2287                },
2288            );
2289            out.push_str(&rendered);
2290        }
2291        "contains_any" => {
2292            if let Some(values) = &assertion.values {
2293                let checks: Vec<String> = values
2294                    .iter()
2295                    .map(|v| {
2296                        let cs_val = json_to_csharp(v);
2297                        format!("{field_as_str}.Contains({cs_val})")
2298                    })
2299                    .collect();
2300                let contains_any_expr = checks.join(" || ");
2301
2302                let rendered = crate::template_env::render(
2303                    "csharp/assertion.jinja",
2304                    minijinja::context! {
2305                        assertion_type => "contains_any",
2306                        contains_any_expr => contains_any_expr,
2307                    },
2308                );
2309                out.push_str(&rendered);
2310            }
2311        }
2312        "greater_than" => {
2313            if let Some(val) = &assertion.value {
2314                let cs_val = json_to_csharp(val);
2315
2316                let rendered = crate::template_env::render(
2317                    "csharp/assertion.jinja",
2318                    minijinja::context! {
2319                        assertion_type => "greater_than",
2320                        field_expr => field_expr.clone(),
2321                        cs_val => cs_val,
2322                    },
2323                );
2324                out.push_str(&rendered);
2325            }
2326        }
2327        "less_than" => {
2328            if let Some(val) = &assertion.value {
2329                let cs_val = json_to_csharp(val);
2330
2331                let rendered = crate::template_env::render(
2332                    "csharp/assertion.jinja",
2333                    minijinja::context! {
2334                        assertion_type => "less_than",
2335                        field_expr => field_expr.clone(),
2336                        cs_val => cs_val,
2337                    },
2338                );
2339                out.push_str(&rendered);
2340            }
2341        }
2342        "greater_than_or_equal" => {
2343            if let Some(val) = &assertion.value {
2344                let cs_val = json_to_csharp(val);
2345
2346                let rendered = crate::template_env::render(
2347                    "csharp/assertion.jinja",
2348                    minijinja::context! {
2349                        assertion_type => "greater_than_or_equal",
2350                        field_expr => field_expr.clone(),
2351                        cs_val => cs_val,
2352                    },
2353                );
2354                out.push_str(&rendered);
2355            }
2356        }
2357        "less_than_or_equal" => {
2358            if let Some(val) = &assertion.value {
2359                let cs_val = json_to_csharp(val);
2360
2361                let rendered = crate::template_env::render(
2362                    "csharp/assertion.jinja",
2363                    minijinja::context! {
2364                        assertion_type => "less_than_or_equal",
2365                        field_expr => field_expr.clone(),
2366                        cs_val => cs_val,
2367                    },
2368                );
2369                out.push_str(&rendered);
2370            }
2371        }
2372        "starts_with" => {
2373            if let Some(expected) = &assertion.value {
2374                let cs_val = json_to_csharp(expected);
2375
2376                let rendered = crate::template_env::render(
2377                    "csharp/assertion.jinja",
2378                    minijinja::context! {
2379                        assertion_type => "starts_with",
2380                        field_expr => field_expr.clone(),
2381                        cs_val => cs_val,
2382                    },
2383                );
2384                out.push_str(&rendered);
2385            }
2386        }
2387        "ends_with" => {
2388            if let Some(expected) = &assertion.value {
2389                let cs_val = json_to_csharp(expected);
2390
2391                let rendered = crate::template_env::render(
2392                    "csharp/assertion.jinja",
2393                    minijinja::context! {
2394                        assertion_type => "ends_with",
2395                        field_expr => field_expr.clone(),
2396                        cs_val => cs_val,
2397                    },
2398                );
2399                out.push_str(&rendered);
2400            }
2401        }
2402        "min_length" => {
2403            if let Some(val) = &assertion.value {
2404                if let Some(n) = val.as_u64() {
2405                    let rendered = crate::template_env::render(
2406                        "csharp/assertion.jinja",
2407                        minijinja::context! {
2408                            assertion_type => "min_length",
2409                            field_expr => field_expr.clone(),
2410                            n => n,
2411                        },
2412                    );
2413                    out.push_str(&rendered);
2414                }
2415            }
2416        }
2417        "max_length" => {
2418            if let Some(val) = &assertion.value {
2419                if let Some(n) = val.as_u64() {
2420                    let rendered = crate::template_env::render(
2421                        "csharp/assertion.jinja",
2422                        minijinja::context! {
2423                            assertion_type => "max_length",
2424                            field_expr => field_expr.clone(),
2425                            n => n,
2426                        },
2427                    );
2428                    out.push_str(&rendered);
2429                }
2430            }
2431        }
2432        "count_min" => {
2433            if let Some(val) = &assertion.value {
2434                if let Some(n) = val.as_u64() {
2435                    let rendered = crate::template_env::render(
2436                        "csharp/assertion.jinja",
2437                        minijinja::context! {
2438                            assertion_type => "count_min",
2439                            field_expr => field_expr.clone(),
2440                            n => n,
2441                        },
2442                    );
2443                    out.push_str(&rendered);
2444                }
2445            }
2446        }
2447        "count_equals" => {
2448            if let Some(val) = &assertion.value {
2449                if let Some(n) = val.as_u64() {
2450                    let rendered = crate::template_env::render(
2451                        "csharp/assertion.jinja",
2452                        minijinja::context! {
2453                            assertion_type => "count_equals",
2454                            field_expr => field_expr.clone(),
2455                            n => n,
2456                        },
2457                    );
2458                    out.push_str(&rendered);
2459                }
2460            }
2461        }
2462        "is_true" => {
2463            let rendered = crate::template_env::render(
2464                "csharp/assertion.jinja",
2465                minijinja::context! {
2466                    assertion_type => "is_true",
2467                    field_expr => field_expr.clone(),
2468                },
2469            );
2470            out.push_str(&rendered);
2471        }
2472        "is_false" => {
2473            let rendered = crate::template_env::render(
2474                "csharp/assertion.jinja",
2475                minijinja::context! {
2476                    assertion_type => "is_false",
2477                    field_expr => field_expr.clone(),
2478                },
2479            );
2480            out.push_str(&rendered);
2481        }
2482        "not_error" => {
2483            // Already handled by the call succeeding without exception.
2484            let rendered = crate::template_env::render(
2485                "csharp/assertion.jinja",
2486                minijinja::context! {
2487                    assertion_type => "not_error",
2488                },
2489            );
2490            out.push_str(&rendered);
2491        }
2492        "error" => {
2493            // Handled at the test method level.
2494            let rendered = crate::template_env::render(
2495                "csharp/assertion.jinja",
2496                minijinja::context! {
2497                    assertion_type => "error",
2498                },
2499            );
2500            out.push_str(&rendered);
2501        }
2502        "method_result" => {
2503            if let Some(method_name) = &assertion.method {
2504                let call_expr = build_csharp_method_call(result_var, method_name, assertion.args.as_ref(), class_name);
2505                let check = assertion.check.as_deref().unwrap_or("is_true");
2506
2507                match check {
2508                    "equals" => {
2509                        if let Some(val) = &assertion.value {
2510                            let is_check_bool_true = val.as_bool() == Some(true);
2511                            let is_check_bool_false = val.as_bool() == Some(false);
2512                            let cs_check_val = json_to_csharp(val);
2513
2514                            let rendered = crate::template_env::render(
2515                                "csharp/assertion.jinja",
2516                                minijinja::context! {
2517                                    assertion_type => "method_result",
2518                                    check => "equals",
2519                                    call_expr => call_expr.clone(),
2520                                    is_check_bool_true => is_check_bool_true,
2521                                    is_check_bool_false => is_check_bool_false,
2522                                    cs_check_val => cs_check_val,
2523                                },
2524                            );
2525                            out.push_str(&rendered);
2526                        }
2527                    }
2528                    "is_true" => {
2529                        let rendered = crate::template_env::render(
2530                            "csharp/assertion.jinja",
2531                            minijinja::context! {
2532                                assertion_type => "method_result",
2533                                check => "is_true",
2534                                call_expr => call_expr.clone(),
2535                            },
2536                        );
2537                        out.push_str(&rendered);
2538                    }
2539                    "is_false" => {
2540                        let rendered = crate::template_env::render(
2541                            "csharp/assertion.jinja",
2542                            minijinja::context! {
2543                                assertion_type => "method_result",
2544                                check => "is_false",
2545                                call_expr => call_expr.clone(),
2546                            },
2547                        );
2548                        out.push_str(&rendered);
2549                    }
2550                    "greater_than_or_equal" => {
2551                        if let Some(val) = &assertion.value {
2552                            let check_n = val.as_u64().unwrap_or(0);
2553
2554                            let rendered = crate::template_env::render(
2555                                "csharp/assertion.jinja",
2556                                minijinja::context! {
2557                                    assertion_type => "method_result",
2558                                    check => "greater_than_or_equal",
2559                                    call_expr => call_expr.clone(),
2560                                    check_n => check_n,
2561                                },
2562                            );
2563                            out.push_str(&rendered);
2564                        }
2565                    }
2566                    "count_min" => {
2567                        if let Some(val) = &assertion.value {
2568                            let check_n = val.as_u64().unwrap_or(0);
2569
2570                            let rendered = crate::template_env::render(
2571                                "csharp/assertion.jinja",
2572                                minijinja::context! {
2573                                    assertion_type => "method_result",
2574                                    check => "count_min",
2575                                    call_expr => call_expr.clone(),
2576                                    check_n => check_n,
2577                                },
2578                            );
2579                            out.push_str(&rendered);
2580                        }
2581                    }
2582                    "is_error" => {
2583                        let rendered = crate::template_env::render(
2584                            "csharp/assertion.jinja",
2585                            minijinja::context! {
2586                                assertion_type => "method_result",
2587                                check => "is_error",
2588                                call_expr => call_expr.clone(),
2589                                exception_class => exception_class,
2590                            },
2591                        );
2592                        out.push_str(&rendered);
2593                    }
2594                    "contains" => {
2595                        if let Some(val) = &assertion.value {
2596                            let cs_check_val = json_to_csharp(val);
2597
2598                            let rendered = crate::template_env::render(
2599                                "csharp/assertion.jinja",
2600                                minijinja::context! {
2601                                    assertion_type => "method_result",
2602                                    check => "contains",
2603                                    call_expr => call_expr.clone(),
2604                                    cs_check_val => cs_check_val,
2605                                },
2606                            );
2607                            out.push_str(&rendered);
2608                        }
2609                    }
2610                    other_check => {
2611                        panic!("C# e2e generator: unsupported method_result check type: {other_check}");
2612                    }
2613                }
2614            } else {
2615                panic!("C# e2e generator: method_result assertion missing 'method' field");
2616            }
2617        }
2618        "matches_regex" => {
2619            if let Some(expected) = &assertion.value {
2620                let cs_val = json_to_csharp(expected);
2621
2622                let rendered = crate::template_env::render(
2623                    "csharp/assertion.jinja",
2624                    minijinja::context! {
2625                        assertion_type => "matches_regex",
2626                        field_expr => field_expr.clone(),
2627                        cs_val => cs_val,
2628                    },
2629                );
2630                out.push_str(&rendered);
2631            }
2632        }
2633        other => {
2634            panic!("C# e2e generator: unsupported assertion type: {other}");
2635        }
2636    }
2637}
2638
2639/// Recursively sort JSON objects so that any key named `"type"` appears first.
2640///
2641/// System.Text.Json's `[JsonPolymorphic]` requires the type discriminator to be
2642/// the first property when deserializing polymorphic types. Fixture config values
2643/// serialised via serde_json preserve insertion/alphabetical order, which may put
2644/// `"type"` after other keys (e.g. `"password"` before `"type"` in auth configs).
2645fn sort_discriminator_first(value: serde_json::Value) -> serde_json::Value {
2646    match value {
2647        serde_json::Value::Object(map) => {
2648            let mut sorted = serde_json::Map::with_capacity(map.len());
2649            // Insert "type" first if present.
2650            if let Some(type_val) = map.get("type") {
2651                sorted.insert("type".to_string(), sort_discriminator_first(type_val.clone()));
2652            }
2653            for (k, v) in map {
2654                if k != "type" {
2655                    sorted.insert(k, sort_discriminator_first(v));
2656                }
2657            }
2658            serde_json::Value::Object(sorted)
2659        }
2660        serde_json::Value::Array(arr) => {
2661            serde_json::Value::Array(arr.into_iter().map(sort_discriminator_first).collect())
2662        }
2663        other => other,
2664    }
2665}
2666
2667/// Convert a `serde_json::Value` to a C# literal string.
2668fn json_to_csharp(value: &serde_json::Value) -> String {
2669    match value {
2670        serde_json::Value::String(s) => format!("\"{}\"", escape_csharp(s)),
2671        serde_json::Value::Bool(true) => "true".to_string(),
2672        serde_json::Value::Bool(false) => "false".to_string(),
2673        serde_json::Value::Number(n) => {
2674            if n.is_f64() {
2675                format!("{}d", n)
2676            } else {
2677                n.to_string()
2678            }
2679        }
2680        serde_json::Value::Null => "null".to_string(),
2681        serde_json::Value::Array(arr) => {
2682            let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2683            format!("new[] {{ {} }}", items.join(", "))
2684        }
2685        serde_json::Value::Object(_) => {
2686            let json_str = serde_json::to_string(value).unwrap_or_default();
2687            format!("\"{}\"", escape_csharp(&json_str))
2688        }
2689    }
2690}
2691
2692/// Build default nested type mappings for C# extraction config types.
2693///
2694/// Maps known Kreuzberg/Kreuzcrawl config field names (in snake_case) to their
2695/// C# record type names (in PascalCase). These defaults allow e2e codegen to
2696/// automatically deserialize nested config objects without requiring explicit
2697/// configuration in alef.toml. User-provided overrides take precedence.
2698fn default_csharp_nested_types() -> HashMap<String, String> {
2699    [
2700        ("chunking", "ChunkingConfig"),
2701        ("ocr", "OcrConfig"),
2702        ("images", "ImageExtractionConfig"),
2703        ("html_output", "HtmlOutputConfig"),
2704        ("language_detection", "LanguageDetectionConfig"),
2705        ("postprocessor", "PostProcessorConfig"),
2706        ("acceleration", "AccelerationConfig"),
2707        ("email", "EmailConfig"),
2708        ("pages", "PageConfig"),
2709        ("pdf_options", "PdfConfig"),
2710        ("layout", "LayoutDetectionConfig"),
2711        ("tree_sitter", "TreeSitterConfig"),
2712        ("structured_extraction", "StructuredExtractionConfig"),
2713        ("content_filter", "ContentFilterConfig"),
2714        ("token_reduction", "TokenReductionOptions"),
2715        ("security_limits", "SecurityLimits"),
2716        ("format", "FormatMetadata"),
2717    ]
2718    .iter()
2719    .map(|(k, v)| (k.to_string(), v.to_string()))
2720    .collect()
2721}
2722
2723/// Emit a C# object initializer for a JSON options object.
2724///
2725/// - camelCase fixture keys → PascalCase C# property names
2726/// - Enum fields (from `enum_fields`) → `EnumType.Member`
2727/// - Nested objects with known type (from `nested_types`) → `JsonSerializer.Deserialize<T>(...)`
2728/// - Arrays → `new List<string> { ... }`
2729/// - Primitives → C# literals via `json_to_csharp`
2730fn csharp_object_initializer(
2731    obj: &serde_json::Map<String, serde_json::Value>,
2732    type_name: &str,
2733    enum_fields: &HashMap<String, String>,
2734    nested_types: &HashMap<String, String>,
2735) -> String {
2736    if obj.is_empty() {
2737        return format!("new {type_name}()");
2738    }
2739
2740    // Snake_case fixture keys for fields that are real C# enums in the binding.
2741    // The fixture string value (e.g. "markdown") maps to `EnumType.Member` (e.g. `OutputFormat.Markdown`).
2742    static IMPLICIT_ENUM_FIELDS: &[(&str, &str)] = &[("output_format", "OutputFormat")];
2743
2744    let props: Vec<String> = obj
2745        .iter()
2746        .map(|(key, val)| {
2747            let pascal_key = key.to_upper_camel_case();
2748            let implicit_enum_type = IMPLICIT_ENUM_FIELDS
2749                .iter()
2750                .find(|(k, _)| *k == key.as_str())
2751                .map(|(_, t)| *t);
2752            let cs_val =
2753                if let Some(enum_type) = enum_fields.get(key.as_str()).map(String::as_str).or(implicit_enum_type) {
2754                    // Enum: EnumType.Member
2755                    if val.is_null() {
2756                        "null".to_string()
2757                    } else {
2758                        let member = val
2759                            .as_str()
2760                            .map(|s| s.to_upper_camel_case())
2761                            .unwrap_or_else(|| "null".to_string());
2762                        format!("{enum_type}.{member}")
2763                    }
2764                } else if let Some(nested_type) = nested_types.get(key.as_str()) {
2765                    // Nested object: JSON deserialization (keys are typically single-word, matching JsonPropertyName)
2766                    let normalized = normalize_csharp_enum_values(val, enum_fields);
2767                    let json_str = serde_json::to_string(&normalized).unwrap_or_default();
2768                    format!(
2769                        "JsonSerializer.Deserialize<{nested_type}>(\"{}\", ConfigOptions)!",
2770                        escape_csharp(&json_str)
2771                    )
2772                } else if let Some(arr) = val.as_array() {
2773                    // Array: List<string>
2774                    let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2775                    format!("new List<string> {{ {} }}", items.join(", "))
2776                } else {
2777                    json_to_csharp(val)
2778                };
2779            format!("{pascal_key} = {cs_val}")
2780        })
2781        .collect();
2782    format!("new {} {{ {} }}", type_name, props.join(", "))
2783}
2784
2785/// Convert enum values in a JSON object to lowercase to match C# [JsonPropertyName] attributes.
2786/// The JSON deserialization uses JsonPropertyName("lowercase_value"), so fixture enum values
2787/// (typically PascalCase like "Tildes") must be converted to lowercase ("tildes") for correct
2788/// deserialization with JsonStringEnumConverter.
2789fn normalize_csharp_enum_values(value: &serde_json::Value, enum_fields: &HashMap<String, String>) -> serde_json::Value {
2790    match value {
2791        serde_json::Value::Object(map) => {
2792            let mut result = map.clone();
2793            for (key, val) in result.iter_mut() {
2794                if enum_fields.contains_key(key) {
2795                    // This is an enum field; convert the string value to lowercase.
2796                    if let Some(s) = val.as_str() {
2797                        *val = serde_json::Value::String(s.to_lowercase());
2798                    }
2799                }
2800            }
2801            serde_json::Value::Object(result)
2802        }
2803        other => other.clone(),
2804    }
2805}
2806
2807// ---------------------------------------------------------------------------
2808// Visitor generation
2809// ---------------------------------------------------------------------------
2810
2811/// Build a C# visitor: add an instantiation line to `setup_lines` and push
2812/// a private nested class declaration to `class_decls` (emitted at class scope,
2813/// outside any method body — C# does not allow local class declarations inside
2814/// methods).  Each fixture gets a unique class name derived from its ID to avoid
2815/// duplicate-name compile errors when multiple visitor fixtures exist per file.
2816/// Returns the visitor variable name for use as a call argument.
2817fn build_csharp_visitor(
2818    setup_lines: &mut Vec<String>,
2819    class_decls: &mut Vec<String>,
2820    fixture_id: &str,
2821    visitor_spec: &crate::fixture::VisitorSpec,
2822) -> String {
2823    use heck::ToUpperCamelCase;
2824    let class_name = format!("{}Visitor", fixture_id.to_upper_camel_case());
2825    let var_name = format!("_visitor_{}", fixture_id.replace('-', "_"));
2826
2827    setup_lines.push(format!("var {var_name} = new {class_name}();"));
2828
2829    // Build the class declaration string (indented for nesting inside the test class).
2830    let mut decl = String::new();
2831    decl.push_str(&format!("    private sealed class {class_name} : IHtmlVisitor\n"));
2832    decl.push_str("    {\n");
2833
2834    // List of all visitor methods that must be implemented by IHtmlVisitor.
2835    let all_methods = [
2836        "visit_element_start",
2837        "visit_element_end",
2838        "visit_text",
2839        "visit_link",
2840        "visit_image",
2841        "visit_heading",
2842        "visit_code_block",
2843        "visit_code_inline",
2844        "visit_list_item",
2845        "visit_list_start",
2846        "visit_list_end",
2847        "visit_table_start",
2848        "visit_table_row",
2849        "visit_table_end",
2850        "visit_blockquote",
2851        "visit_strong",
2852        "visit_emphasis",
2853        "visit_strikethrough",
2854        "visit_underline",
2855        "visit_subscript",
2856        "visit_superscript",
2857        "visit_mark",
2858        "visit_line_break",
2859        "visit_horizontal_rule",
2860        "visit_custom_element",
2861        "visit_definition_list_start",
2862        "visit_definition_term",
2863        "visit_definition_description",
2864        "visit_definition_list_end",
2865        "visit_form",
2866        "visit_input",
2867        "visit_button",
2868        "visit_audio",
2869        "visit_video",
2870        "visit_iframe",
2871        "visit_details",
2872        "visit_summary",
2873        "visit_figure_start",
2874        "visit_figcaption",
2875        "visit_figure_end",
2876    ];
2877
2878    // Emit all methods: use fixture action if specified, otherwise default to Continue.
2879    for method_name in &all_methods {
2880        if let Some(action) = visitor_spec.callbacks.get(*method_name) {
2881            emit_csharp_visitor_method(&mut decl, method_name, action);
2882        } else {
2883            // Default: Continue for methods not in the fixture
2884            emit_csharp_visitor_method(&mut decl, method_name, &CallbackAction::Continue);
2885        }
2886    }
2887
2888    decl.push_str("    }\n");
2889    class_decls.push(decl);
2890
2891    var_name
2892}
2893
2894/// Emit a C# visitor method into a class declaration string.
2895fn emit_csharp_visitor_method(decl: &mut String, method_name: &str, action: &CallbackAction) {
2896    let camel_method = method_to_camel(method_name);
2897    let params = match method_name {
2898        "visit_link" => "NodeContext ctx, string href, string text, string title",
2899        "visit_image" => "NodeContext ctx, string src, string alt, string title",
2900        "visit_heading" => "NodeContext ctx, uint level, string text, string id",
2901        "visit_code_block" => "NodeContext ctx, string lang, string code",
2902        "visit_code_inline"
2903        | "visit_strong"
2904        | "visit_emphasis"
2905        | "visit_strikethrough"
2906        | "visit_underline"
2907        | "visit_subscript"
2908        | "visit_superscript"
2909        | "visit_mark"
2910        | "visit_button"
2911        | "visit_summary"
2912        | "visit_figcaption"
2913        | "visit_definition_term"
2914        | "visit_definition_description" => "NodeContext ctx, string text",
2915        "visit_text" => "NodeContext ctx, string text",
2916        "visit_list_item" => "NodeContext ctx, bool ordered, string marker, string text",
2917        "visit_blockquote" => "NodeContext ctx, string content, ulong depth",
2918        "visit_table_row" => "NodeContext ctx, List<string> cells, bool isHeader",
2919        "visit_custom_element" => "NodeContext ctx, string tagName, string html",
2920        "visit_form" => "NodeContext ctx, string actionUrl, string method",
2921        "visit_input" => "NodeContext ctx, string inputType, string name, string value",
2922        "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, string src",
2923        "visit_details" => "NodeContext ctx, bool isOpen",
2924        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2925            "NodeContext ctx, string output"
2926        }
2927        "visit_list_start" => "NodeContext ctx, bool ordered",
2928        "visit_list_end" => "NodeContext ctx, bool ordered, string output",
2929        "visit_element_start"
2930        | "visit_table_start"
2931        | "visit_definition_list_start"
2932        | "visit_figure_start"
2933        | "visit_line_break"
2934        | "visit_horizontal_rule" => "NodeContext ctx",
2935        _ => "NodeContext ctx",
2936    };
2937
2938    let (action_type, action_value) = match action {
2939        CallbackAction::Skip => ("skip", String::new()),
2940        CallbackAction::Continue => ("continue", String::new()),
2941        CallbackAction::PreserveHtml => ("preserve_html", String::new()),
2942        CallbackAction::Custom { output } => ("custom", escape_csharp(output)),
2943        CallbackAction::CustomTemplate { template } => {
2944            let camel = snake_case_template_to_camel(template);
2945            ("custom_template", escape_csharp(&camel))
2946        }
2947    };
2948
2949    let rendered = crate::template_env::render(
2950        "csharp/visitor_method.jinja",
2951        minijinja::context! {
2952            camel_method => camel_method,
2953            params => params,
2954            action_type => action_type,
2955            action_value => action_value,
2956        },
2957    );
2958    let _ = write!(decl, "{}", rendered);
2959}
2960
2961/// Convert snake_case method names to C# PascalCase.
2962fn method_to_camel(snake: &str) -> String {
2963    use heck::ToUpperCamelCase;
2964    snake.to_upper_camel_case()
2965}
2966
2967/// Rewrite `{snake_case}` placeholders in a custom template to `{camelCase}` so
2968/// they match C# parameter names (which alef emits in camelCase).
2969fn snake_case_template_to_camel(template: &str) -> String {
2970    use heck::ToLowerCamelCase;
2971    let mut out = String::with_capacity(template.len());
2972    let mut chars = template.chars().peekable();
2973    while let Some(c) = chars.next() {
2974        if c == '{' {
2975            let mut name = String::new();
2976            while let Some(&nc) = chars.peek() {
2977                if nc == '}' {
2978                    chars.next();
2979                    break;
2980                }
2981                name.push(nc);
2982                chars.next();
2983            }
2984            out.push('{');
2985            out.push_str(&name.to_lower_camel_case());
2986            out.push('}');
2987        } else {
2988            out.push(c);
2989        }
2990    }
2991    out
2992}
2993
2994/// Build a C# call expression for a `method_result` assertion on a tree-sitter Tree.
2995///
2996/// Maps well-known method names to the appropriate C# static helper calls on the
2997/// generated lib class, falling back to `result_var.PascalCase()` for unknowns.
2998fn build_csharp_method_call(
2999    result_var: &str,
3000    method_name: &str,
3001    args: Option<&serde_json::Value>,
3002    class_name: &str,
3003) -> String {
3004    match method_name {
3005        "root_child_count" => format!("{result_var}.RootNode.ChildCount"),
3006        "root_node_type" => format!("{result_var}.RootNode.Kind"),
3007        "named_children_count" => format!("{result_var}.RootNode.NamedChildCount"),
3008        "has_error_nodes" => format!("{class_name}.TreeHasErrorNodes({result_var})"),
3009        "error_count" | "tree_error_count" => format!("{class_name}.TreeErrorCount({result_var})"),
3010        "tree_to_sexp" => format!("{class_name}.TreeToSexp({result_var})"),
3011        "contains_node_type" => {
3012            let node_type = args
3013                .and_then(|a| a.get("node_type"))
3014                .and_then(|v| v.as_str())
3015                .unwrap_or("");
3016            format!("{class_name}.TreeContainsNodeType({result_var}, \"{node_type}\")")
3017        }
3018        "find_nodes_by_type" => {
3019            let node_type = args
3020                .and_then(|a| a.get("node_type"))
3021                .and_then(|v| v.as_str())
3022                .unwrap_or("");
3023            format!("{class_name}.FindNodesByType({result_var}, \"{node_type}\")")
3024        }
3025        "run_query" => {
3026            let query_source = args
3027                .and_then(|a| a.get("query_source"))
3028                .and_then(|v| v.as_str())
3029                .unwrap_or("");
3030            let language = args
3031                .and_then(|a| a.get("language"))
3032                .and_then(|v| v.as_str())
3033                .unwrap_or("");
3034            format!("{class_name}.RunQuery({result_var}, \"{language}\", \"{query_source}\", source)")
3035        }
3036        _ => {
3037            use heck::ToUpperCamelCase;
3038            let pascal = method_name.to_upper_camel_case();
3039            format!("{result_var}.{pascal}()")
3040        }
3041    }
3042}
3043
3044fn fixture_has_csharp_callable(fixture: &Fixture, e2e_config: &E2eConfig) -> bool {
3045    // HTTP fixtures are handled separately — not our concern here.
3046    if fixture.is_http_test() {
3047        return false;
3048    }
3049    // Use resolve_call_for_fixture to support auto-routing via select_when.
3050    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
3051    let cs_override = call_config
3052        .overrides
3053        .get("csharp")
3054        .or_else(|| e2e_config.call.overrides.get("csharp"));
3055    // When a client_factory is configured the fixture is callable via the client pattern.
3056    if cs_override.and_then(|o| o.client_factory.as_deref()).is_some() {
3057        return true;
3058    }
3059    // C# binding provides a default class name (e.g., KreuzcrawlLib) if not overridden,
3060    // so any function name makes a callable available.
3061    cs_override.and_then(|o| o.function.as_deref()).is_some() || !call_config.function.is_empty()
3062}
3063
3064/// Classify a fixture string value that maps to a `bytes` argument.
3065/// Determines whether to treat it as a file path, inline text, or base64-encoded data.
3066fn classify_bytes_value_csharp(s: &str) -> String {
3067    // File paths: start with alphanumeric/underscore, contain "/" with extension
3068    // e.g., "pdf/fake.pdf", "images/test.png"
3069    if let Some(first) = s.chars().next() {
3070        if first.is_ascii_alphanumeric() || first == '_' {
3071            if let Some(slash_pos) = s.find('/') {
3072                if slash_pos > 0 {
3073                    let after_slash = &s[slash_pos + 1..];
3074                    if after_slash.contains('.') && !after_slash.is_empty() {
3075                        // File path: use File.ReadAllBytes(path)
3076                        return format!("System.IO.File.ReadAllBytes(\"{}\")", s);
3077                    }
3078                }
3079            }
3080        }
3081    }
3082
3083    // Inline text: starts with markup or contains spaces
3084    // e.g., "<html>...", "{...}", "[...]", "text with spaces"
3085    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
3086        // Inline text: use System.Text.Encoding.UTF8.GetBytes()
3087        return format!("System.Text.Encoding.UTF8.GetBytes(\"{}\")", escape_csharp(s));
3088    }
3089
3090    // Base64: base64-like pattern (uppercase/lowercase letters, digits, +, /, =)
3091    // e.g., "/9j/4AAQ", "SGVsbG8gV29ybGQ="
3092    // Use Convert.FromBase64String()
3093    format!("System.Convert.FromBase64String(\"{}\")", s)
3094}
3095
3096#[cfg(test)]
3097mod tests {
3098    use crate::config::{CallConfig, E2eConfig, SelectWhen};
3099    use crate::fixture::Fixture;
3100    use std::collections::HashMap;
3101
3102    fn make_fixture_with_input(id: &str, input: serde_json::Value) -> Fixture {
3103        Fixture {
3104            id: id.to_string(),
3105            category: None,
3106            description: "test fixture".to_string(),
3107            tags: vec![],
3108            skip: None,
3109            env: None,
3110            call: None,
3111            input,
3112            mock_response: None,
3113            source: String::new(),
3114            http: None,
3115            assertions: vec![],
3116            visitor: None,
3117        }
3118    }
3119
3120    /// Test that resolve_call_for_fixture correctly routes to batch_scrape
3121    /// when input has batch_urls and select_when condition matches.
3122    #[test]
3123    fn test_csharp_select_when_routes_to_batch_scrape() {
3124        let mut calls = HashMap::new();
3125        calls.insert(
3126            "batch_scrape".to_string(),
3127            CallConfig {
3128                function: "BatchScrape".to_string(),
3129                module: "KreuzBrowser".to_string(),
3130                select_when: Some(SelectWhen::InputHas("batch_urls".to_string())),
3131                ..CallConfig::default()
3132            },
3133        );
3134
3135        let e2e_config = E2eConfig {
3136            call: CallConfig {
3137                function: "Scrape".to_string(),
3138                module: "KreuzBrowser".to_string(),
3139                ..CallConfig::default()
3140            },
3141            calls,
3142            ..E2eConfig::default()
3143        };
3144
3145        // Fixture with batch_urls but no explicit call field should route to batch_scrape
3146        let fixture = make_fixture_with_input("batch_empty_urls", serde_json::json!({ "batch_urls": [] }));
3147
3148        let resolved_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
3149        assert_eq!(resolved_call.function, "BatchScrape");
3150
3151        // Fixture without batch_urls should fall back to default Scrape
3152        let fixture_no_batch =
3153            make_fixture_with_input("simple_scrape", serde_json::json!({ "url": "https://example.com" }));
3154        let resolved_default =
3155            e2e_config.resolve_call_for_fixture(fixture_no_batch.call.as_deref(), &fixture_no_batch.input);
3156        assert_eq!(resolved_default.function, "Scrape");
3157    }
3158}