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    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
776    let lang = "csharp";
777    let cs_overrides = call_config.overrides.get(lang);
778
779    // Streaming branch: chat_stream returns IAsyncEnumerable<ChatCompletionChunk>,
780    // not Task<T>. Emit `await foreach` over the stream, building local
781    // aggregator vars (`chunks`, `streamContent`, `streamComplete`, ...) and
782    // asserting on those locals — never on response pseudo-fields.
783    let raw_function_name = cs_overrides
784        .and_then(|o| o.function.as_ref())
785        .cloned()
786        .unwrap_or_else(|| call_config.function.clone());
787    if raw_function_name == "chat_stream" {
788        render_chat_stream_test_method(
789            out,
790            fixture,
791            class_name,
792            call_config,
793            cs_overrides,
794            e2e_config,
795            enum_fields,
796            nested_types,
797            exception_class,
798        );
799        return;
800    }
801
802    let effective_function_name = cs_overrides
803        .and_then(|o| o.function.as_ref())
804        .cloned()
805        .unwrap_or_else(|| call_config.function.to_upper_camel_case());
806    let effective_result_var = &call_config.result_var;
807    let effective_is_async = call_config.r#async;
808    let function_name = effective_function_name.as_str();
809    let result_var = effective_result_var.as_str();
810    let is_async = effective_is_async;
811    let args = call_config.args.as_slice();
812
813    // Per-call overrides: result shape, void returns, extra trailing args.
814    // Pull `result_is_simple` from the per-call config first (call-level value
815    // wins, then per-language override, then the top-level call's value).
816    let per_call_result_is_simple = call_config.result_is_simple || cs_overrides.is_some_and(|o| o.result_is_simple);
817    // result_is_bytes: when set, the call returns a raw byte[] in C# (not a
818    // struct with named fields). Mirrors the C codegen flag added in 50e1d309.
819    // Treat byte-buffer returns like result_is_simple (no struct accessors) and
820    // emit byte-specific assertions for `not_empty`/`is_empty`.
821    let per_call_result_is_bytes = call_config.result_is_bytes || cs_overrides.is_some_and(|o| o.result_is_bytes);
822    let effective_result_is_simple = result_is_simple || per_call_result_is_simple || per_call_result_is_bytes;
823    let effective_result_is_bytes = per_call_result_is_bytes;
824    let returns_void = call_config.returns_void;
825    let extra_args_slice: &[String] = cs_overrides.map_or(&[], |o| o.extra_args.as_slice());
826    // options_type: prefer per-call override, fall back to top-level csharp override.
827    let top_level_options_type = e2e_config
828        .call
829        .overrides
830        .get("csharp")
831        .and_then(|o| o.options_type.as_deref());
832    let effective_options_type = cs_overrides
833        .and_then(|o| o.options_type.as_deref())
834        .or(top_level_options_type);
835
836    // options_via: how to construct the options object. Supported values:
837    //   "kwargs" (default) — emit a C# object initializer (`new T { ... }`).
838    //   "from_json"        — emit `JsonSerializer.Deserialize<T>(json, ConfigOptions)!`,
839    //                        sidestepping per-field type ambiguity for fields like
840    //                        `JsonElement?` (untagged unions) or `List<NamedRecord>`
841    //                        (where the codegen would otherwise default to `List<string>`).
842    let top_level_options_via = e2e_config
843        .call
844        .overrides
845        .get("csharp")
846        .and_then(|o| o.options_via.as_deref());
847    let effective_options_via = cs_overrides
848        .and_then(|o| o.options_via.as_deref())
849        .or(top_level_options_via);
850
851    let (mut setup_lines, args_str) = build_args_and_setup(
852        &fixture.input,
853        args,
854        class_name,
855        effective_options_type,
856        effective_options_via,
857        enum_fields,
858        nested_types,
859        fixture,
860    );
861
862    // Build visitor if present: instantiate in method body, declare class at file scope.
863    let mut visitor_arg = String::new();
864    let has_visitor = fixture.visitor.is_some();
865    if let Some(visitor_spec) = &fixture.visitor {
866        visitor_arg = build_csharp_visitor(&mut setup_lines, visitor_class_decls, &fixture.id, visitor_spec);
867    }
868
869    // When a visitor is present, embed it in the options object instead of passing as a separate arg.
870    // args_str should contain the function arguments with null for missing options (e.g., "html, null").
871    // We need to replace that null with a ConversionOptions instance that has Visitor set.
872    let final_args = if has_visitor && !visitor_arg.is_empty() {
873        let opts_type = effective_options_type.unwrap_or("ConversionOptions");
874        if args_str.contains("JsonSerializer.Deserialize") {
875            // Deserialize form: extract the deserialized object and set Visitor on it
876            setup_lines.push(format!("var options = {args_str};"));
877            setup_lines.push(format!("options.Visitor = {visitor_arg};"));
878            "options".to_string()
879        } else if args_str.ends_with(", null") {
880            // Replace trailing ", null" with options
881            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
882            let trimmed = args_str[..args_str.len() - 6].to_string(); // Remove ", null" (6 chars including space)
883            format!("{trimmed}, options")
884        } else if args_str.contains(", null,") {
885            // Options parameter is null in the middle; replace it
886            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
887            args_str.replace(", null,", ", options,")
888        } else if args_str.is_empty() {
889            // No options were provided; create new instance with Visitor
890            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
891            "options".to_string()
892        } else {
893            // Fall back to appending options
894            setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
895            format!("{args_str}, options")
896        }
897    } else if extra_args_slice.is_empty() {
898        args_str
899    } else if args_str.is_empty() {
900        extra_args_slice.join(", ")
901    } else {
902        format!("{args_str}, {}", extra_args_slice.join(", "))
903    };
904
905    // Always use the base function name (Convert) regardless of visitor presence
906    // The visitor is now handled internally via options.Visitor
907    let effective_function_name = function_name.to_string();
908
909    let return_type = if is_async { "async Task" } else { "void" };
910    let await_kw = if is_async { "await " } else { "" };
911
912    // Client factory: when set, create a client instance and call methods on it
913    // rather than using static class calls.
914    let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
915        e2e_config
916            .call
917            .overrides
918            .get("csharp")
919            .and_then(|o| o.client_factory.as_deref())
920    });
921    let call_target = if client_factory.is_some() {
922        "client".to_string()
923    } else {
924        class_name.to_string()
925    };
926
927    // Build client factory setup code. For fixtures whose env block sets
928    // an `api_key_var` AND that have neither `mock_response` nor an `http`
929    // override (live-smoke tests against real provider APIs), prepend an
930    // early-return when the env var is unset so CI without API keys does
931    // not fail with `not found: No mock route for ...`. Mirrors the
932    // Elixir / Python skip pattern documented in CHANGELOG v0.15.9.
933    let mut client_factory_setup = String::new();
934    if let Some(factory) = client_factory {
935        let factory_name = factory.to_upper_camel_case();
936        let fixture_id = &fixture.id;
937        let is_live_smoke = fixture.mock_response.is_none()
938            && fixture.http.is_none()
939            && fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()).is_some();
940        if is_live_smoke {
941            let api_key_var = fixture
942                .env
943                .as_ref()
944                .and_then(|e| e.api_key_var.as_deref())
945                .unwrap_or("");
946            client_factory_setup.push_str(&format!(
947                "        var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
948            ));
949            client_factory_setup.push_str("        if (string.IsNullOrEmpty(apiKey)) { return; }\n");
950            client_factory_setup.push_str(&format!(
951                "        var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
952            ));
953        } else if fixture.has_host_root_route() {
954            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
955            client_factory_setup.push_str(&format!(
956                "        var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
957            ));
958            client_factory_setup.push_str(&format!("        var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
959            client_factory_setup.push_str(&format!(
960                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
961            ));
962        } else {
963            client_factory_setup.push_str(&format!("        var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
964            client_factory_setup.push_str(&format!(
965                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
966            ));
967        }
968    }
969
970    // Build call expression
971    let call_expr = format!("{}({})", effective_function_name, final_args);
972
973    // Merge per-call C# `enum_fields` keys with the global file-level
974    // `fields_enum` set so call-specific enum-typed result fields (e.g.
975    // BatchObject's `status` → BatchStatus) trigger enum coercion in
976    // assertions even when the global set does not list them. The
977    // file-level `enum_fields` argument carries the default-call's override;
978    // `cs_overrides.enum_fields` carries the per-fixture-call's override
979    // (e.g. retrieve_batch.overrides.csharp.enum_fields).
980    let mut effective_enum_fields: std::collections::HashSet<String> = e2e_config.fields_enum.clone();
981    for k in enum_fields.keys() {
982        effective_enum_fields.insert(k.clone());
983    }
984    if let Some(o) = cs_overrides {
985        for k in o.enum_fields.keys() {
986            effective_enum_fields.insert(k.clone());
987        }
988    }
989
990    // Build assertions body for non-error cases
991    let mut assertions_body = String::new();
992    if !expects_error && !returns_void {
993        for assertion in &fixture.assertions {
994            render_assertion(
995                &mut assertions_body,
996                assertion,
997                result_var,
998                class_name,
999                exception_class,
1000                field_resolver,
1001                effective_result_is_simple,
1002                call_config.result_is_vec || cs_overrides.is_some_and(|o| o.result_is_vec),
1003                call_config.result_is_array,
1004                effective_result_is_bytes,
1005                &effective_enum_fields,
1006            );
1007        }
1008    }
1009
1010    let ctx = minijinja::context! {
1011        is_skipped => false,
1012        expects_error => expects_error,
1013        description => description,
1014        return_type => return_type,
1015        method_name => method_name,
1016        async_kw => await_kw,
1017        call_target => call_target,
1018        setup_lines => setup_lines.clone(),
1019        call_expr => call_expr,
1020        exception_class => exception_class,
1021        client_factory_setup => client_factory_setup,
1022        has_usable_assertion => !expects_error && !returns_void,
1023        result_var => result_var,
1024        assertions_body => assertions_body,
1025    };
1026
1027    let rendered = crate::template_env::render("csharp/test_method.jinja", ctx);
1028    // Indent each line by 4 spaces to nest inside the test class
1029    for line in rendered.lines() {
1030        out.push_str("    ");
1031        out.push_str(line);
1032        out.push('\n');
1033    }
1034}
1035
1036/// Render a `chat_stream` test method. The C# binding emits
1037/// `IAsyncEnumerable<ChatCompletionChunk> ChatStream(req)` (not `Task<T>`), so
1038/// the test body uses `await foreach` to drive the stream and aggregates
1039/// per-chunk data into local vars (`chunks`, `streamContent`, `streamComplete`,
1040/// optional `lastFinishReason`/`toolCallsJson`/`toolCalls0FunctionName`/`totalTokens`).
1041/// Assertions then run against those locals — never against pseudo-fields on a
1042/// response object.
1043#[allow(clippy::too_many_arguments)]
1044fn render_chat_stream_test_method(
1045    out: &mut String,
1046    fixture: &Fixture,
1047    class_name: &str,
1048    call_config: &crate::config::CallConfig,
1049    cs_overrides: Option<&crate::config::CallOverride>,
1050    e2e_config: &E2eConfig,
1051    enum_fields: &HashMap<String, String>,
1052    nested_types: &HashMap<String, String>,
1053    exception_class: &str,
1054) {
1055    let method_name = fixture.id.to_upper_camel_case();
1056    let description = &fixture.description;
1057    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1058
1059    let effective_function_name = cs_overrides
1060        .and_then(|o| o.function.as_ref())
1061        .cloned()
1062        .unwrap_or_else(|| call_config.function.to_upper_camel_case());
1063    let function_name = effective_function_name.as_str();
1064    let args = call_config.args.as_slice();
1065
1066    let top_level_options_type = e2e_config
1067        .call
1068        .overrides
1069        .get("csharp")
1070        .and_then(|o| o.options_type.as_deref());
1071    let effective_options_type = cs_overrides
1072        .and_then(|o| o.options_type.as_deref())
1073        .or(top_level_options_type);
1074    let top_level_options_via = e2e_config
1075        .call
1076        .overrides
1077        .get("csharp")
1078        .and_then(|o| o.options_via.as_deref());
1079    let effective_options_via = cs_overrides
1080        .and_then(|o| o.options_via.as_deref())
1081        .or(top_level_options_via);
1082
1083    let (setup_lines, args_str) = build_args_and_setup(
1084        &fixture.input,
1085        args,
1086        class_name,
1087        effective_options_type,
1088        effective_options_via,
1089        enum_fields,
1090        nested_types,
1091        fixture,
1092    );
1093
1094    let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
1095        e2e_config
1096            .call
1097            .overrides
1098            .get("csharp")
1099            .and_then(|o| o.client_factory.as_deref())
1100    });
1101    let mut client_factory_setup = String::new();
1102    if let Some(factory) = client_factory {
1103        let factory_name = factory.to_upper_camel_case();
1104        let fixture_id = &fixture.id;
1105        let is_live_smoke = fixture.mock_response.is_none()
1106            && fixture.http.is_none()
1107            && fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()).is_some();
1108        if is_live_smoke {
1109            let api_key_var = fixture
1110                .env
1111                .as_ref()
1112                .and_then(|e| e.api_key_var.as_deref())
1113                .unwrap_or("");
1114            client_factory_setup.push_str(&format!(
1115                "        var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1116            ));
1117            client_factory_setup.push_str("        if (string.IsNullOrEmpty(apiKey)) { return; }\n");
1118            client_factory_setup.push_str(&format!(
1119                "        var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
1120            ));
1121        } else if fixture.has_host_root_route() {
1122            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1123            client_factory_setup.push_str(&format!(
1124                "        var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
1125            ));
1126            client_factory_setup.push_str(&format!("        var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1127            client_factory_setup.push_str(&format!(
1128                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1129            ));
1130        } else {
1131            client_factory_setup.push_str(&format!(
1132                "        var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"
1133            ));
1134            client_factory_setup.push_str(&format!(
1135                "        var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1136            ));
1137        }
1138    }
1139
1140    let call_target = if client_factory.is_some() { "client" } else { class_name };
1141    let call_expr = format!("{call_target}.{function_name}({args_str})");
1142
1143    // Detect which aggregators a fixture's assertions actually need.
1144    let mut needs_finish_reason = false;
1145    let mut needs_tool_calls_json = false;
1146    let mut needs_tool_calls_0_function_name = false;
1147    let mut needs_total_tokens = false;
1148    for a in &fixture.assertions {
1149        if let Some(f) = a.field.as_deref() {
1150            match f {
1151                "finish_reason" => needs_finish_reason = true,
1152                "tool_calls" => needs_tool_calls_json = true,
1153                "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
1154                "usage.total_tokens" => needs_total_tokens = true,
1155                _ => {}
1156            }
1157        }
1158    }
1159
1160    let mut body = String::new();
1161    let _ = writeln!(body, "    [Fact]");
1162    let _ = writeln!(body, "    public async Task Test_{method_name}()");
1163    let _ = writeln!(body, "    {{");
1164    let _ = writeln!(body, "        // {description}");
1165    if !client_factory_setup.is_empty() {
1166        body.push_str(&client_factory_setup);
1167    }
1168    for line in &setup_lines {
1169        let _ = writeln!(body, "        {line}");
1170    }
1171
1172    if expects_error {
1173        // Wrap the foreach in a lambda so the IAsyncEnumerable is actually
1174        // consumed (otherwise the producer never runs and no exception is raised).
1175        let _ = writeln!(
1176            body,
1177            "        await Assert.ThrowsAnyAsync<{exception_class}>(async () => {{"
1178        );
1179        let _ = writeln!(body, "            await foreach (var _chunk in {call_expr}) {{ }}");
1180        body.push_str("        });\n");
1181        body.push_str("    }\n");
1182        for line in body.lines() {
1183            out.push_str("    ");
1184            out.push_str(line);
1185            out.push('\n');
1186        }
1187        return;
1188    }
1189
1190    body.push_str("        var chunks = new List<ChatCompletionChunk>();\n");
1191    body.push_str("        var streamContent = new System.Text.StringBuilder();\n");
1192    body.push_str("        var streamComplete = false;\n");
1193    if needs_finish_reason {
1194        body.push_str("        string? lastFinishReason = null;\n");
1195    }
1196    if needs_tool_calls_json {
1197        body.push_str("        string? toolCallsJson = null;\n");
1198    }
1199    if needs_tool_calls_0_function_name {
1200        body.push_str("        string? toolCalls0FunctionName = null;\n");
1201    }
1202    if needs_total_tokens {
1203        body.push_str("        long? totalTokens = null;\n");
1204    }
1205    let _ = writeln!(body, "        await foreach (var chunk in {call_expr})");
1206    body.push_str("        {\n");
1207    body.push_str("            chunks.Add(chunk);\n");
1208    body.push_str(
1209        "            var choice = chunk.Choices != null && chunk.Choices.Count > 0 ? chunk.Choices[0] : null;\n",
1210    );
1211    body.push_str("            if (choice != null)\n");
1212    body.push_str("            {\n");
1213    body.push_str("                var delta = choice.Delta;\n");
1214    body.push_str("                if (delta != null && !string.IsNullOrEmpty(delta.Content))\n");
1215    body.push_str("                {\n");
1216    body.push_str("                    streamContent.Append(delta.Content);\n");
1217    body.push_str("                }\n");
1218    if needs_finish_reason {
1219        // Streaming accumulator must use the wire-form snake_case representation
1220        // (e.g. `tool_calls`) so equality assertions against the fixture-side
1221        // string match. `.ToString().ToLower()` collapses compound PascalCase
1222        // names like `ToolCalls` to `toolcalls` (no underscore), causing
1223        // assertion failures. `JsonNamingPolicy.SnakeCaseLower.ConvertName`
1224        // mirrors the policy used by the global `JsonStringEnumConverter`,
1225        // matching exactly what serde would emit on the wire.
1226        body.push_str("                if (choice.FinishReason != null)\n");
1227        body.push_str("                {\n");
1228        body.push_str(
1229            "                    lastFinishReason = JsonNamingPolicy.SnakeCaseLower.ConvertName(choice.FinishReason.ToString()!);\n",
1230        );
1231        body.push_str("                }\n");
1232    }
1233    if needs_tool_calls_json || needs_tool_calls_0_function_name {
1234        body.push_str("                var tcs = delta?.ToolCalls;\n");
1235        body.push_str("                if (tcs != null && tcs.Count > 0)\n");
1236        body.push_str("                {\n");
1237        if needs_tool_calls_json {
1238            body.push_str(
1239                "                    toolCallsJson ??= JsonSerializer.Serialize(tcs.Select(tc => new { function = new { name = tc.Function?.Name } }));\n",
1240            );
1241        }
1242        if needs_tool_calls_0_function_name {
1243            body.push_str("                    toolCalls0FunctionName ??= tcs[0].Function?.Name;\n");
1244        }
1245        body.push_str("                }\n");
1246    }
1247    body.push_str("            }\n");
1248    if needs_total_tokens {
1249        body.push_str("            if (chunk.Usage != null)\n");
1250        body.push_str("            {\n");
1251        body.push_str("                totalTokens = chunk.Usage.TotalTokens;\n");
1252        body.push_str("            }\n");
1253    }
1254    body.push_str("        }\n");
1255    body.push_str("        streamComplete = true;\n");
1256
1257    // Emit assertions on local aggregator vars.
1258    let mut had_explicit_complete = false;
1259    for assertion in &fixture.assertions {
1260        if assertion.field.as_deref() == Some("stream_complete") {
1261            had_explicit_complete = true;
1262        }
1263        emit_chat_stream_assertion(&mut body, assertion);
1264    }
1265    if !had_explicit_complete {
1266        body.push_str("        Assert.True(streamComplete);\n");
1267    }
1268
1269    body.push_str("    }\n");
1270
1271    for line in body.lines() {
1272        out.push_str("    ");
1273        out.push_str(line);
1274        out.push('\n');
1275    }
1276}
1277
1278/// Map a streaming fixture assertion to an `Assert` call on the local aggregator
1279/// variable produced by `render_chat_stream_test_method`. Pseudo-fields like
1280/// `chunks` / `stream_content` / `stream_complete` resolve to in-method locals.
1281fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion) {
1282    let atype = assertion.assertion_type.as_str();
1283    if atype == "not_error" || atype == "error" {
1284        return;
1285    }
1286    let field = assertion.field.as_deref().unwrap_or("");
1287
1288    enum Kind {
1289        Chunks,
1290        Bool,
1291        Str,
1292        IntTokens,
1293        Json,
1294        Unsupported,
1295    }
1296
1297    let (expr, kind) = match field {
1298        "chunks" => ("chunks", Kind::Chunks),
1299        "stream_content" => ("streamContent.ToString()", Kind::Str),
1300        "stream_complete" => ("streamComplete", Kind::Bool),
1301        "no_chunks_after_done" => ("streamComplete", Kind::Bool),
1302        "finish_reason" => ("lastFinishReason", Kind::Str),
1303        "tool_calls" => ("toolCallsJson", Kind::Json),
1304        "tool_calls[0].function.name" => ("toolCalls0FunctionName", Kind::Str),
1305        "usage.total_tokens" => ("totalTokens", Kind::IntTokens),
1306        _ => ("", Kind::Unsupported),
1307    };
1308
1309    if matches!(kind, Kind::Unsupported) {
1310        let _ = writeln!(
1311            out,
1312            "        // skipped: streaming assertion on unsupported field '{field}'"
1313        );
1314        return;
1315    }
1316
1317    match (atype, &kind) {
1318        ("count_min", Kind::Chunks) => {
1319            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1320                let _ = writeln!(
1321                    out,
1322                    "        Assert.True(chunks.Count >= {n}, \"expected at least {n} chunks\");"
1323                );
1324            }
1325        }
1326        ("count_equals", Kind::Chunks) => {
1327            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1328                let _ = writeln!(out, "        Assert.Equal({n}, chunks.Count);");
1329            }
1330        }
1331        ("equals", Kind::Str) => {
1332            if let Some(val) = &assertion.value {
1333                let cs_val = json_to_csharp(val);
1334                let _ = writeln!(out, "        Assert.Equal({cs_val}, {expr});");
1335            }
1336        }
1337        ("contains", Kind::Str) => {
1338            if let Some(val) = &assertion.value {
1339                let cs_val = json_to_csharp(val);
1340                let _ = writeln!(out, "        Assert.Contains({cs_val}, {expr} ?? string.Empty);");
1341            }
1342        }
1343        ("not_empty", Kind::Str) => {
1344            let _ = writeln!(out, "        Assert.False(string.IsNullOrEmpty({expr}));");
1345        }
1346        ("not_empty", Kind::Json) => {
1347            let _ = writeln!(out, "        Assert.NotNull({expr});");
1348        }
1349        ("is_empty", Kind::Str) => {
1350            let _ = writeln!(out, "        Assert.True(string.IsNullOrEmpty({expr}));");
1351        }
1352        ("is_true", Kind::Bool) => {
1353            let _ = writeln!(out, "        Assert.True({expr});");
1354        }
1355        ("is_false", Kind::Bool) => {
1356            let _ = writeln!(out, "        Assert.False({expr});");
1357        }
1358        ("greater_than_or_equal", Kind::IntTokens) => {
1359            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1360                let _ = writeln!(out, "        Assert.True({expr} >= {n}, \"expected >= {n}\");");
1361            }
1362        }
1363        ("equals", Kind::IntTokens) => {
1364            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1365                let _ = writeln!(out, "        Assert.Equal((long?){n}, {expr});");
1366            }
1367        }
1368        _ => {
1369            let _ = writeln!(
1370                out,
1371                "        // skipped: streaming assertion '{atype}' on field '{field}' not supported"
1372            );
1373        }
1374    }
1375}
1376
1377/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1378///
1379/// Returns `(setup_lines, args_string)`.
1380#[allow(clippy::too_many_arguments)]
1381fn build_args_and_setup(
1382    input: &serde_json::Value,
1383    args: &[crate::config::ArgMapping],
1384    class_name: &str,
1385    options_type: Option<&str>,
1386    options_via: Option<&str>,
1387    enum_fields: &HashMap<String, String>,
1388    nested_types: &HashMap<String, String>,
1389    fixture: &crate::fixture::Fixture,
1390) -> (Vec<String>, String) {
1391    let fixture_id = &fixture.id;
1392    if args.is_empty() {
1393        return (Vec::new(), String::new());
1394    }
1395
1396    let mut setup_lines: Vec<String> = Vec::new();
1397    let mut parts: Vec<String> = Vec::new();
1398
1399    for arg in args {
1400        if arg.arg_type == "bytes" {
1401            // bytes args must be passed as byte[] in C#.
1402            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1403            let val = input.get(field);
1404            match val {
1405                None | Some(serde_json::Value::Null) if arg.optional => {
1406                    parts.push("null".to_string());
1407                }
1408                None | Some(serde_json::Value::Null) => {
1409                    parts.push("System.Array.Empty<byte>()".to_string());
1410                }
1411                Some(v) => {
1412                    // Classify the value to determine how to interpret it:
1413                    // - File paths (like "pdf/fake.pdf") → File.ReadAllBytes(path)
1414                    // - Inline text → System.Text.Encoding.UTF8.GetBytes()
1415                    // - Base64 → Convert.FromBase64String()
1416                    if let Some(s) = v.as_str() {
1417                        let bytes_code = classify_bytes_value_csharp(s);
1418                        parts.push(bytes_code);
1419                    } else {
1420                        // Literal arrays or other non-string types: use as-is
1421                        let cs_str = json_to_csharp(v);
1422                        parts.push(format!("System.Text.Encoding.UTF8.GetBytes({cs_str})"));
1423                    }
1424                }
1425            }
1426            continue;
1427        }
1428
1429        if arg.arg_type == "mock_url" {
1430            if fixture.has_host_root_route() {
1431                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1432                setup_lines.push(format!(
1433                    "var _pfUrl_{name} = Environment.GetEnvironmentVariable(\"{env_key}\");",
1434                    name = arg.name,
1435                ));
1436                setup_lines.push(format!(
1437                    "var {} = !string.IsNullOrEmpty(_pfUrl_{name}) ? _pfUrl_{name} : Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1438                    arg.name,
1439                    name = arg.name,
1440                ));
1441            } else {
1442                setup_lines.push(format!(
1443                    "var {} = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1444                    arg.name,
1445                ));
1446            }
1447            parts.push(arg.name.clone());
1448            continue;
1449        }
1450
1451        if arg.arg_type == "handle" {
1452            // Generate a CreateEngine (or equivalent) call and pass the variable.
1453            let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
1454            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1455            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1456            if config_value.is_null()
1457                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1458            {
1459                setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1460            } else {
1461                // Sort discriminator fields ("type") to appear first in nested objects so
1462                // System.Text.Json [JsonPolymorphic] can find the type discriminator before
1463                // reading other properties (a requirement as of .NET 8).
1464                let sorted = sort_discriminator_first(config_value.clone());
1465                let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1466                let name = &arg.name;
1467                setup_lines.push(format!(
1468                    "var {name}Config = JsonSerializer.Deserialize<CrawlConfig>(\"{}\", ConfigOptions)!;",
1469                    escape_csharp(&json_str),
1470                ));
1471                setup_lines.push(format!(
1472                    "var {} = {class_name}.{constructor_name}({name}Config);",
1473                    arg.name,
1474                    name = name,
1475                ));
1476            }
1477            parts.push(arg.name.clone());
1478            continue;
1479        }
1480
1481        // When field is exactly "input", treat the entire input object as the value.
1482        // This matches the convention used by other language generators (e.g. Go).
1483        let val: Option<&serde_json::Value> = if arg.field == "input" {
1484            Some(input)
1485        } else {
1486            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1487            input.get(field)
1488        };
1489        match val {
1490            None | Some(serde_json::Value::Null) if arg.optional => {
1491                // Optional arg with no fixture value: pass null explicitly since
1492                // C# nullable parameters still require an argument at the call site.
1493                parts.push("null".to_string());
1494                continue;
1495            }
1496            None | Some(serde_json::Value::Null) => {
1497                // Required arg with no fixture value: pass a language-appropriate default.
1498                // For json_object args with a known options_type, use `new OptionsType()`
1499                // so the generated code compiles when the method parameter is non-nullable.
1500                let default_val = match arg.arg_type.as_str() {
1501                    "string" => "\"\"".to_string(),
1502                    "int" | "integer" => "0".to_string(),
1503                    "float" | "number" => "0.0d".to_string(),
1504                    "bool" | "boolean" => "false".to_string(),
1505                    "json_object" => {
1506                        if let Some(opts_type) = options_type {
1507                            format!("new {opts_type}()")
1508                        } else {
1509                            "null".to_string()
1510                        }
1511                    }
1512                    _ => "null".to_string(),
1513                };
1514                parts.push(default_val);
1515            }
1516            Some(v) => {
1517                if arg.arg_type == "json_object" {
1518                    // `options_via = "from_json"`: deserialize the entire value (object,
1519                    // array, or scalar) as the options type. This sidesteps per-field
1520                    // type ambiguity — e.g. `JsonElement?` (untagged unions) or
1521                    // `List<NamedRecord>` whose element type cannot be inferred from
1522                    // JSON shape alone — by delegating to System.Text.Json.
1523                    if options_via == Some("from_json")
1524                        && let Some(opts_type) = options_type
1525                    {
1526                        let sorted = sort_discriminator_first(v.clone());
1527                        let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1528                        let escaped = escape_csharp(&json_str);
1529                        // Use the binding-emitted `<Type>.FromJson(...)` factory so any
1530                        // System.Text.Json deserialization failure is wrapped in
1531                        // `<Crate>Exception`, allowing error fixtures asserting
1532                        // `Assert.ThrowsAny<<Crate>Exception>(...)` to catch the parse
1533                        // failure (e.g. `Unknown FilePurpose value: invalid-purpose`).
1534                        parts.push(format!("{opts_type}.FromJson(\"{escaped}\")",));
1535                        continue;
1536                    }
1537                    // Array value: generate a typed List<T> based on element_type.
1538                    if let Some(arr) = v.as_array() {
1539                        parts.push(json_array_to_csharp_list(arr, arg.element_type.as_deref()));
1540                        continue;
1541                    }
1542                    // Object value with known type: generate idiomatic C# object initializer.
1543                    if let Some(opts_type) = options_type {
1544                        if let Some(obj) = v.as_object() {
1545                            parts.push(csharp_object_initializer(obj, opts_type, enum_fields, nested_types));
1546                            continue;
1547                        }
1548                    }
1549                }
1550                parts.push(json_to_csharp(v));
1551            }
1552        }
1553    }
1554
1555    (setup_lines, parts.join(", "))
1556}
1557
1558/// Convert a JSON array to a typed C# `List<T>` expression.
1559///
1560/// Mapping from `ArgMapping::element_type`:
1561/// - `None` or any string type → `List<string>`
1562/// - `"f32"` → `List<float>` with `(float)` casts
1563/// - `"(String, String)"` → `List<List<string>>` for key-value pair arrays
1564/// - `"BatchBytesItem"` / `"BatchFileItem"` → array of batch item instances
1565fn json_array_to_csharp_list(arr: &[serde_json::Value], element_type: Option<&str>) -> String {
1566    match element_type {
1567        Some("BatchBytesItem") => {
1568            let items: Vec<String> = arr
1569                .iter()
1570                .filter_map(|v| v.as_object())
1571                .map(|obj| {
1572                    let content = obj.get("content").and_then(|v| v.as_array());
1573                    let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1574                    let content_code = if let Some(arr) = content {
1575                        let bytes: Vec<String> = arr
1576                            .iter()
1577                            .filter_map(|v| v.as_u64().map(|n| format!("(byte){}", n)))
1578                            .collect();
1579                        format!("new byte[] {{ {} }}", bytes.join(", "))
1580                    } else {
1581                        "new byte[] { }".to_string()
1582                    };
1583                    format!(
1584                        "new BatchBytesItem {{ Content = {}, MimeType = \"{}\" }}",
1585                        content_code, mime_type
1586                    )
1587                })
1588                .collect();
1589            format!("new List<BatchBytesItem>() {{ {} }}", items.join(", "))
1590        }
1591        Some("BatchFileItem") => {
1592            let items: Vec<String> = arr
1593                .iter()
1594                .filter_map(|v| v.as_object())
1595                .map(|obj| {
1596                    let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1597                    format!("new BatchFileItem {{ Path = \"{}\" }}", path)
1598                })
1599                .collect();
1600            format!("new List<BatchFileItem>() {{ {} }}", items.join(", "))
1601        }
1602        Some("f32") => {
1603            let items: Vec<String> = arr.iter().map(|v| format!("(float){}", json_to_csharp(v))).collect();
1604            format!("new List<float>() {{ {} }}", items.join(", "))
1605        }
1606        Some("(String, String)") => {
1607            let items: Vec<String> = arr
1608                .iter()
1609                .map(|v| {
1610                    let strs: Vec<String> = v
1611                        .as_array()
1612                        .map_or_else(Vec::new, |a| a.iter().map(json_to_csharp).collect());
1613                    format!("new List<string>() {{ {} }}", strs.join(", "))
1614                })
1615                .collect();
1616            format!("new List<List<string>>() {{ {} }}", items.join(", "))
1617        }
1618        Some(et)
1619            if et != "f32"
1620                && et != "(String, String)"
1621                && et != "string"
1622                && et != "BatchBytesItem"
1623                && et != "BatchFileItem" =>
1624        {
1625            // Class/record types: deserialize each element from JSON
1626            let items: Vec<String> = arr
1627                .iter()
1628                .map(|v| {
1629                    let json_str = serde_json::to_string(v).unwrap_or_default();
1630                    let escaped = escape_csharp(&json_str);
1631                    format!("JsonSerializer.Deserialize<{et}>(\"{escaped}\", ConfigOptions)!")
1632                })
1633                .collect();
1634            format!("new List<{et}>() {{ {} }}", items.join(", "))
1635        }
1636        _ => {
1637            let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
1638            format!("new List<string>() {{ {} }}", items.join(", "))
1639        }
1640    }
1641}
1642
1643/// Detect if a field path accesses a discriminated union variant in C#.
1644/// Pattern: `metadata.format.<variant_name>.<field_name>`
1645/// Returns: Some((accessor, variant_name, inner_field)) if matched, otherwise None
1646fn parse_discriminated_union_access(field: &str) -> Option<(String, String, String)> {
1647    let parts: Vec<&str> = field.split('.').collect();
1648    if parts.len() >= 3 && parts.len() <= 4 {
1649        // Check if this is metadata.format.{variant}.{field} pattern
1650        if parts[0] == "metadata" && parts[1] == "format" {
1651            let variant_name = parts[2];
1652            // Known C# discriminated union variants (lowercase in fixture paths)
1653            let known_variants = [
1654                "pdf",
1655                "docx",
1656                "excel",
1657                "email",
1658                "pptx",
1659                "archive",
1660                "image",
1661                "xml",
1662                "text",
1663                "html",
1664                "ocr",
1665                "csv",
1666                "bibtex",
1667                "citation",
1668                "fiction_book",
1669                "dbf",
1670                "jats",
1671                "epub",
1672                "pst",
1673                "code",
1674            ];
1675            if known_variants.contains(&variant_name) {
1676                let variant_pascal = variant_name.to_upper_camel_case();
1677                if parts.len() == 4 {
1678                    let inner_field = parts[3];
1679                    return Some((
1680                        format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1681                        variant_pascal,
1682                        inner_field.to_string(),
1683                    ));
1684                } else if parts.len() == 3 {
1685                    // Just accessing the variant itself (no inner field)
1686                    return Some((
1687                        format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1688                        variant_pascal,
1689                        String::new(),
1690                    ));
1691                }
1692            }
1693        }
1694    }
1695    None
1696}
1697
1698/// Render an assertion against a discriminated union variant's inner field.
1699/// `variant_var` is the unwrapped union variant (e.g., `variant` from pattern match).
1700/// `inner_field` is the field to access on the variant's Value (e.g., `sheet_count`).
1701fn render_discriminated_union_assertion(
1702    out: &mut String,
1703    assertion: &Assertion,
1704    variant_var: &str,
1705    inner_field: &str,
1706    _result_is_vec: bool,
1707) {
1708    if inner_field.is_empty() {
1709        return; // No field to assert on
1710    }
1711
1712    let field_pascal = inner_field.to_upper_camel_case();
1713    let field_expr = format!("{variant_var}.Value.{field_pascal}");
1714
1715    match assertion.assertion_type.as_str() {
1716        "equals" => {
1717            if let Some(expected) = &assertion.value {
1718                let cs_val = json_to_csharp(expected);
1719                if expected.is_string() {
1720                    let _ = writeln!(out, "            Assert.Equal({cs_val}, {field_expr}!.Trim());");
1721                } else if expected.as_bool() == Some(true) {
1722                    let _ = writeln!(out, "            Assert.True({field_expr});");
1723                } else if expected.as_bool() == Some(false) {
1724                    let _ = writeln!(out, "            Assert.False({field_expr});");
1725                } else if expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0) {
1726                    let _ = writeln!(out, "            Assert.True({field_expr} == {cs_val});");
1727                } else {
1728                    let _ = writeln!(out, "            Assert.Equal({cs_val}, {field_expr});");
1729                }
1730            }
1731        }
1732        "greater_than_or_equal" => {
1733            if let Some(val) = &assertion.value {
1734                let cs_val = json_to_csharp(val);
1735                let _ = writeln!(
1736                    out,
1737                    "            Assert.True({field_expr} >= {cs_val}, \"expected >= {cs_val}\");"
1738                );
1739            }
1740        }
1741        "contains_all" => {
1742            if let Some(values) = &assertion.values {
1743                let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1744                for val in values {
1745                    let lower_val = val.as_str().map(|s| s.to_lowercase());
1746                    let cs_val = lower_val
1747                        .as_deref()
1748                        .map(|s| format!("\"{}\"", escape_csharp(s)))
1749                        .unwrap_or_else(|| json_to_csharp(val));
1750                    let _ = writeln!(out, "            Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1751                }
1752            }
1753        }
1754        "contains" => {
1755            if let Some(expected) = &assertion.value {
1756                let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1757                let lower_expected = expected.as_str().map(|s| s.to_lowercase());
1758                let cs_val = lower_expected
1759                    .as_deref()
1760                    .map(|s| format!("\"{}\"", escape_csharp(s)))
1761                    .unwrap_or_else(|| json_to_csharp(expected));
1762                let _ = writeln!(out, "            Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1763            }
1764        }
1765        "not_empty" => {
1766            let _ = writeln!(out, "            Assert.NotEmpty({field_expr});");
1767        }
1768        "is_empty" => {
1769            let _ = writeln!(out, "            Assert.Empty({field_expr});");
1770        }
1771        _ => {
1772            let _ = writeln!(
1773                out,
1774                "            // skipped: assertion type '{}' not yet supported for discriminated union fields",
1775                assertion.assertion_type
1776            );
1777        }
1778    }
1779}
1780
1781#[allow(clippy::too_many_arguments)]
1782fn render_assertion(
1783    out: &mut String,
1784    assertion: &Assertion,
1785    result_var: &str,
1786    class_name: &str,
1787    exception_class: &str,
1788    field_resolver: &FieldResolver,
1789    result_is_simple: bool,
1790    result_is_vec: bool,
1791    result_is_array: bool,
1792    result_is_bytes: bool,
1793    fields_enum: &std::collections::HashSet<String>,
1794) {
1795    // Byte-buffer returns: emit length-based assertions instead of struct-field
1796    // accessors. The result is a `byte[]` and has no named fields like
1797    // `result.Audio` or `result.Content`.
1798    if result_is_bytes {
1799        match assertion.assertion_type.as_str() {
1800            "not_empty" => {
1801                let _ = writeln!(out, "        Assert.NotEmpty({result_var});");
1802                return;
1803            }
1804            "is_empty" => {
1805                let _ = writeln!(out, "        Assert.Empty({result_var});");
1806                return;
1807            }
1808            "count_equals" | "length_equals" => {
1809                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1810                    let _ = writeln!(out, "        Assert.Equal({n}, {result_var}.Length);");
1811                }
1812                return;
1813            }
1814            "count_min" | "length_min" => {
1815                if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1816                    let _ = writeln!(out, "        Assert.True({result_var}.Length >= {n});");
1817                }
1818                return;
1819            }
1820            _ => {
1821                // Other assertion types are not meaningful on raw byte buffers;
1822                // emit a comment so the test still compiles but flags unsupported
1823                // assertion types for fixture authors.
1824                let _ = writeln!(
1825                    out,
1826                    "        // skipped: assertion type '{}' not supported on byte[] result",
1827                    assertion.assertion_type
1828                );
1829                return;
1830            }
1831        }
1832    }
1833    // Handle synthetic / derived fields before the is_valid_for_result check
1834    // so they are never treated as struct property accesses on the result.
1835    if let Some(f) = &assertion.field {
1836        match f.as_str() {
1837            "chunks_have_content" => {
1838                let synthetic_pred =
1839                    format!("({result_var}.Chunks ?? new()).All(c => !string.IsNullOrEmpty(c.Content))");
1840                let synthetic_pred_type = match assertion.assertion_type.as_str() {
1841                    "is_true" => "is_true",
1842                    "is_false" => "is_false",
1843                    _ => {
1844                        out.push_str(&format!(
1845                            "        // skipped: unsupported assertion type on synthetic field '{f}'\n"
1846                        ));
1847                        return;
1848                    }
1849                };
1850                let rendered = crate::template_env::render(
1851                    "csharp/assertion.jinja",
1852                    minijinja::context! {
1853                        assertion_type => "synthetic_assertion",
1854                        synthetic_pred => synthetic_pred,
1855                        synthetic_pred_type => synthetic_pred_type,
1856                    },
1857                );
1858                out.push_str(&rendered);
1859                return;
1860            }
1861            "chunks_have_embeddings" => {
1862                let synthetic_pred =
1863                    format!("({result_var}.Chunks ?? new()).All(c => c.Embedding != null && c.Embedding.Count > 0)");
1864                let synthetic_pred_type = match assertion.assertion_type.as_str() {
1865                    "is_true" => "is_true",
1866                    "is_false" => "is_false",
1867                    _ => {
1868                        out.push_str(&format!(
1869                            "        // skipped: unsupported assertion type on synthetic field '{f}'\n"
1870                        ));
1871                        return;
1872                    }
1873                };
1874                let rendered = crate::template_env::render(
1875                    "csharp/assertion.jinja",
1876                    minijinja::context! {
1877                        assertion_type => "synthetic_assertion",
1878                        synthetic_pred => synthetic_pred,
1879                        synthetic_pred_type => synthetic_pred_type,
1880                    },
1881                );
1882                out.push_str(&rendered);
1883                return;
1884            }
1885            // ---- EmbedResponse virtual fields ----
1886            // embed_texts returns List<List<float>> in C# — no wrapper object.
1887            // result_var is the embedding matrix; use it directly.
1888            "embeddings" => {
1889                match assertion.assertion_type.as_str() {
1890                    "count_equals" => {
1891                        if let Some(val) = &assertion.value {
1892                            if let Some(n) = val.as_u64() {
1893                                let rendered = crate::template_env::render(
1894                                    "csharp/assertion.jinja",
1895                                    minijinja::context! {
1896                                        assertion_type => "synthetic_embeddings_count_equals",
1897                                        synthetic_pred => format!("{result_var}.Count"),
1898                                        n => n,
1899                                    },
1900                                );
1901                                out.push_str(&rendered);
1902                            }
1903                        }
1904                    }
1905                    "count_min" => {
1906                        if let Some(val) = &assertion.value {
1907                            if let Some(n) = val.as_u64() {
1908                                let rendered = crate::template_env::render(
1909                                    "csharp/assertion.jinja",
1910                                    minijinja::context! {
1911                                        assertion_type => "synthetic_embeddings_count_min",
1912                                        synthetic_pred => format!("{result_var}.Count"),
1913                                        n => n,
1914                                    },
1915                                );
1916                                out.push_str(&rendered);
1917                            }
1918                        }
1919                    }
1920                    "not_empty" => {
1921                        let rendered = crate::template_env::render(
1922                            "csharp/assertion.jinja",
1923                            minijinja::context! {
1924                                assertion_type => "synthetic_embeddings_not_empty",
1925                                synthetic_pred => result_var.to_string(),
1926                            },
1927                        );
1928                        out.push_str(&rendered);
1929                    }
1930                    "is_empty" => {
1931                        let rendered = crate::template_env::render(
1932                            "csharp/assertion.jinja",
1933                            minijinja::context! {
1934                                assertion_type => "synthetic_embeddings_is_empty",
1935                                synthetic_pred => result_var.to_string(),
1936                            },
1937                        );
1938                        out.push_str(&rendered);
1939                    }
1940                    _ => {
1941                        out.push_str(
1942                            "        // skipped: unsupported assertion type on synthetic field 'embeddings'\n",
1943                        );
1944                    }
1945                }
1946                return;
1947            }
1948            "embedding_dimensions" => {
1949                let expr = format!("({result_var}.Count > 0 ? {result_var}[0].Count : 0)");
1950                match assertion.assertion_type.as_str() {
1951                    "equals" => {
1952                        if let Some(val) = &assertion.value {
1953                            if let Some(n) = val.as_u64() {
1954                                let rendered = crate::template_env::render(
1955                                    "csharp/assertion.jinja",
1956                                    minijinja::context! {
1957                                        assertion_type => "synthetic_embedding_dimensions_equals",
1958                                        synthetic_pred => expr,
1959                                        n => n,
1960                                    },
1961                                );
1962                                out.push_str(&rendered);
1963                            }
1964                        }
1965                    }
1966                    "greater_than" => {
1967                        if let Some(val) = &assertion.value {
1968                            if let Some(n) = val.as_u64() {
1969                                let rendered = crate::template_env::render(
1970                                    "csharp/assertion.jinja",
1971                                    minijinja::context! {
1972                                        assertion_type => "synthetic_embedding_dimensions_greater_than",
1973                                        synthetic_pred => expr,
1974                                        n => n,
1975                                    },
1976                                );
1977                                out.push_str(&rendered);
1978                            }
1979                        }
1980                    }
1981                    _ => {
1982                        out.push_str("        // skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n");
1983                    }
1984                }
1985                return;
1986            }
1987            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1988                let synthetic_pred = match f.as_str() {
1989                    "embeddings_valid" => {
1990                        format!("{result_var}.All(e => e.Count > 0)")
1991                    }
1992                    "embeddings_finite" => {
1993                        format!("{result_var}.All(e => e.All(v => !float.IsInfinity(v) && !float.IsNaN(v)))")
1994                    }
1995                    "embeddings_non_zero" => {
1996                        format!("{result_var}.All(e => e.Any(v => v != 0.0f))")
1997                    }
1998                    "embeddings_normalized" => {
1999                        format!(
2000                            "{result_var}.All(e => {{ var n = e.Sum(v => (double)v * v); return Math.Abs(n - 1.0) < 1e-3; }})"
2001                        )
2002                    }
2003                    _ => unreachable!(),
2004                };
2005                let synthetic_pred_type = match assertion.assertion_type.as_str() {
2006                    "is_true" => "is_true",
2007                    "is_false" => "is_false",
2008                    _ => {
2009                        out.push_str(&format!(
2010                            "        // skipped: unsupported assertion type on synthetic field '{f}'\n"
2011                        ));
2012                        return;
2013                    }
2014                };
2015                let rendered = crate::template_env::render(
2016                    "csharp/assertion.jinja",
2017                    minijinja::context! {
2018                        assertion_type => "synthetic_assertion",
2019                        synthetic_pred => synthetic_pred,
2020                        synthetic_pred_type => synthetic_pred_type,
2021                    },
2022                );
2023                out.push_str(&rendered);
2024                return;
2025            }
2026            // ---- keywords / keywords_count ----
2027            // C# ExtractionResult does not expose extracted_keywords; skip.
2028            "keywords" | "keywords_count" => {
2029                let skipped_reason = format!("field '{f}' not available on C# ExtractionResult");
2030                let rendered = crate::template_env::render(
2031                    "csharp/assertion.jinja",
2032                    minijinja::context! {
2033                        skipped_reason => skipped_reason,
2034                    },
2035                );
2036                out.push_str(&rendered);
2037                return;
2038            }
2039            _ => {}
2040        }
2041    }
2042
2043    // Skip assertions on fields that don't exist on the result type.
2044    if let Some(f) = &assertion.field {
2045        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
2046            let skipped_reason = format!("field '{f}' not available on result type");
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    // For count assertions on list results with no field specified, use the list directly.
2059    // Otherwise, when the result is a List<T>, index into the first element for field access.
2060    let is_count_assertion = matches!(
2061        assertion.assertion_type.as_str(),
2062        "count_equals" | "count_min" | "count_max"
2063    );
2064    let is_no_field = assertion.field.is_none() || assertion.field.as_ref().is_some_and(|f| f.is_empty());
2065    let use_list_directly = result_is_vec && is_count_assertion && is_no_field;
2066
2067    let effective_result_var: String = if result_is_vec && !use_list_directly {
2068        format!("{result_var}[0]")
2069    } else {
2070        result_var.to_string()
2071    };
2072
2073    // Check if this is a discriminated union access (e.g., metadata.format.excel.sheet_count)
2074    let is_discriminated_union = assertion
2075        .field
2076        .as_ref()
2077        .is_some_and(|f| parse_discriminated_union_access(f).is_some());
2078
2079    // For discriminated union assertions, generate pattern-matching wrapper
2080    if is_discriminated_union {
2081        if let Some((_, variant_name, inner_field)) = assertion
2082            .field
2083            .as_ref()
2084            .and_then(|f| parse_discriminated_union_access(f))
2085        {
2086            // Use a unique variable name based on the field hash to avoid shadowing
2087            let mut hasher = std::collections::hash_map::DefaultHasher::new();
2088            inner_field.hash(&mut hasher);
2089            let var_hash = format!("{:x}", hasher.finish());
2090            let variant_var = format!("variant_{}", &var_hash[..8]);
2091            let _ = writeln!(
2092                out,
2093                "        if ({effective_result_var}.Metadata.Format is FormatMetadata.{} {})",
2094                variant_name, &variant_var
2095            );
2096            let _ = writeln!(out, "        {{");
2097            render_discriminated_union_assertion(out, assertion, &variant_var, &inner_field, result_is_vec);
2098            let _ = writeln!(out, "        }}");
2099            let _ = writeln!(out, "        else");
2100            let _ = writeln!(out, "        {{");
2101            let _ = writeln!(
2102                out,
2103                "            Assert.Fail(\"Expected {} format metadata\");",
2104                variant_name.to_lowercase()
2105            );
2106            let _ = writeln!(out, "        }}");
2107            return;
2108        }
2109    }
2110
2111    let field_expr = if result_is_simple {
2112        effective_result_var.clone()
2113    } else {
2114        match &assertion.field {
2115            Some(f) if !f.is_empty() => field_resolver.accessor(f, "csharp", &effective_result_var),
2116            _ => effective_result_var.clone(),
2117        }
2118    };
2119
2120    // Determine if field_expr is a list or complex object that requires JSON serialization
2121    // for string-based assertions (contains, not_contains, etc.). List<T>.ToString() in C#
2122    // returns the type name, not the contents.
2123    let field_needs_json_serialize = if result_is_simple {
2124        // Simple results are scalars, but when they're also arrays (e.g., List<string>),
2125        // JSON-serialize so substring checks see actual content, not the type name.
2126        result_is_array
2127    } else {
2128        match &assertion.field {
2129            Some(f) if !f.is_empty() => field_resolver.is_array(f),
2130            // No field specified — the whole result object; needs serialization when complex.
2131            _ => !result_is_simple,
2132        }
2133    };
2134    // Build the string representation of field_expr for substring-based assertions.
2135    let field_as_str = if field_needs_json_serialize {
2136        format!("JsonSerializer.Serialize({field_expr})")
2137    } else {
2138        format!("{field_expr}.ToString()")
2139    };
2140
2141    // Detect enum-typed fields. C# emits typed enums (e.g. `FinishReason?`) for
2142    // these so the codegen must avoid `.Trim()` (string-only) and instead
2143    // compare via `?.ToString()?.ToLower()` to match snake_case JSON.
2144    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
2145        let resolved = field_resolver.resolve(f);
2146        fields_enum.contains(f) || fields_enum.contains(resolved)
2147    });
2148
2149    match assertion.assertion_type.as_str() {
2150        "equals" => {
2151            if let Some(expected) = &assertion.value {
2152                // Enum field equality bypasses the template (which would emit `.Trim()`,
2153                // a string-only API). Compare the snake-cased ToString() against the
2154                // expected value to match the wire JSON form (`InProgress` → `in_progress`,
2155                // `ContentFilter` → `content_filter`, etc.). `JsonNamingPolicy.SnakeCaseLower`
2156                // is the same policy used by the global JsonStringEnumConverter, so the
2157                // assertion compares against exactly what serde would emit.
2158                if field_is_enum && expected.is_string() {
2159                    let s_lower = expected.as_str().map(|s| s.to_lowercase()).unwrap_or_default();
2160                    let _ = writeln!(
2161                        out,
2162                        "        Assert.Equal(\"{}\", {field_expr} == null ? null : JsonNamingPolicy.SnakeCaseLower.ConvertName({field_expr}.ToString()!));",
2163                        escape_csharp(&s_lower)
2164                    );
2165                    return;
2166                }
2167                let cs_val = json_to_csharp(expected);
2168                let is_string_val = expected.is_string();
2169                let is_bool_true = expected.as_bool() == Some(true);
2170                let is_bool_false = expected.as_bool() == Some(false);
2171                let is_integer_val = expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0);
2172
2173                let rendered = crate::template_env::render(
2174                    "csharp/assertion.jinja",
2175                    minijinja::context! {
2176                        assertion_type => "equals",
2177                        field_expr => field_expr.clone(),
2178                        cs_val => cs_val,
2179                        is_string_val => is_string_val,
2180                        is_bool_true => is_bool_true,
2181                        is_bool_false => is_bool_false,
2182                        is_integer_val => is_integer_val,
2183                    },
2184                );
2185                out.push_str(&rendered);
2186            }
2187        }
2188        "contains" => {
2189            if let Some(expected) = &assertion.value {
2190                // Lowercase both expected and actual so that enum fields (where .ToString()
2191                // returns the PascalCase C# member name like "Anchor") correctly match
2192                // fixture snake_case values like "anchor".  String fields are unaffected
2193                // because lowercasing both sides preserves substring matches.
2194                // List/complex fields use JsonSerializer.Serialize() since List<T>.ToString()
2195                // returns the type name, not the contents.
2196                let lower_expected = expected.as_str().map(|s| s.to_lowercase());
2197                let cs_val = lower_expected
2198                    .as_deref()
2199                    .map(|s| format!("\"{}\"", escape_csharp(s)))
2200                    .unwrap_or_else(|| json_to_csharp(expected));
2201
2202                let rendered = crate::template_env::render(
2203                    "csharp/assertion.jinja",
2204                    minijinja::context! {
2205                        assertion_type => "contains",
2206                        field_as_str => field_as_str.clone(),
2207                        cs_val => cs_val,
2208                    },
2209                );
2210                out.push_str(&rendered);
2211            }
2212        }
2213        "contains_all" => {
2214            if let Some(values) = &assertion.values {
2215                let values_cs_lower: Vec<String> = values
2216                    .iter()
2217                    .map(|val| {
2218                        let lower_val = val.as_str().map(|s| s.to_lowercase());
2219                        lower_val
2220                            .as_deref()
2221                            .map(|s| format!("\"{}\"", escape_csharp(s)))
2222                            .unwrap_or_else(|| json_to_csharp(val))
2223                    })
2224                    .collect();
2225
2226                let rendered = crate::template_env::render(
2227                    "csharp/assertion.jinja",
2228                    minijinja::context! {
2229                        assertion_type => "contains_all",
2230                        field_as_str => field_as_str.clone(),
2231                        values_cs_lower => values_cs_lower,
2232                    },
2233                );
2234                out.push_str(&rendered);
2235            }
2236        }
2237        "not_contains" => {
2238            if let Some(expected) = &assertion.value {
2239                let cs_val = json_to_csharp(expected);
2240
2241                let rendered = crate::template_env::render(
2242                    "csharp/assertion.jinja",
2243                    minijinja::context! {
2244                        assertion_type => "not_contains",
2245                        field_as_str => field_as_str.clone(),
2246                        cs_val => cs_val,
2247                    },
2248                );
2249                out.push_str(&rendered);
2250            }
2251        }
2252        "not_empty" => {
2253            let rendered = crate::template_env::render(
2254                "csharp/assertion.jinja",
2255                minijinja::context! {
2256                    assertion_type => "not_empty",
2257                    field_expr => field_expr.clone(),
2258                    field_needs_json_serialize => field_needs_json_serialize,
2259                },
2260            );
2261            out.push_str(&rendered);
2262        }
2263        "is_empty" => {
2264            let rendered = crate::template_env::render(
2265                "csharp/assertion.jinja",
2266                minijinja::context! {
2267                    assertion_type => "is_empty",
2268                    field_expr => field_expr.clone(),
2269                    field_needs_json_serialize => field_needs_json_serialize,
2270                },
2271            );
2272            out.push_str(&rendered);
2273        }
2274        "contains_any" => {
2275            if let Some(values) = &assertion.values {
2276                let checks: Vec<String> = values
2277                    .iter()
2278                    .map(|v| {
2279                        let cs_val = json_to_csharp(v);
2280                        format!("{field_as_str}.Contains({cs_val})")
2281                    })
2282                    .collect();
2283                let contains_any_expr = checks.join(" || ");
2284
2285                let rendered = crate::template_env::render(
2286                    "csharp/assertion.jinja",
2287                    minijinja::context! {
2288                        assertion_type => "contains_any",
2289                        contains_any_expr => contains_any_expr,
2290                    },
2291                );
2292                out.push_str(&rendered);
2293            }
2294        }
2295        "greater_than" => {
2296            if let Some(val) = &assertion.value {
2297                let cs_val = json_to_csharp(val);
2298
2299                let rendered = crate::template_env::render(
2300                    "csharp/assertion.jinja",
2301                    minijinja::context! {
2302                        assertion_type => "greater_than",
2303                        field_expr => field_expr.clone(),
2304                        cs_val => cs_val,
2305                    },
2306                );
2307                out.push_str(&rendered);
2308            }
2309        }
2310        "less_than" => {
2311            if let Some(val) = &assertion.value {
2312                let cs_val = json_to_csharp(val);
2313
2314                let rendered = crate::template_env::render(
2315                    "csharp/assertion.jinja",
2316                    minijinja::context! {
2317                        assertion_type => "less_than",
2318                        field_expr => field_expr.clone(),
2319                        cs_val => cs_val,
2320                    },
2321                );
2322                out.push_str(&rendered);
2323            }
2324        }
2325        "greater_than_or_equal" => {
2326            if let Some(val) = &assertion.value {
2327                let cs_val = json_to_csharp(val);
2328
2329                let rendered = crate::template_env::render(
2330                    "csharp/assertion.jinja",
2331                    minijinja::context! {
2332                        assertion_type => "greater_than_or_equal",
2333                        field_expr => field_expr.clone(),
2334                        cs_val => cs_val,
2335                    },
2336                );
2337                out.push_str(&rendered);
2338            }
2339        }
2340        "less_than_or_equal" => {
2341            if let Some(val) = &assertion.value {
2342                let cs_val = json_to_csharp(val);
2343
2344                let rendered = crate::template_env::render(
2345                    "csharp/assertion.jinja",
2346                    minijinja::context! {
2347                        assertion_type => "less_than_or_equal",
2348                        field_expr => field_expr.clone(),
2349                        cs_val => cs_val,
2350                    },
2351                );
2352                out.push_str(&rendered);
2353            }
2354        }
2355        "starts_with" => {
2356            if let Some(expected) = &assertion.value {
2357                let cs_val = json_to_csharp(expected);
2358
2359                let rendered = crate::template_env::render(
2360                    "csharp/assertion.jinja",
2361                    minijinja::context! {
2362                        assertion_type => "starts_with",
2363                        field_expr => field_expr.clone(),
2364                        cs_val => cs_val,
2365                    },
2366                );
2367                out.push_str(&rendered);
2368            }
2369        }
2370        "ends_with" => {
2371            if let Some(expected) = &assertion.value {
2372                let cs_val = json_to_csharp(expected);
2373
2374                let rendered = crate::template_env::render(
2375                    "csharp/assertion.jinja",
2376                    minijinja::context! {
2377                        assertion_type => "ends_with",
2378                        field_expr => field_expr.clone(),
2379                        cs_val => cs_val,
2380                    },
2381                );
2382                out.push_str(&rendered);
2383            }
2384        }
2385        "min_length" => {
2386            if let Some(val) = &assertion.value {
2387                if let Some(n) = val.as_u64() {
2388                    let rendered = crate::template_env::render(
2389                        "csharp/assertion.jinja",
2390                        minijinja::context! {
2391                            assertion_type => "min_length",
2392                            field_expr => field_expr.clone(),
2393                            n => n,
2394                        },
2395                    );
2396                    out.push_str(&rendered);
2397                }
2398            }
2399        }
2400        "max_length" => {
2401            if let Some(val) = &assertion.value {
2402                if let Some(n) = val.as_u64() {
2403                    let rendered = crate::template_env::render(
2404                        "csharp/assertion.jinja",
2405                        minijinja::context! {
2406                            assertion_type => "max_length",
2407                            field_expr => field_expr.clone(),
2408                            n => n,
2409                        },
2410                    );
2411                    out.push_str(&rendered);
2412                }
2413            }
2414        }
2415        "count_min" => {
2416            if let Some(val) = &assertion.value {
2417                if let Some(n) = val.as_u64() {
2418                    let rendered = crate::template_env::render(
2419                        "csharp/assertion.jinja",
2420                        minijinja::context! {
2421                            assertion_type => "count_min",
2422                            field_expr => field_expr.clone(),
2423                            n => n,
2424                        },
2425                    );
2426                    out.push_str(&rendered);
2427                }
2428            }
2429        }
2430        "count_equals" => {
2431            if let Some(val) = &assertion.value {
2432                if let Some(n) = val.as_u64() {
2433                    let rendered = crate::template_env::render(
2434                        "csharp/assertion.jinja",
2435                        minijinja::context! {
2436                            assertion_type => "count_equals",
2437                            field_expr => field_expr.clone(),
2438                            n => n,
2439                        },
2440                    );
2441                    out.push_str(&rendered);
2442                }
2443            }
2444        }
2445        "is_true" => {
2446            let rendered = crate::template_env::render(
2447                "csharp/assertion.jinja",
2448                minijinja::context! {
2449                    assertion_type => "is_true",
2450                    field_expr => field_expr.clone(),
2451                },
2452            );
2453            out.push_str(&rendered);
2454        }
2455        "is_false" => {
2456            let rendered = crate::template_env::render(
2457                "csharp/assertion.jinja",
2458                minijinja::context! {
2459                    assertion_type => "is_false",
2460                    field_expr => field_expr.clone(),
2461                },
2462            );
2463            out.push_str(&rendered);
2464        }
2465        "not_error" => {
2466            // Already handled by the call succeeding without exception.
2467            let rendered = crate::template_env::render(
2468                "csharp/assertion.jinja",
2469                minijinja::context! {
2470                    assertion_type => "not_error",
2471                },
2472            );
2473            out.push_str(&rendered);
2474        }
2475        "error" => {
2476            // Handled at the test method level.
2477            let rendered = crate::template_env::render(
2478                "csharp/assertion.jinja",
2479                minijinja::context! {
2480                    assertion_type => "error",
2481                },
2482            );
2483            out.push_str(&rendered);
2484        }
2485        "method_result" => {
2486            if let Some(method_name) = &assertion.method {
2487                let call_expr = build_csharp_method_call(result_var, method_name, assertion.args.as_ref(), class_name);
2488                let check = assertion.check.as_deref().unwrap_or("is_true");
2489
2490                match check {
2491                    "equals" => {
2492                        if let Some(val) = &assertion.value {
2493                            let is_check_bool_true = val.as_bool() == Some(true);
2494                            let is_check_bool_false = val.as_bool() == Some(false);
2495                            let cs_check_val = json_to_csharp(val);
2496
2497                            let rendered = crate::template_env::render(
2498                                "csharp/assertion.jinja",
2499                                minijinja::context! {
2500                                    assertion_type => "method_result",
2501                                    check => "equals",
2502                                    call_expr => call_expr.clone(),
2503                                    is_check_bool_true => is_check_bool_true,
2504                                    is_check_bool_false => is_check_bool_false,
2505                                    cs_check_val => cs_check_val,
2506                                },
2507                            );
2508                            out.push_str(&rendered);
2509                        }
2510                    }
2511                    "is_true" => {
2512                        let rendered = crate::template_env::render(
2513                            "csharp/assertion.jinja",
2514                            minijinja::context! {
2515                                assertion_type => "method_result",
2516                                check => "is_true",
2517                                call_expr => call_expr.clone(),
2518                            },
2519                        );
2520                        out.push_str(&rendered);
2521                    }
2522                    "is_false" => {
2523                        let rendered = crate::template_env::render(
2524                            "csharp/assertion.jinja",
2525                            minijinja::context! {
2526                                assertion_type => "method_result",
2527                                check => "is_false",
2528                                call_expr => call_expr.clone(),
2529                            },
2530                        );
2531                        out.push_str(&rendered);
2532                    }
2533                    "greater_than_or_equal" => {
2534                        if let Some(val) = &assertion.value {
2535                            let check_n = val.as_u64().unwrap_or(0);
2536
2537                            let rendered = crate::template_env::render(
2538                                "csharp/assertion.jinja",
2539                                minijinja::context! {
2540                                    assertion_type => "method_result",
2541                                    check => "greater_than_or_equal",
2542                                    call_expr => call_expr.clone(),
2543                                    check_n => check_n,
2544                                },
2545                            );
2546                            out.push_str(&rendered);
2547                        }
2548                    }
2549                    "count_min" => {
2550                        if let Some(val) = &assertion.value {
2551                            let check_n = val.as_u64().unwrap_or(0);
2552
2553                            let rendered = crate::template_env::render(
2554                                "csharp/assertion.jinja",
2555                                minijinja::context! {
2556                                    assertion_type => "method_result",
2557                                    check => "count_min",
2558                                    call_expr => call_expr.clone(),
2559                                    check_n => check_n,
2560                                },
2561                            );
2562                            out.push_str(&rendered);
2563                        }
2564                    }
2565                    "is_error" => {
2566                        let rendered = crate::template_env::render(
2567                            "csharp/assertion.jinja",
2568                            minijinja::context! {
2569                                assertion_type => "method_result",
2570                                check => "is_error",
2571                                call_expr => call_expr.clone(),
2572                                exception_class => exception_class,
2573                            },
2574                        );
2575                        out.push_str(&rendered);
2576                    }
2577                    "contains" => {
2578                        if let Some(val) = &assertion.value {
2579                            let cs_check_val = json_to_csharp(val);
2580
2581                            let rendered = crate::template_env::render(
2582                                "csharp/assertion.jinja",
2583                                minijinja::context! {
2584                                    assertion_type => "method_result",
2585                                    check => "contains",
2586                                    call_expr => call_expr.clone(),
2587                                    cs_check_val => cs_check_val,
2588                                },
2589                            );
2590                            out.push_str(&rendered);
2591                        }
2592                    }
2593                    other_check => {
2594                        panic!("C# e2e generator: unsupported method_result check type: {other_check}");
2595                    }
2596                }
2597            } else {
2598                panic!("C# e2e generator: method_result assertion missing 'method' field");
2599            }
2600        }
2601        "matches_regex" => {
2602            if let Some(expected) = &assertion.value {
2603                let cs_val = json_to_csharp(expected);
2604
2605                let rendered = crate::template_env::render(
2606                    "csharp/assertion.jinja",
2607                    minijinja::context! {
2608                        assertion_type => "matches_regex",
2609                        field_expr => field_expr.clone(),
2610                        cs_val => cs_val,
2611                    },
2612                );
2613                out.push_str(&rendered);
2614            }
2615        }
2616        other => {
2617            panic!("C# e2e generator: unsupported assertion type: {other}");
2618        }
2619    }
2620}
2621
2622/// Recursively sort JSON objects so that any key named `"type"` appears first.
2623///
2624/// System.Text.Json's `[JsonPolymorphic]` requires the type discriminator to be
2625/// the first property when deserializing polymorphic types. Fixture config values
2626/// serialised via serde_json preserve insertion/alphabetical order, which may put
2627/// `"type"` after other keys (e.g. `"password"` before `"type"` in auth configs).
2628fn sort_discriminator_first(value: serde_json::Value) -> serde_json::Value {
2629    match value {
2630        serde_json::Value::Object(map) => {
2631            let mut sorted = serde_json::Map::with_capacity(map.len());
2632            // Insert "type" first if present.
2633            if let Some(type_val) = map.get("type") {
2634                sorted.insert("type".to_string(), sort_discriminator_first(type_val.clone()));
2635            }
2636            for (k, v) in map {
2637                if k != "type" {
2638                    sorted.insert(k, sort_discriminator_first(v));
2639                }
2640            }
2641            serde_json::Value::Object(sorted)
2642        }
2643        serde_json::Value::Array(arr) => {
2644            serde_json::Value::Array(arr.into_iter().map(sort_discriminator_first).collect())
2645        }
2646        other => other,
2647    }
2648}
2649
2650/// Convert a `serde_json::Value` to a C# literal string.
2651fn json_to_csharp(value: &serde_json::Value) -> String {
2652    match value {
2653        serde_json::Value::String(s) => format!("\"{}\"", escape_csharp(s)),
2654        serde_json::Value::Bool(true) => "true".to_string(),
2655        serde_json::Value::Bool(false) => "false".to_string(),
2656        serde_json::Value::Number(n) => {
2657            if n.is_f64() {
2658                format!("{}d", n)
2659            } else {
2660                n.to_string()
2661            }
2662        }
2663        serde_json::Value::Null => "null".to_string(),
2664        serde_json::Value::Array(arr) => {
2665            let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2666            format!("new[] {{ {} }}", items.join(", "))
2667        }
2668        serde_json::Value::Object(_) => {
2669            let json_str = serde_json::to_string(value).unwrap_or_default();
2670            format!("\"{}\"", escape_csharp(&json_str))
2671        }
2672    }
2673}
2674
2675/// Build default nested type mappings for C# extraction config types.
2676///
2677/// Maps known Kreuzberg/Kreuzcrawl config field names (in snake_case) to their
2678/// C# record type names (in PascalCase). These defaults allow e2e codegen to
2679/// automatically deserialize nested config objects without requiring explicit
2680/// configuration in alef.toml. User-provided overrides take precedence.
2681fn default_csharp_nested_types() -> HashMap<String, String> {
2682    [
2683        ("chunking", "ChunkingConfig"),
2684        ("ocr", "OcrConfig"),
2685        ("images", "ImageExtractionConfig"),
2686        ("html_output", "HtmlOutputConfig"),
2687        ("language_detection", "LanguageDetectionConfig"),
2688        ("postprocessor", "PostProcessorConfig"),
2689        ("acceleration", "AccelerationConfig"),
2690        ("email", "EmailConfig"),
2691        ("pages", "PageConfig"),
2692        ("pdf_options", "PdfConfig"),
2693        ("layout", "LayoutDetectionConfig"),
2694        ("tree_sitter", "TreeSitterConfig"),
2695        ("structured_extraction", "StructuredExtractionConfig"),
2696        ("content_filter", "ContentFilterConfig"),
2697        ("token_reduction", "TokenReductionOptions"),
2698        ("security_limits", "SecurityLimits"),
2699        ("format", "FormatMetadata"),
2700    ]
2701    .iter()
2702    .map(|(k, v)| (k.to_string(), v.to_string()))
2703    .collect()
2704}
2705
2706/// Emit a C# object initializer for a JSON options object.
2707///
2708/// - camelCase fixture keys → PascalCase C# property names
2709/// - Enum fields (from `enum_fields`) → `EnumType.Member`
2710/// - Nested objects with known type (from `nested_types`) → `JsonSerializer.Deserialize<T>(...)`
2711/// - Arrays → `new List<string> { ... }`
2712/// - Primitives → C# literals via `json_to_csharp`
2713fn csharp_object_initializer(
2714    obj: &serde_json::Map<String, serde_json::Value>,
2715    type_name: &str,
2716    enum_fields: &HashMap<String, String>,
2717    nested_types: &HashMap<String, String>,
2718) -> String {
2719    if obj.is_empty() {
2720        return format!("new {type_name}()");
2721    }
2722
2723    // Snake_case fixture keys for fields that are real C# enums in the binding.
2724    // The fixture string value (e.g. "markdown") maps to `EnumType.Member` (e.g. `OutputFormat.Markdown`).
2725    static IMPLICIT_ENUM_FIELDS: &[(&str, &str)] = &[("output_format", "OutputFormat")];
2726
2727    let props: Vec<String> = obj
2728        .iter()
2729        .map(|(key, val)| {
2730            let pascal_key = key.to_upper_camel_case();
2731            let implicit_enum_type = IMPLICIT_ENUM_FIELDS
2732                .iter()
2733                .find(|(k, _)| *k == key.as_str())
2734                .map(|(_, t)| *t);
2735            let cs_val =
2736                if let Some(enum_type) = enum_fields.get(key.as_str()).map(String::as_str).or(implicit_enum_type) {
2737                    // Enum: EnumType.Member
2738                    if val.is_null() {
2739                        "null".to_string()
2740                    } else {
2741                        let member = val
2742                            .as_str()
2743                            .map(|s| s.to_upper_camel_case())
2744                            .unwrap_or_else(|| "null".to_string());
2745                        format!("{enum_type}.{member}")
2746                    }
2747                } else if let Some(nested_type) = nested_types.get(key.as_str()) {
2748                    // Nested object: JSON deserialization (keys are typically single-word, matching JsonPropertyName)
2749                    let normalized = normalize_csharp_enum_values(val, enum_fields);
2750                    let json_str = serde_json::to_string(&normalized).unwrap_or_default();
2751                    format!(
2752                        "JsonSerializer.Deserialize<{nested_type}>(\"{}\", ConfigOptions)!",
2753                        escape_csharp(&json_str)
2754                    )
2755                } else if let Some(arr) = val.as_array() {
2756                    // Array: List<string>
2757                    let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2758                    format!("new List<string> {{ {} }}", items.join(", "))
2759                } else {
2760                    json_to_csharp(val)
2761                };
2762            format!("{pascal_key} = {cs_val}")
2763        })
2764        .collect();
2765    format!("new {} {{ {} }}", type_name, props.join(", "))
2766}
2767
2768/// Convert enum values in a JSON object to lowercase to match C# [JsonPropertyName] attributes.
2769/// The JSON deserialization uses JsonPropertyName("lowercase_value"), so fixture enum values
2770/// (typically PascalCase like "Tildes") must be converted to lowercase ("tildes") for correct
2771/// deserialization with JsonStringEnumConverter.
2772fn normalize_csharp_enum_values(value: &serde_json::Value, enum_fields: &HashMap<String, String>) -> serde_json::Value {
2773    match value {
2774        serde_json::Value::Object(map) => {
2775            let mut result = map.clone();
2776            for (key, val) in result.iter_mut() {
2777                if enum_fields.contains_key(key) {
2778                    // This is an enum field; convert the string value to lowercase.
2779                    if let Some(s) = val.as_str() {
2780                        *val = serde_json::Value::String(s.to_lowercase());
2781                    }
2782                }
2783            }
2784            serde_json::Value::Object(result)
2785        }
2786        other => other.clone(),
2787    }
2788}
2789
2790// ---------------------------------------------------------------------------
2791// Visitor generation
2792// ---------------------------------------------------------------------------
2793
2794/// Build a C# visitor: add an instantiation line to `setup_lines` and push
2795/// a private nested class declaration to `class_decls` (emitted at class scope,
2796/// outside any method body — C# does not allow local class declarations inside
2797/// methods).  Each fixture gets a unique class name derived from its ID to avoid
2798/// duplicate-name compile errors when multiple visitor fixtures exist per file.
2799/// Returns the visitor variable name for use as a call argument.
2800fn build_csharp_visitor(
2801    setup_lines: &mut Vec<String>,
2802    class_decls: &mut Vec<String>,
2803    fixture_id: &str,
2804    visitor_spec: &crate::fixture::VisitorSpec,
2805) -> String {
2806    use heck::ToUpperCamelCase;
2807    let class_name = format!("{}Visitor", fixture_id.to_upper_camel_case());
2808    let var_name = format!("_visitor_{}", fixture_id.replace('-', "_"));
2809
2810    setup_lines.push(format!("var {var_name} = new {class_name}();"));
2811
2812    // Build the class declaration string (indented for nesting inside the test class).
2813    let mut decl = String::new();
2814    decl.push_str(&format!("    private sealed class {class_name} : IHtmlVisitor\n"));
2815    decl.push_str("    {\n");
2816
2817    // List of all visitor methods that must be implemented by IHtmlVisitor.
2818    let all_methods = [
2819        "visit_element_start",
2820        "visit_element_end",
2821        "visit_text",
2822        "visit_link",
2823        "visit_image",
2824        "visit_heading",
2825        "visit_code_block",
2826        "visit_code_inline",
2827        "visit_list_item",
2828        "visit_list_start",
2829        "visit_list_end",
2830        "visit_table_start",
2831        "visit_table_row",
2832        "visit_table_end",
2833        "visit_blockquote",
2834        "visit_strong",
2835        "visit_emphasis",
2836        "visit_strikethrough",
2837        "visit_underline",
2838        "visit_subscript",
2839        "visit_superscript",
2840        "visit_mark",
2841        "visit_line_break",
2842        "visit_horizontal_rule",
2843        "visit_custom_element",
2844        "visit_definition_list_start",
2845        "visit_definition_term",
2846        "visit_definition_description",
2847        "visit_definition_list_end",
2848        "visit_form",
2849        "visit_input",
2850        "visit_button",
2851        "visit_audio",
2852        "visit_video",
2853        "visit_iframe",
2854        "visit_details",
2855        "visit_summary",
2856        "visit_figure_start",
2857        "visit_figcaption",
2858        "visit_figure_end",
2859    ];
2860
2861    // Emit all methods: use fixture action if specified, otherwise default to Continue.
2862    for method_name in &all_methods {
2863        if let Some(action) = visitor_spec.callbacks.get(*method_name) {
2864            emit_csharp_visitor_method(&mut decl, method_name, action);
2865        } else {
2866            // Default: Continue for methods not in the fixture
2867            emit_csharp_visitor_method(&mut decl, method_name, &CallbackAction::Continue);
2868        }
2869    }
2870
2871    decl.push_str("    }\n");
2872    class_decls.push(decl);
2873
2874    var_name
2875}
2876
2877/// Emit a C# visitor method into a class declaration string.
2878fn emit_csharp_visitor_method(decl: &mut String, method_name: &str, action: &CallbackAction) {
2879    let camel_method = method_to_camel(method_name);
2880    let params = match method_name {
2881        "visit_link" => "NodeContext ctx, string href, string text, string title",
2882        "visit_image" => "NodeContext ctx, string src, string alt, string title",
2883        "visit_heading" => "NodeContext ctx, uint level, string text, string id",
2884        "visit_code_block" => "NodeContext ctx, string lang, string code",
2885        "visit_code_inline"
2886        | "visit_strong"
2887        | "visit_emphasis"
2888        | "visit_strikethrough"
2889        | "visit_underline"
2890        | "visit_subscript"
2891        | "visit_superscript"
2892        | "visit_mark"
2893        | "visit_button"
2894        | "visit_summary"
2895        | "visit_figcaption"
2896        | "visit_definition_term"
2897        | "visit_definition_description" => "NodeContext ctx, string text",
2898        "visit_text" => "NodeContext ctx, string text",
2899        "visit_list_item" => "NodeContext ctx, bool ordered, string marker, string text",
2900        "visit_blockquote" => "NodeContext ctx, string content, ulong depth",
2901        "visit_table_row" => "NodeContext ctx, List<string> cells, bool isHeader",
2902        "visit_custom_element" => "NodeContext ctx, string tagName, string html",
2903        "visit_form" => "NodeContext ctx, string actionUrl, string method",
2904        "visit_input" => "NodeContext ctx, string inputType, string name, string value",
2905        "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, string src",
2906        "visit_details" => "NodeContext ctx, bool isOpen",
2907        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2908            "NodeContext ctx, string output"
2909        }
2910        "visit_list_start" => "NodeContext ctx, bool ordered",
2911        "visit_list_end" => "NodeContext ctx, bool ordered, string output",
2912        "visit_element_start"
2913        | "visit_table_start"
2914        | "visit_definition_list_start"
2915        | "visit_figure_start"
2916        | "visit_line_break"
2917        | "visit_horizontal_rule" => "NodeContext ctx",
2918        _ => "NodeContext ctx",
2919    };
2920
2921    let (action_type, action_value) = match action {
2922        CallbackAction::Skip => ("skip", String::new()),
2923        CallbackAction::Continue => ("continue", String::new()),
2924        CallbackAction::PreserveHtml => ("preserve_html", String::new()),
2925        CallbackAction::Custom { output } => ("custom", escape_csharp(output)),
2926        CallbackAction::CustomTemplate { template } => {
2927            let camel = snake_case_template_to_camel(template);
2928            ("custom_template", escape_csharp(&camel))
2929        }
2930    };
2931
2932    let rendered = crate::template_env::render(
2933        "csharp/visitor_method.jinja",
2934        minijinja::context! {
2935            camel_method => camel_method,
2936            params => params,
2937            action_type => action_type,
2938            action_value => action_value,
2939        },
2940    );
2941    let _ = write!(decl, "{}", rendered);
2942}
2943
2944/// Convert snake_case method names to C# PascalCase.
2945fn method_to_camel(snake: &str) -> String {
2946    use heck::ToUpperCamelCase;
2947    snake.to_upper_camel_case()
2948}
2949
2950/// Rewrite `{snake_case}` placeholders in a custom template to `{camelCase}` so
2951/// they match C# parameter names (which alef emits in camelCase).
2952fn snake_case_template_to_camel(template: &str) -> String {
2953    use heck::ToLowerCamelCase;
2954    let mut out = String::with_capacity(template.len());
2955    let mut chars = template.chars().peekable();
2956    while let Some(c) = chars.next() {
2957        if c == '{' {
2958            let mut name = String::new();
2959            while let Some(&nc) = chars.peek() {
2960                if nc == '}' {
2961                    chars.next();
2962                    break;
2963                }
2964                name.push(nc);
2965                chars.next();
2966            }
2967            out.push('{');
2968            out.push_str(&name.to_lower_camel_case());
2969            out.push('}');
2970        } else {
2971            out.push(c);
2972        }
2973    }
2974    out
2975}
2976
2977/// Build a C# call expression for a `method_result` assertion on a tree-sitter Tree.
2978///
2979/// Maps well-known method names to the appropriate C# static helper calls on the
2980/// generated lib class, falling back to `result_var.PascalCase()` for unknowns.
2981fn build_csharp_method_call(
2982    result_var: &str,
2983    method_name: &str,
2984    args: Option<&serde_json::Value>,
2985    class_name: &str,
2986) -> String {
2987    match method_name {
2988        "root_child_count" => format!("{result_var}.RootNode.ChildCount"),
2989        "root_node_type" => format!("{result_var}.RootNode.Kind"),
2990        "named_children_count" => format!("{result_var}.RootNode.NamedChildCount"),
2991        "has_error_nodes" => format!("{class_name}.TreeHasErrorNodes({result_var})"),
2992        "error_count" | "tree_error_count" => format!("{class_name}.TreeErrorCount({result_var})"),
2993        "tree_to_sexp" => format!("{class_name}.TreeToSexp({result_var})"),
2994        "contains_node_type" => {
2995            let node_type = args
2996                .and_then(|a| a.get("node_type"))
2997                .and_then(|v| v.as_str())
2998                .unwrap_or("");
2999            format!("{class_name}.TreeContainsNodeType({result_var}, \"{node_type}\")")
3000        }
3001        "find_nodes_by_type" => {
3002            let node_type = args
3003                .and_then(|a| a.get("node_type"))
3004                .and_then(|v| v.as_str())
3005                .unwrap_or("");
3006            format!("{class_name}.FindNodesByType({result_var}, \"{node_type}\")")
3007        }
3008        "run_query" => {
3009            let query_source = args
3010                .and_then(|a| a.get("query_source"))
3011                .and_then(|v| v.as_str())
3012                .unwrap_or("");
3013            let language = args
3014                .and_then(|a| a.get("language"))
3015                .and_then(|v| v.as_str())
3016                .unwrap_or("");
3017            format!("{class_name}.RunQuery({result_var}, \"{language}\", \"{query_source}\", source)")
3018        }
3019        _ => {
3020            use heck::ToUpperCamelCase;
3021            let pascal = method_name.to_upper_camel_case();
3022            format!("{result_var}.{pascal}()")
3023        }
3024    }
3025}
3026
3027fn fixture_has_csharp_callable(fixture: &Fixture, e2e_config: &E2eConfig) -> bool {
3028    // HTTP fixtures are handled separately — not our concern here.
3029    if fixture.is_http_test() {
3030        return false;
3031    }
3032    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
3033    let cs_override = call_config
3034        .overrides
3035        .get("csharp")
3036        .or_else(|| e2e_config.call.overrides.get("csharp"));
3037    // When a client_factory is configured the fixture is callable via the client pattern.
3038    if cs_override.and_then(|o| o.client_factory.as_deref()).is_some() {
3039        return true;
3040    }
3041    // C# binding provides a default class name (e.g., KreuzcrawlLib) if not overridden,
3042    // so any function name makes a callable available.
3043    cs_override.and_then(|o| o.function.as_deref()).is_some() || !call_config.function.is_empty()
3044}
3045
3046/// Classify a fixture string value that maps to a `bytes` argument.
3047/// Determines whether to treat it as a file path, inline text, or base64-encoded data.
3048fn classify_bytes_value_csharp(s: &str) -> String {
3049    // File paths: start with alphanumeric/underscore, contain "/" with extension
3050    // e.g., "pdf/fake.pdf", "images/test.png"
3051    if let Some(first) = s.chars().next() {
3052        if first.is_ascii_alphanumeric() || first == '_' {
3053            if let Some(slash_pos) = s.find('/') {
3054                if slash_pos > 0 {
3055                    let after_slash = &s[slash_pos + 1..];
3056                    if after_slash.contains('.') && !after_slash.is_empty() {
3057                        // File path: use File.ReadAllBytes(path)
3058                        return format!("System.IO.File.ReadAllBytes(\"{}\")", s);
3059                    }
3060                }
3061            }
3062        }
3063    }
3064
3065    // Inline text: starts with markup or contains spaces
3066    // e.g., "<html>...", "{...}", "[...]", "text with spaces"
3067    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
3068        // Inline text: use System.Text.Encoding.UTF8.GetBytes()
3069        return format!("System.Text.Encoding.UTF8.GetBytes(\"{}\")", escape_csharp(s));
3070    }
3071
3072    // Base64: base64-like pattern (uppercase/lowercase letters, digits, +, /, =)
3073    // e.g., "/9j/4AAQ", "SGVsbG8gV29ybGQ="
3074    // Use Convert.FromBase64String()
3075    format!("System.Convert.FromBase64String(\"{}\")", s)
3076}