//! Shared streaming-virtual-fields module for e2e test codegen.
//!
//! Chat-stream fixtures assert on "virtual" fields that don't exist on the
//! stream result type itself — `chunks`, `chunks.length`, `stream_content`,
//! `stream_complete`, `no_chunks_after_done`, `tool_calls`, `finish_reason`.
//! These fields resolve against the *collected* list of chunks produced by
//! draining the stream.
//!
//! [`StreamingFieldResolver`] provides two entry points:
//! - [`StreamingFieldResolver::accessor`] — the language-specific expression
//!   for a virtual field given a local variable that holds the collected list.
//! - [`StreamingFieldResolver::collect_snippet`] — the language-specific
//!   code snippet that drains a stream variable into the collected list.
//!
//! ## Convention
//!
//! The `chunks_var` parameter is the local variable name that holds the
//! collected list (default: `"chunks"`).  The `stream_var` parameter is the
//! result variable produced by the stream call (default: `"result"`).
//!
//! The set of streaming-virtual field names handled by this module:
//! - `chunks`              → the collected list itself
//! - `chunks.length`       → length/count of the collected list
//! - `stream_content`      → concatenation of all delta content strings
//! - `stream_complete`     → boolean — last chunk has a non-null finish_reason
//! - `no_chunks_after_done` → structural invariant (true by construction for
//!   channel/iterator-based APIs once the channel is closed; emitted as
//!   `assert!(true)` / `assertTrue` for languages without post-DONE chunk plumbing)
//! - `tool_calls`          → flat list of tool_calls from all chunk deltas
//! - `finish_reason`       → finish_reason string from the last chunk

/// The set of field names treated as streaming-virtual fields.
pub const STREAMING_VIRTUAL_FIELDS: &[&str] = &[
    "chunks",
    "chunks.length",
    "stream_content",
    "stream_complete",
    "no_chunks_after_done",
    "tool_calls",
    "finish_reason",
    // Crawl-stream event-variant predicates: resolve against the collected
    // `chunks` list where each item is a tagged-union CrawlEvent (`page` /
    // `error` / `complete`). `event_count_min` is a synonym for the chunk
    // count, used with `greater_than_or_equal` to assert "at least N events".
    "stream.has_page_event",
    "stream.has_error_event",
    "stream.has_complete_event",
    "stream.event_count_min",
];

/// The set of streaming-virtual root names that may have deep-path continuations.
///
/// A field like `tool_calls[0].function.name` starts with `tool_calls` and has
/// a continuation `[0].function.name`. These are handled by
/// [`StreamingFieldResolver::accessor`] via the deep-path logic.
///
/// `usage` is a stream-level root: `usage.total_tokens` resolves against the
/// last chunk that carried a usage payload (accessed via the collected chunks
/// list). Python accessor: `(chunks[-1].usage if chunks else None)`.
const STREAMING_VIRTUAL_ROOTS: &[&str] = &["tool_calls", "finish_reason"];

/// Returns `true` when `field` is a streaming-virtual field name, including
/// deep-nested paths that start with a known streaming-virtual root.
///
/// Examples that return `true`:
/// - `"tool_calls"` (exact root)
/// - `"tool_calls[0].function.name"` (deep path)
/// - `"tool_calls[0].id"` (deep path)
pub fn is_streaming_virtual_field(field: &str) -> bool {
    if STREAMING_VIRTUAL_FIELDS.contains(&field) {
        return true;
    }
    // Check deep-path prefixes: `tool_calls[…` or `tool_calls.`
    for root in STREAMING_VIRTUAL_ROOTS {
        if field.len() > root.len() && field.starts_with(root) {
            let rest = &field[root.len()..];
            if rest.starts_with('[') || rest.starts_with('.') {
                return true;
            }
        }
    }
    false
}

/// Split a field path into `(root, tail)` when it starts with a streaming-virtual
/// root and has a continuation.
///
/// Returns `None` when the field is an exact root match (no tail) or is not a
/// streaming-virtual root at all.
fn split_streaming_deep_path(field: &str) -> Option<(&str, &str)> {
    for root in STREAMING_VIRTUAL_ROOTS {
        if field.len() > root.len() && field.starts_with(root) {
            let rest = &field[root.len()..];
            if rest.starts_with('[') || rest.starts_with('.') {
                return Some((root, rest));
            }
        }
    }
    None
}

/// Field names that unambiguously imply a streaming test (no overlap with
/// non-streaming response shapes). `usage`, `tool_calls`, and `finish_reason`
/// are intentionally excluded — they exist on non-streaming responses too
/// (`usage.total_tokens` on ChatCompletionResponse, `choices[0].finish_reason`,
/// etc.) and would otherwise drag non-streaming fixtures into streaming
/// codegen.
const STREAMING_ONLY_AUTO_DETECT_FIELDS: &[&str] = &[
    "chunks",
    "chunks.length",
    "stream_content",
    "stream_complete",
    "no_chunks_after_done",
    "stream.has_page_event",
    "stream.has_error_event",
    "stream.has_complete_event",
    "stream.event_count_min",
];

/// Resolve whether a fixture should be treated as streaming, honoring the
/// call-level three-valued opt-in/out (`CallConfig::streaming`):
///
/// - `Some(true)` → forced streaming.
/// - `Some(false)` → forced non-streaming (skip the auto-detect even when an
///   assertion references a streaming-virtual-field name like `chunks`).
/// - `None` → auto-detect: streaming iff the fixture has a streaming mock
///   (`mock_response.stream_chunks`) or any assertion references one of the
///   unambiguous streaming-only field names.
///
/// All backends should use this helper so the opt-out is respected uniformly.
pub fn resolve_is_streaming(fixture: &crate::e2e::fixture::Fixture, call_streaming: Option<bool>) -> bool {
    if let Some(forced) = call_streaming {
        return forced;
    }
    fixture.is_streaming_mock()
        || fixture.assertions.iter().any(|a| {
            a.field
                .as_deref()
                .is_some_and(|f| !f.is_empty() && STREAMING_ONLY_AUTO_DETECT_FIELDS.contains(&f))
        })
}

/// Shared streaming-virtual-fields resolver for e2e test codegen.
pub struct StreamingFieldResolver;

impl StreamingFieldResolver {
    /// Returns the language-specific expression for a streaming-virtual field,
    /// given `chunks_var` (the collected-list local name) and `lang`.
    ///
    /// Returns `None` when the field name is not a known streaming-virtual
    /// field or the language has no streaming support.
    ///
    /// `module_qualifier` carries the per-project module/crate name used by the
    /// Rust and C# `stream.has_*_event` branches to construct the streaming
    /// union type path. Pass the cargo crate name (snake_case) for Rust callers
    /// and the C# namespace (PascalCase) for C# callers. When `None` is
    /// supplied for those branches, the accessor returns `None` so the call
    /// site can skip the assertion rather than emit code referencing an unknown
    /// type.
    pub fn accessor(field: &str, lang: &str, chunks_var: &str) -> Option<String> {
        Self::accessor_with_module_qualifier(field, lang, chunks_var, None)
    }

    /// Same as [`Self::accessor`] but accepts a per-project module qualifier
    /// for the `stream.has_*_event` branches that emit a streaming union type
    /// path.
    ///
    /// This is a backward-compatible wrapper; it forwards to
    /// [`Self::accessor_with_streaming_context`] with the legacy default item
    /// type `"CrawlEvent"` so existing callers continue to emit correct code for
    /// kreuzcrawl without changes. Consumers whose streaming union type differs
    /// should call [`Self::accessor_with_streaming_context`] directly.
    pub fn accessor_with_module_qualifier(
        field: &str,
        lang: &str,
        chunks_var: &str,
        module_qualifier: Option<&str>,
    ) -> Option<String> {
        // Pass the legacy default item type so the `stream.has_*_event` branches
        // continue to work for callers that predate the generic API.
        Self::accessor_with_streaming_context(field, lang, chunks_var, module_qualifier, Some("CrawlEvent"))
    }

    /// Same as [`Self::accessor_with_module_qualifier`] but also accepts the
    /// unqualified name of the streaming union item type (e.g. `"CrawlEvent"`
    /// for kreuzcrawl, or any other tagged-union name a consumer defines).
    ///
    /// When `item_type` is `None` the `stream.has_*_event` branches fall back
    /// to the legacy default supplied by the originating consumer — callers
    /// that do not know their item type should pass `None` and the function
    /// returns `None` for those branches, so the assertion is skipped rather
    /// than emitting a reference to an unknown type.
    pub fn accessor_with_streaming_context(
        field: &str,
        lang: &str,
        chunks_var: &str,
        module_qualifier: Option<&str>,
        item_type: Option<&str>,
    ) -> Option<String> {
        match field {
            "chunks" => Some(match lang {
                // Zig ArrayList does not expose .len directly; must use .items
                "zig" => format!("{chunks_var}.items"),
                // PHP variables require `$` sigil — bareword `chunks` is parsed as a
                // constant reference and triggers "Undefined constant" errors.
                "php" => format!("${chunks_var}"),
                _ => chunks_var.to_string(),
            }),

            "chunks.length" => Some(match lang {
                "rust" => format!("{chunks_var}.len()"),
                "go" => format!("len({chunks_var})"),
                "python" => format!("len({chunks_var})"),
                "php" => format!("count(${chunks_var})"),
                "elixir" => format!("length({chunks_var})"),
                // kotlin List.size is a property (not .length)
                "kotlin" => format!("{chunks_var}.size"),
                // zig: chunks_var is ArrayList([]u8); use .items.len
                "zig" => format!("{chunks_var}.items.len"),
                // Swift Array uses .count (Collection protocol)
                "swift" => format!("{chunks_var}.count"),
                // node/wasm/typescript use .length
                _ => format!("{chunks_var}.length"),
            }),

            "stream_content" => Some(match lang {
                "rust" => {
                    format!(
                        "{chunks_var}.iter().map(|c| c.choices.first().and_then(|ch| ch.delta.content.as_deref()).unwrap_or(\"\")).collect::<String>()"
                    )
                }
                "go" => {
                    // Go: chunks is []pkg.ChatCompletionChunk
                    format!(
                        "func() string {{ var s string; for _, c := range {chunks_var} {{ if len(c.Choices) > 0 && c.Choices[0].Delta.Content != nil {{ s += *c.Choices[0].Delta.Content }} }}; return s }}()"
                    )
                }
                "java" => {
                    format!(
                        "{chunks_var}.stream().map(c -> c.choices().stream().findFirst().map(ch -> ch.delta().content() != null ? ch.delta().content() : \"\").orElse(\"\")).collect(java.util.stream.Collectors.joining())"
                    )
                }
                "php" => {
                    format!("implode('', array_map(fn($c) => $c->choices[0]->delta->content ?? '', ${chunks_var}))")
                }
                "kotlin" => {
                    // Kotlin: chunks is List<ChatCompletionChunk> (Java records via typealias).
                    // choices() / delta() / content() are Java record accessor methods.
                    format!(
                        "{chunks_var}.joinToString(\"\") {{ it.choices()?.firstOrNull()?.delta()?.content() ?: \"\" }}"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!("{chunks_var}.joinToString(\"\") {{ it.choices?.firstOrNull()?.delta?.content ?: \"\" }}")
                }
                "elixir" => {
                    // StreamDelta has all fields optional with skip_serializing_if, so
                    // absent fields are not present as keys in the Jason-decoded map.
                    // Use Map.get with defaults to avoid KeyError on absent :content.
                    format!(
                        "{chunks_var} |> Enum.map(fn c -> (Enum.at(c.choices, 0) || %{{}}) |> Map.get(:delta, %{{}}) |> Map.get(:content, \"\") end) |> Enum.join(\"\")"
                    )
                }
                "python" => {
                    format!("\"\".join(c.choices[0].delta.content or \"\" for c in {chunks_var} if c.choices)")
                }
                "zig" => {
                    // Zig: `{chunks_var}_content` is a `std.ArrayList(u8)` populated by
                    // the collect snippet. `.items` gives a `[]u8` slice of the content.
                    format!("{chunks_var}_content.items")
                }
                // Swift: chunks is [<Module>.ChatCompletionChunk] (first-class
                // Codable struct emitted by alef-backend-swift). choices is
                // `[StreamChoice]` (property), delta is `StreamDelta` (property),
                // content is `String?` (property). No `.toString()` wrapping —
                // first-class fields are already native Swift values.
                "swift" => {
                    format!(
                        "{chunks_var}.map {{ c in c.choices.first.flatMap {{ ch in ch.delta.content }} ?? \"\" }}.joined()"
                    )
                }
                // Ruby: choices returns Array<StreamChoice>, use .first with safe navigation
                "ruby" => {
                    format!("{chunks_var}.map {{ |c| c.choices.first&.delta&.content || '' }}.join")
                }
                // node/wasm/typescript
                _ => {
                    format!("{chunks_var}.map((c: any) => c.choices?.[0]?.delta?.content ?? '').join('')")
                }
            }),

            "stream_complete" => Some(match lang {
                "rust" => {
                    format!(
                        "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).is_some()"
                    )
                }
                "go" => {
                    format!(
                        "func() bool {{ if len({chunks_var}) == 0 {{ return false }}; last := {chunks_var}[len({chunks_var})-1]; return len(last.Choices) > 0 && last.Choices[0].FinishReason != nil }}()"
                    )
                }
                "java" => {
                    format!(
                        "!{chunks_var}.isEmpty() && {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().flatMap(ch -> java.util.Optional.ofNullable(ch.finishReason())).isPresent()"
                    )
                }
                "php" => {
                    // PHP streaming chunks come from `json_decode` of the binding's JSON
                    // string return. The PHP binding serializes with rename_all = "camelCase",
                    // so use `finishReason` (camelCase) to match the emitted JSON keys.
                    format!("!empty(${chunks_var}) && isset(end(${chunks_var})->choices[0]->finishReason)")
                }
                "kotlin" => {
                    // Kotlin: use isNotEmpty() + last() + safe-call chain
                    format!(
                        "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices()?.firstOrNull()?.finishReason() != null"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!(
                        "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices?.firstOrNull()?.finishReason != null"
                    )
                }
                "python" => {
                    format!("bool({chunks_var}) and {chunks_var}[-1].choices[0].finish_reason is not None")
                }
                "elixir" => {
                    format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason != nil")
                }
                // zig: the collect snippet exhausts the stream; check last chunk JSON
                // was collected (chunks.items is non-empty) as a proxy for completion.
                "zig" => {
                    format!("{chunks_var}.items.len > 0")
                }
                // Swift: chunks is [<Module>.ChatCompletionChunk] first-class
                // struct. `choices` is `[StreamChoice]` (property), `finishReason`
                // is `FinishReason?` (property, camelCase).
                "swift" => {
                    format!("!{chunks_var}.isEmpty && {chunks_var}.last!.choices.first?.finishReason != nil")
                }
                // Ruby: choices/finish_reason are Magnus method accessors; use safe navigation
                "ruby" => {
                    format!("!{chunks_var}.empty? && !{chunks_var}.last&.choices&.first&.finish_reason.nil?")
                }
                // node/wasm/typescript
                _ => {
                    format!(
                        "{chunks_var}.length > 0 && {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason != null"
                    )
                }
            }),

            // no_chunks_after_done is a structural invariant: once the stream
            // closes (channel drained / iterator exhausted), no further chunks
            // can arrive.  We assert `true` as a compile-time proof of intent.
            "no_chunks_after_done" => Some(match lang {
                "rust" => "true".to_string(),
                "go" => "true".to_string(),
                "java" => "true".to_string(),
                "php" => "true".to_string(),
                _ => "true".to_string(),
            }),

            // Streaming union event-variant predicates.
            //
            // Each chunk is a tagged union whose concrete type name is given by
            // `item_type` (e.g. `"CrawlEvent"` for kreuzcrawl). The accessor
            // returns a language-native boolean expression that is `true` iff
            // any chunk in the collected list matches the named variant.
            //
            // When `item_type` is `None` the helper returns `None` so the
            // assertion is silently skipped — callers must supply the type name
            // to emit working code.
            //
            // PHP and WASM intentionally return `None`: PHP's crawl-stream is
            // exposed as eager JSON (see `chunks_var` collect_snippet) and WASM
            // does not support streaming on `wasm32` targets.
            "stream.has_page_event" => item_type
                .and_then(|ty| has_event_variant_accessor(lang, chunks_var, EventVariant::Page, ty, module_qualifier)),
            "stream.has_error_event" => item_type
                .and_then(|ty| has_event_variant_accessor(lang, chunks_var, EventVariant::Error, ty, module_qualifier)),
            "stream.has_complete_event" => item_type.and_then(|ty| {
                has_event_variant_accessor(lang, chunks_var, EventVariant::Complete, ty, module_qualifier)
            }),

            // event_count_min is the collected chunks count — used with
            // `greater_than_or_equal` assertions on the chunk count.  Render the
            // language-appropriate length/size accessor.
            "stream.event_count_min" => Some(match lang {
                "java" => format!("{chunks_var}.size()"),
                "go" => format!("len({chunks_var})"),
                "php" => format!("count(${chunks_var})"),
                "kotlin" | "kotlin_android" => format!("{chunks_var}.size"),
                "python" => format!("len({chunks_var})"),
                "rust" => format!("{chunks_var}.len()"),
                "node" | "typescript" | "wasm" => format!("{chunks_var}.length"),
                "swift" => format!("{chunks_var}.count"),
                "zig" => format!("{chunks_var}.items.len"),
                "ruby" => format!("{chunks_var}.length"),
                "elixir" => format!("length({chunks_var})"),
                "c" => format!("vlen({chunks_var})"),
                _ => format!("{chunks_var}.length"),
            }),

            "tool_calls" => Some(match lang {
                "rust" => {
                    format!(
                        "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten())).collect::<Vec<_>>()"
                    )
                }
                "go" => {
                    // StreamDelta.ToolCalls is `[]StreamToolCall` (slice, not pointer).
                    // Return the typed slice so deep-path accessors like `tool_calls[0].function.name`
                    // can index and access typed fields.
                    format!(
                        "func() []pkg.StreamToolCall {{ var tc []pkg.StreamToolCall; for _, c := range {chunks_var} {{ for _, ch := range c.Choices {{ tc = append(tc, ch.Delta.ToolCalls...) }} }}; return tc }}()"
                    )
                }
                "java" => {
                    format!(
                        "{chunks_var}.stream().flatMap(c -> c.choices().stream()).flatMap(ch -> ch.delta().toolCalls() != null ? ch.delta().toolCalls().stream() : java.util.stream.Stream.empty()).toList()"
                    )
                }
                "php" => {
                    // PHP streaming chunks are json_decoded stdClass. The PHP binding
                    // serializes with rename_all = "camelCase", so use `toolCalls`.
                    format!(
                        "array_merge(...array_map(fn($c) => $c->choices[0]->delta->toolCalls ?? [], ${chunks_var}))"
                    )
                }
                "kotlin" => {
                    // Kotlin: flatten tool_calls from all chunk deltas into one list
                    format!(
                        "{chunks_var}.flatMap {{ c -> c.choices()?.flatMap {{ ch -> ch.delta()?.toolCalls() ?: emptyList() }} ?: emptyList() }}"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!(
                        "{chunks_var}.flatMap {{ c -> c.choices?.flatMap {{ ch -> ch.delta?.toolCalls ?: emptyList() }} ?: emptyList() }}"
                    )
                }
                "python" => {
                    format!(
                        "[t for c in {chunks_var} for ch in (c.choices or []) for t in (ch.delta.tool_calls or [])]"
                    )
                }
                "elixir" => {
                    format!(
                        "{chunks_var} |> Enum.flat_map(fn c -> (List.first(c.choices) || %{{}}).delta |> Map.get(:tool_calls, []) end)"
                    )
                }
                // Zig: tool_calls count from all chunk deltas
                "zig" => {
                    format!("{chunks_var}.items")
                }
                // Swift: chunks is [<Module>.ChatCompletionChunk] first-class
                // Codable struct. choices is `[StreamChoice]`, delta is
                // `StreamDelta`, toolCalls is `[StreamToolCall]?`.
                "swift" => {
                    format!(
                        "{chunks_var}.flatMap {{ c -> [StreamToolCall] in guard let ch = c.choices.first, let tcs = ch.delta.toolCalls else {{ return [] }}; return tcs }}"
                    )
                }
                // Ruby: choices/delta/tool_calls are Magnus method accessors;
                // delta.tool_calls returns nil when absent — default to empty array.
                "ruby" => {
                    format!("{chunks_var}.flat_map {{ |c| c.choices&.first&.delta&.tool_calls || [] }}")
                }
                _ => {
                    format!("{chunks_var}.flatMap((c: any) => c.choices?.[0]?.delta?.toolCalls ?? [])")
                }
            }),

            "finish_reason" => Some(match lang {
                "rust" => {
                    // ChatCompletionChunk's finish_reason is Option<FinishReason> (enum, not
                    // String). Display impl writes the JSON wire form (e.g. "tool_calls").
                    format!(
                        "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).map(|v| v.to_string()).unwrap_or_default()"
                    )
                }
                "go" => {
                    // FinishReason is a typed alias (`type FinishReason string`) in bindings,
                    // so cast to string explicitly to match the assertion target type.
                    format!(
                        "func() string {{ if len({chunks_var}) == 0 {{ return \"\" }}; last := {chunks_var}[len({chunks_var})-1]; if len(last.Choices) > 0 && last.Choices[0].FinishReason != nil {{ return string(*last.Choices[0].FinishReason) }}; return \"\" }}()"
                    )
                }
                "java" => {
                    // FinishReason.getValue() returns the JSON wire string (e.g. "tool_calls").
                    // Without it, assertEquals(String, FinishReason) fails because Object.equals
                    // doesn't cross types even when toString() matches.
                    format!(
                        "({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().map(ch -> ch.finishReason() == null ? null : ch.finishReason().getValue()).orElse(null))"
                    )
                }
                "php" => {
                    // PHP streaming chunks are json_decoded stdClass. The PHP binding
                    // serializes with rename_all = "camelCase", so use `finishReason`.
                    format!("(!empty(${chunks_var}) ? (end(${chunks_var})->choices[0]->finishReason ?? null) : null)")
                }
                "kotlin" => {
                    // Returns the string value of the finish_reason enum from the last chunk.
                    // FinishReason.getValue() returns the JSON wire string (e.g. "tool_calls").
                    format!(
                        "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices()?.firstOrNull()?.finishReason()?.getValue())"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: plain Kotlin enum class uses .name.lowercase() for wire string.
                    format!(
                        "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices?.firstOrNull()?.finishReason?.name?.lowercase())"
                    )
                }
                "python" => {
                    // FinishReason is a PyO3 enum object, not a plain string.
                    // Wrap in str() so callers can do `.strip()` / string comparisons
                    // without `AttributeError: 'FinishReason' has no attribute 'strip'`.
                    format!(
                        "(str({chunks_var}[-1].choices[0].finish_reason) if {chunks_var} and {chunks_var}[-1].choices else None)"
                    )
                }
                "elixir" => {
                    format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason")
                }
                // Zig: finish_reason from the last chunk's JSON via an inline labeled block.
                // Returns `[]const u8` (unwrapped with orelse "" for expectEqualStrings).
                "zig" => {
                    format!(
                        "(blk: {{ if ({chunks_var}.items.len == 0) break :blk \"\"; var _lcp = std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {chunks_var}.items[{chunks_var}.items.len - 1], .{{}}) catch break :blk \"\"; defer _lcp.deinit(); if (_lcp.value.object.get(\"choices\")) |_lchs| if (_lchs.array.items.len > 0) if (_lchs.array.items[0].object.get(\"finish_reason\")) |_fr| if (_fr == .string) break :blk _fr.string; break :blk \"\"; }})"
                    )
                }
                // Swift: first-class `StreamChoice.finishReason: FinishReason?`
                // where FinishReason is a Codable Swift enum with `String` raw
                // values matching serde wire strings. `.rawValue` yields e.g.
                // "tool_calls" for cross-language fixture parity.
                "swift" => {
                    format!("({chunks_var}.isEmpty ? nil : {chunks_var}.last!.choices.first?.finishReason?.rawValue)")
                }
                // Ruby: FinishReason is a Magnus-wrapped enum. Call .to_s to get the
                // wire string (e.g. "tool_calls") for cross-language fixture parity.
                "ruby" => {
                    format!("({chunks_var}.empty? ? nil : {chunks_var}.last&.choices&.first&.finish_reason&.to_s)")
                }
                _ => {
                    format!(
                        "{chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason : undefined"
                    )
                }
            }),

            // `usage` is a stream-level virtual root: resolves against the last
            // chunk that carried a usage payload.  Deep paths like `usage.total_tokens`
            // are handled by the deep-path logic in the `_` arm below (root=`usage`,
            // tail=`.total_tokens`), which calls this base accessor and appends the tail.
            "usage" => Some(match lang {
                "python" => {
                    // Access the last chunk's usage object (may be None).
                    // Deep paths like usage.total_tokens are rendered as:
                    //   (chunks[-1].usage if chunks else None).total_tokens
                    format!("({chunks_var}[-1].usage if {chunks_var} else None)")
                }
                "rust" => {
                    format!("{chunks_var}.last().and_then(|c| c.usage.as_ref())")
                }
                "go" => {
                    format!(
                        "func() interface{{}} {{ if len({chunks_var}) == 0 {{ return nil }}; return {chunks_var}[len({chunks_var})-1].Usage }}()"
                    )
                }
                "java" => {
                    format!("({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).usage())")
                }
                "kotlin" => {
                    format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage())")
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage)")
                }
                "php" => {
                    format!("(!empty(${chunks_var}) ? end(${chunks_var})->usage ?? null : null)")
                }
                "elixir" => {
                    format!("(if length({chunks_var}) > 0, do: List.last({chunks_var}).usage, else: nil)")
                }
                // Swift: first-class `ChatCompletionChunk.usage: Usage?`
                // (Codable struct property — no method call).
                "swift" => {
                    format!("({chunks_var}.isEmpty ? nil : {chunks_var}.last!.usage)")
                }
                // Ruby: usage is a Magnus method accessor; returns nil when absent.
                "ruby" => {
                    format!("({chunks_var}.empty? ? nil : {chunks_var}.last&.usage)")
                }
                _ => {
                    format!("({chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].usage : undefined)")
                }
            }),

            _ => {
                // Deep-path: e.g. `tool_calls[0].function.name`
                // Split into root + tail, get the root's inline expression, then
                // render the tail (index + fields) in a per-language style on top.
                if let Some((root, tail)) = split_streaming_deep_path(field) {
                    // Rust needs Option-aware chaining for the StreamToolCall fields
                    // (function/id are Option<...>). The generic tail renderer can't
                    // infer Option-wrapping, so we emit rust-specific idiom here.
                    if lang == "rust" && root == "tool_calls" {
                        return Some(render_rust_tool_calls_deep(chunks_var, tail));
                    }
                    // Swift: StreamToolCallRef fields are swift-bridge methods returning
                    // Optional.  The generic render_deep_tail doesn't know to add `()`
                    // or optional-chain with `?.`, so use a dedicated renderer.
                    if lang == "swift" && root == "tool_calls" {
                        let root_expr = Self::accessor(root, lang, chunks_var)?;
                        return Some(render_swift_tool_calls_deep(&root_expr, tail));
                    }
                    // Zig stores stream chunks as JSON strings (`[]const u8`) in
                    // `chunks: ArrayList([]u8)`, not typed `ChatCompletionChunk`
                    // records. A deep `tool_calls[N].function.name` access would
                    // require parsing each chunk's JSON inline — rather than
                    // emit code that won't compile, signal "unsupported" so the
                    // assertion is skipped at the call site.
                    if lang == "zig" && root == "tool_calls" {
                        return None;
                    }
                    let root_expr = Self::accessor(root, lang, chunks_var)?;
                    Some(render_deep_tail(&root_expr, tail, lang))
                } else {
                    None
                }
            }
        }
    }

    /// Returns the language-specific stream-collect-into-list snippet that
    /// produces `chunks_var` from `stream_var`.
    ///
    /// Returns `None` when the language has no streaming collect support or
    /// when the collect snippet cannot be expressed generically.
    pub fn collect_snippet(lang: &str, stream_var: &str, chunks_var: &str) -> Option<String> {
        Self::collect_snippet_typed(lang, stream_var, chunks_var, None)
    }

    /// Collect stream into a list, with optional item_type for languages that need the concrete type.
    ///
    /// When item_type is None, defaults to ChatCompletionChunk for backward compatibility with
    /// liter-llm. For other projects like kreuzcrawl, item_type should be provided (e.g., "CrawlEvent").
    pub fn collect_snippet_typed(
        lang: &str,
        stream_var: &str,
        chunks_var: &str,
        item_type: Option<&str>,
    ) -> Option<String> {
        let item_type = item_type.unwrap_or("ChatCompletionChunk");
        match lang {
            "rust" => Some(format!(
                "let {chunks_var}: Vec<_> = tokio_stream::StreamExt::collect::<Vec<_>>({stream_var}).await\n        .into_iter()\n        .map(|r| r.expect(\"stream item failed\"))\n        .collect();"
            )),
            "go" => Some(format!(
                "var {chunks_var} []pkg.{item_type}\n\tfor chunk := range {stream_var} {{\n\t\t{chunks_var} = append({chunks_var}, chunk)\n\t}}"
            )),
            "java" => Some(format!(
                "var {chunks_var} = new java.util.ArrayList<{item_type}>();\n        var _it = {stream_var}.iterator();\n        while (_it.hasNext()) {{ {chunks_var}.add(_it.next()); }}"
            )),
            // PHP binding's chat_stream returns Vec<String> (each element is a
            // JSON-serialized chunk) because ext-php-rs can't expose Rust
            // iterators directly. Decode each element and recursively
            // camelCase the keys so accessor chains like
            // `$c->choices[0]->delta->finishReason` resolve against what the
            // non-streaming PHP binding returns (camelCase getters). Three
            // input shapes are tolerated: (a) array of JSON strings — the
            // current binding; (b) single concatenated JSON — older binding
            // output; (c) a real iterator — future binding upgrade.
            "php" => Some(format!(
                "$__camel = function ($v) use (&$__camel) {{ \
                    if (is_array($v)) {{ \
                        $out = []; \
                        foreach ($v as $k => $vv) {{ \
                            $key = is_string($k) ? lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $k)))) : $k; \
                            $out[$key] = $__camel($vv); \
                        }} \
                        return (array_keys($out) === range(0, count($out) - 1)) ? $out : (object) $out; \
                    }} \
                    if (is_object($v)) {{ \
                        $out = new \\stdClass(); \
                        foreach (get_object_vars($v) as $k => $vv) {{ \
                            $key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $k)))); \
                            $out->{{$key}} = $__camel($vv); \
                        }} \
                        return $out; \
                    }} \
                    return $v; \
                }};\n        \
                $__decode_chunk = fn($c) => $__camel(is_string($c) ? json_decode($c, true) : (is_array($c) || is_object($c) ? json_decode(json_encode($c), true) : $c));\n        \
                ${chunks_var} = is_string(${stream_var}) \
                    ? array_map($__decode_chunk, (array)(json_decode(${stream_var}, true) ?: [])) \
                    : (is_array(${stream_var}) \
                        ? array_map($__decode_chunk, ${stream_var}) \
                        : array_map($__decode_chunk, iterator_to_array(${stream_var})));"
            )),
            "python" => Some(format!(
                "{chunks_var} = []\n    async for chunk in {stream_var}:\n        {chunks_var}.append(chunk)"
            )),
            "kotlin" => {
                // Kotlin: chatStream returns Iterator<ChatCompletionChunk> (from Java bridge).
                // Drain into a Kotlin List using asSequence().toList().
                Some(format!("val {chunks_var} = {stream_var}.asSequence().toList()"))
            }
            "kotlin_android" => {
                // kotlin-android: chatStream returns Flow<ChatCompletionChunk> (kotlinx.coroutines).
                // Collect inside a runBlocking coroutine scope using Flow.toList().
                Some(format!("val {chunks_var} = {stream_var}.toList()"))
            }
            "elixir" => Some(format!("{chunks_var} = Enum.to_list({stream_var})")),
            // WASM's chatStream returns a hand-rolled `ChatStreamIterator`
            // struct that exposes `next()` returning `Promise<chunk | null>`,
            // not a JS async iterable. wasm-bindgen does not auto-emit the
            // `Symbol.asyncIterator` protocol, so `for await` on this object
            // throws `TypeError: stream is not async iterable`. Drain via an
            // explicit while/next() loop instead.
            "wasm" => Some(format!(
                "const {chunks_var}: any[] = [];\n    while (true) {{ const _chunk = await {stream_var}.next(); if (_chunk == null) break; {chunks_var}.push(_chunk); }}"
            )),
            "node" | "typescript" => Some(format!(
                "const {chunks_var}: any[] = [];\n    for await (const _chunk of {stream_var}) {{ {chunks_var}.push(_chunk); }}"
            )),
            "swift" => {
                // Swift's chat-stream wrapper returns AsyncThrowingStream<ChunkType, Error>,
                // so consumers drain it with `for try await chunk in stream { ... }`. The
                // chunk type is decoded from the bridge-boundary JSON inside the wrapper —
                // here we just collect the typed Swift values.
                // When item_type is provided (e.g., "CrawlEvent" from kreuzcrawl adapters),
                // use it; otherwise default to "ChatCompletionChunk" for backward compatibility.
                Some(format!(
                    "var {chunks_var}: [{item_type}] = []\n        for try await _chunk in {stream_var} {{ {chunks_var}.append(_chunk) }}"
                ))
            }
            "zig" => Some(Self::collect_snippet_zig(stream_var, chunks_var, "module", "ffi")),
            _ => None,
        }
    }

    /// Render Zig's streaming collect snippet using the configured module and FFI prefix.
    pub fn collect_snippet_zig(stream_var: &str, chunks_var: &str, module_name: &str, ffi_prefix: &str) -> String {
        let stream_next = format!("{ffi_prefix}_default_client_chat_stream_next");
        let chunk_to_json = format!("{ffi_prefix}_chat_completion_chunk_to_json");
        let chunk_free = format!("{ffi_prefix}_chat_completion_chunk_free");
        let free_string = format!("{ffi_prefix}_free_string");

        // Zig 0.16: ArrayList is unmanaged — no stored allocator.
        // Use `.empty` to initialize, pass `std.heap.c_allocator` to each mutation.
        // `stream_var` is the opaque stream handle obtained via `_start`.
        // We collect every chunk's JSON string into `chunks_var: ArrayList([]u8)`
        // and concatenate delta content into `{chunks_var}_content: ArrayList(u8)`.
        // Accessors use `.items.len` and `{chunks_var}_content.items` on these lists.
        format!(
            concat!(
                "var {chunks_var}: std.ArrayList([]u8) = .empty;
",
                "    defer {{
",
                "        for ({chunks_var}.items) |_cj| std.heap.c_allocator.free(_cj);
",
                "        {chunks_var}.deinit(std.heap.c_allocator);
",
                "    }}
",
                "    var {chunks_var}_content: std.ArrayList(u8) = .empty;
",
                "    defer {chunks_var}_content.deinit(std.heap.c_allocator);
",
                "    while (true) {{
",
                "        const _nc = {module_name}.c.{stream_next}({stream_var});
",
                "        if (_nc == null) break;
",
                "        const _np = {module_name}.c.{chunk_to_json}(_nc);
",
                "        {module_name}.c.{chunk_free}(_nc);
",
                "        if (_np == null) continue;
",
                "        const _ns = std.mem.span(_np);
",
                "        const _nj = try std.heap.c_allocator.dupe(u8, _ns);
",
                "        {module_name}.c.{free_string}(_np);
",
                "        if (std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, _nj, .{{}})) |_cp| {{
",
                "            defer _cp.deinit();
",
                "            if (_cp.value.object.get(\"choices\")) |_chs|
",
                "                if (_chs.array.items.len > 0)
",
                "                    if (_chs.array.items[0].object.get(\"delta\")) |_dl|
",
                "                        if (_dl.object.get(\"content\")) |_ct|
",
                "                            if (_ct == .string) try {chunks_var}_content.appendSlice(std.heap.c_allocator, _ct.string);
",
                "        }} else |_| {{}}
",
                "        try {chunks_var}.append(std.heap.c_allocator, _nj);
",
                "    }}"
            ),
            chunks_var = chunks_var,
            stream_var = stream_var,
            module_name = module_name,
            stream_next = stream_next,
            chunk_to_json = chunk_to_json,
            chunk_free = chunk_free,
            free_string = free_string,
        )
    }
}

/// Identifies a `CrawlEvent` variant for `stream.has_*_event` accessors.
#[derive(Debug, Clone, Copy)]
enum EventVariant {
    Page,
    Error,
    Complete,
}

impl EventVariant {
    /// Lower-case JSON-wire tag value for the `type` discriminator.
    fn tag(self) -> &'static str {
        match self {
            EventVariant::Page => "page",
            EventVariant::Error => "error",
            EventVariant::Complete => "complete",
        }
    }

    /// Upper-camel variant name as used in most language bindings
    /// (e.g. `CrawlEvent_Page`, `CrawlEventPage`, `CrawlEvent.Page`).
    fn upper_camel(self) -> &'static str {
        match self {
            EventVariant::Page => "Page",
            EventVariant::Error => "Error",
            EventVariant::Complete => "Complete",
        }
    }
}

/// Emit a language-native boolean expression that is `true` iff any chunk in
/// `chunks_var` matches the given streaming-union variant.
///
/// `item_type` is the unqualified name of the streaming union type (e.g.
/// `"CrawlEvent"` for kreuzcrawl).  `module_qualifier` is the per-project
/// module/namespace prefix required by Rust and C# to form a fully-qualified
/// type path.
///
/// Returns `None` for languages where typed streaming-union matching is not
/// expressible (PHP — eager-JSON, WASM — no streaming on wasm32).
fn has_event_variant_accessor(
    lang: &str,
    chunks_var: &str,
    variant: EventVariant,
    item_type: &str,
    module_qualifier: Option<&str>,
) -> Option<String> {
    let tag = variant.tag();
    let camel = variant.upper_camel();
    match lang {
        // Python: tagged-union exposes `.type` returning the lower-case wire tag.
        "python" => Some(format!("any(e.type == \"{tag}\" for e in {chunks_var})")),
        // Node / TypeScript: deserialized union objects expose a `type`
        // discriminator field with the lower-case wire tag.
        "node" | "typescript" => Some(format!("{chunks_var}.some((e: any) => e?.type === \"{tag}\")")),
        // Ruby: each variant class exposes `<tag>?` predicates.
        "ruby" => Some(format!("{chunks_var}.any? {{ |e| e.{tag}? }}")),
        // Go: variants are concrete struct types ({item_type}{Camel}) that
        // implement the {item_type} interface.  Use a type switch via an
        // anonymous IIFE so the accessor remains an expression.
        "go" => Some(format!(
            "func() bool {{ for _, e := range {chunks_var} {{ if _, _ok := e.(pkg.{item_type}{camel}); _ok {{ return true }} }}; return false }}()"
        )),
        // Java: sealed interface {item_type} with nested records.
        "java" => Some(format!(
            "{chunks_var}.stream().anyMatch(e -> e instanceof {item_type}.{camel})"
        )),
        // C#: abstract record {item_type} with nested sealed records.
        // The qualifier is the project's C# namespace (e.g. `Kreuzcrawl`).
        "csharp" => module_qualifier.map(|ns| format!("{chunks_var}.Any(e => e is global::{ns}.{item_type}.{camel})")),
        // Swift: the swift-bridge `to_string()` impl on the bridge enum returns the
        // serde-serialized variant name (i.e. the same wire tag the JSON discriminator
        // uses). Match on `tag` (e.g. "page", "error", "complete") rather than the raw
        // Rust identifier so the comparison aligns with whatever `rename_all` the source
        // enum declares. `to_string()` returns `RustString`; convert via `.toString()`
        // before calling `.contains()`.
        "swift" => Some(format!(
            "{chunks_var}.contains(where: {{ e in e.to_string().toString().contains(\"{tag}\") }})"
        )),
        // Elixir: each event is a map with a `:type` key whose value is a string (from JSON).
        "elixir" => Some(format!(
            "Enum.any?({chunks_var}, fn e -> Map.get(e, :type) == \"{tag}\" end)"
        )),
        // Kotlin (Java records via typealias): same shape as Java.
        "kotlin" => Some(format!("{chunks_var}.any {{ it is {item_type}.{camel} }}")),
        // kotlin-android: native sealed class with the same nested variants.
        "kotlin_android" => Some(format!("{chunks_var}.any {{ it is {item_type}.{camel} }}")),
        // Dart (freezed): variants are {item_type}_{Camel} (underscored).
        "dart" => Some(format!("{chunks_var}.any((e) => e is {item_type}_{camel})")),
        // Zig: collected chunks are JSON strings (see Zig collect_snippet); check
        // for the wire-format `"type":"<tag>"` substring on any item.  Substring
        // matching is safe because the JSON is produced by the FFI marshaller
        // with a fixed key ordering and the tag values do not collide.
        "zig" => Some(format!(
            "blk: {{ for ({chunks_var}.items) |_e| {{ if (std.mem.indexOf(u8, _e, \"\\\"type\\\":\\\"{tag}\\\"\") != null) break :blk true; }} break :blk false; }}"
        )),
        // Rust: {item_type} is a tagged enum (`#[serde(tag = "type")]`).
        // Use `matches!` for the predicate so we don't bind the variant payload.
        // The qualifier is the project's cargo crate name (snake_case).
        "rust" => module_qualifier.map(|crate_name| {
            format!("{chunks_var}.iter().any(|e| matches!(e, {crate_name}::{item_type}::{camel} {{ .. }}))")
        }),
        // PHP: crawl-stream is delivered as eager JSON (see PHP collect_snippet)
        // and the PHP binding does not expose typed union objects.
        // WASM: streaming is unavailable on wasm32 targets.
        "php" | "wasm" => None,
        _ => None,
    }
}

/// Render a Swift deep accessor for `tool_calls[N]...` paths.
///
/// The flat tool_calls array is `[StreamToolCallRef]`.  Each element is a
/// swift-bridge opaque ref: the first field after an index (e.g. `function`)
/// is accessed with `.method()` (direct call on the non-optional ref).
/// All subsequent fields use `?.method()` (optional chaining) because each
/// intermediate method returns `Optional`.  The string leaf appends
/// `?.toString()` to convert `RustString?` to `String?`.
///
/// Example: `[0].function.name`
///   → `(root)[0].function()?.name()?.toString()`
fn render_swift_tool_calls_deep(root_expr: &str, tail: &str) -> String {
    use heck::ToLowerCamelCase;
    let segs = parse_tail(tail);
    let mut expr = root_expr.to_string();
    // First-class `StreamToolCall` struct: every field is a Codable Swift
    // property (no parens). Index access on `[StreamToolCall]` returns the
    // element directly (non-optional). Subsequent `Optional` properties chain
    // with `?.`. Track whether the prior segment yielded a non-optional value:
    // - after `Index`, the element is non-optional → next field uses `.`
    // - after the first optional property access (`?.`), every subsequent
    //   field also uses `?.` (chained optional)
    let mut prev_is_optional = false;
    for seg in &segs {
        match seg {
            TailSeg::Index(n) => {
                expr = format!("({expr})[{n}]");
                prev_is_optional = false;
            }
            TailSeg::Field(f) => {
                let prop = f.to_lower_camel_case();
                let sep = if prev_is_optional { "?." } else { "." };
                expr = format!("{expr}{sep}{prop}");
                // All `StreamToolCall` fields (function/id/arguments) are
                // `Optional<...>` in the first-class binding, so chaining
                // henceforth uses `?.`.
                prev_is_optional = true;
            }
        }
    }
    expr
}

/// Render a rust deep accessor for `tool_calls[N]...` paths over the flattened
/// stream-chunk tool_calls iterator. Handles Option-wrapped fields by chaining
/// `as_ref().and_then(...)` so the final value is a `&str` (for name/id/arguments).
fn render_rust_tool_calls_deep(chunks_var: &str, tail: &str) -> String {
    let segs = parse_tail(tail);
    // Locate index segment (rust uses .nth(n) on the iterator instead of [N] on a Vec)
    let idx = segs.iter().find_map(|s| match s {
        TailSeg::Index(n) => Some(*n),
        _ => None,
    });
    let field_segs: Vec<&str> = segs
        .iter()
        .filter_map(|s| match s {
            TailSeg::Field(f) => Some(f.as_str()),
            _ => None,
        })
        .collect();

    let base = format!(
        "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten()))"
    );
    let with_nth = match idx {
        Some(n) => format!("{base}.nth({n})"),
        None => base,
    };

    // Chain Option-aware field access. Every field on StreamToolCall is Option<...>;
    // the leaf (String fields) uses `.as_deref()` to project to `&str`.
    let mut expr = with_nth;
    for (i, f) in field_segs.iter().enumerate() {
        let is_leaf = i == field_segs.len() - 1;
        if is_leaf {
            expr = format!("{expr}.and_then(|x| x.{f}.as_deref())");
        } else {
            expr = format!("{expr}.and_then(|x| x.{f}.as_ref())");
        }
    }
    format!("{expr}.unwrap_or(\"\")")
}

/// Parse a deep-path tail (e.g. `[0].function.name`) into structured segments.
///
/// The tail always starts with either `[N]` (array index) or `.field`.
/// Returns a list of segments: `TailSeg::Index(N)` or `TailSeg::Field(name)`.
#[derive(Debug, PartialEq)]
enum TailSeg {
    Index(usize),
    Field(String),
}

fn parse_tail(tail: &str) -> Vec<TailSeg> {
    let mut segs = Vec::new();
    let mut rest = tail;
    while !rest.is_empty() {
        if let Some(inner) = rest.strip_prefix('[') {
            // Array index: `[N]`
            if let Some(close) = inner.find(']') {
                let idx_str = &inner[..close];
                if let Ok(idx) = idx_str.parse::<usize>() {
                    segs.push(TailSeg::Index(idx));
                }
                rest = &inner[close + 1..];
            } else {
                break;
            }
        } else if let Some(inner) = rest.strip_prefix('.') {
            // Field name: up to next `.` or `[`
            let end = inner.find(['.', '[']).unwrap_or(inner.len());
            segs.push(TailSeg::Field(inner[..end].to_string()));
            rest = &inner[end..];
        } else {
            break;
        }
    }
    segs
}

/// Render the full deep accessor expression by appending per-language tail
/// segments onto `root_expr`.
fn render_deep_tail(root_expr: &str, tail: &str, lang: &str) -> String {
    use heck::{ToLowerCamelCase, ToPascalCase};

    let segs = parse_tail(tail);
    let mut out = root_expr.to_string();

    for seg in &segs {
        match (seg, lang) {
            (TailSeg::Index(n), "rust") => {
                out = format!("({out})[{n}]");
            }
            (TailSeg::Index(n), "java") => {
                out = format!("({out}).get({n})");
            }
            (TailSeg::Index(n), "kotlin") => {
                if *n == 0 {
                    out = format!("({out}).first()");
                } else {
                    out = format!("({out}).get({n})");
                }
            }
            (TailSeg::Index(n), "kotlin_android") => {
                if *n == 0 {
                    out = format!("({out}).first()");
                } else {
                    out = format!("({out})[{n}]");
                }
            }
            (TailSeg::Index(n), "elixir") => {
                out = format!("Enum.at({out}, {n})");
            }
            (TailSeg::Index(n), "zig") => {
                out = format!("({out}).items[{n}]");
            }
            (TailSeg::Index(n), "php") => {
                out = format!("({out})[{n}]");
            }
            (TailSeg::Index(n), _) => {
                // rust-like for go (but we handle Field differently), python, node, ts, kotlin, etc.
                out = format!("({out})[{n}]");
            }
            (TailSeg::Field(f), "rust") => {
                use heck::ToSnakeCase;
                out.push('.');
                out.push_str(&f.to_snake_case());
            }
            (TailSeg::Field(f), "go") => {
                use crate::codegen::naming::to_go_name;
                out.push('.');
                out.push_str(&to_go_name(f));
            }
            (TailSeg::Field(f), "java") => {
                out.push('.');
                out.push_str(&f.to_lower_camel_case());
                out.push_str("()");
            }
            (TailSeg::Field(f), "kotlin") => {
                // Use safe-call `?.` for all field accessors in Kotlin deep paths.
                // All streaming tool-call sub-fields (`function`, `id`, `name`,
                // `arguments`) are nullable in the generated Java records, so `?.`
                // is always correct here and prevents "non-null asserted call on
                // nullable receiver" compile errors.
                out.push_str("?.");
                out.push_str(&f.to_lower_camel_case());
                out.push_str("()");
            }
            (TailSeg::Field(f), "kotlin_android") => {
                // kotlin-android: Kotlin data classes use property access (no parens).
                out.push_str("?.");
                out.push_str(&f.to_lower_camel_case());
            }
            (TailSeg::Field(f), "csharp") => {
                out.push('.');
                out.push_str(&f.to_pascal_case());
            }
            (TailSeg::Field(f), "php") => {
                // Streaming PHP accessors operate on json_decoded stdClass with
                // snake_case property names (JSON wire format), not the camelCase
                // properties exposed on the PHP wrapper class. Use the raw field
                // name verbatim.
                out.push_str("->");
                out.push_str(f);
            }
            (TailSeg::Field(f), "elixir") => {
                out.push('.');
                out.push_str(f);
            }
            (TailSeg::Field(f), "zig") => {
                out.push('.');
                out.push_str(f);
            }
            (TailSeg::Field(f), "python") | (TailSeg::Field(f), "ruby") => {
                out.push('.');
                out.push_str(f);
            }
            // node, wasm, typescript, kotlin, dart, swift all use camelCase
            (TailSeg::Field(f), _) => {
                out.push('.');
                out.push_str(&f.to_lower_camel_case());
            }
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_streaming_virtual_field_recognizes_all_fields() {
        for field in STREAMING_VIRTUAL_FIELDS {
            assert!(
                is_streaming_virtual_field(field),
                "field '{field}' not recognized as streaming virtual"
            );
        }
    }

    #[test]
    fn is_streaming_virtual_field_rejects_real_fields() {
        assert!(!is_streaming_virtual_field("content"));
        assert!(!is_streaming_virtual_field("choices"));
        assert!(!is_streaming_virtual_field("model"));
        assert!(!is_streaming_virtual_field(""));
    }

    #[test]
    fn is_streaming_virtual_field_rejects_non_root_paths_with_matching_tail() {
        // Regression: prior impl matched any field whose chars-after-root-len started
        // with `[` or `.` — without checking that the field actually starts with the
        // root token. `choices[0].finish_reason` therefore falsely matched root
        // `tool_calls` because byte 10 onward is `.finish_reason`.
        assert!(!is_streaming_virtual_field("choices[0].finish_reason"));
        assert!(!is_streaming_virtual_field("choices[0].message.content"));
        assert!(!is_streaming_virtual_field("data[0].embedding"));
    }

    #[test]
    fn is_streaming_virtual_field_does_not_match_usage() {
        // `usage` is intentionally NOT a streaming-virtual root: chat/embed
        // responses carry `usage.total_tokens` at the response root, so treating
        // it as virtual would drag non-streaming tests into the chunks accessor.
        assert!(!is_streaming_virtual_field("usage"));
        assert!(!is_streaming_virtual_field("usage.total_tokens"));
        assert!(!is_streaming_virtual_field("usage.prompt_tokens"));
    }

    #[test]
    fn accessor_chunks_returns_var_name() {
        assert_eq!(
            StreamingFieldResolver::accessor("chunks", "rust", "chunks"),
            Some("chunks".to_string())
        );
        assert_eq!(
            StreamingFieldResolver::accessor("chunks", "node", "chunks"),
            Some("chunks".to_string())
        );
    }

    #[test]
    fn accessor_chunks_length_uses_language_idiom() {
        let rust = StreamingFieldResolver::accessor("chunks.length", "rust", "chunks").unwrap();
        assert!(rust.contains(".len()"), "rust: {rust}");

        let go = StreamingFieldResolver::accessor("chunks.length", "go", "chunks").unwrap();
        assert!(go.starts_with("len("), "go: {go}");

        let node = StreamingFieldResolver::accessor("chunks.length", "node", "chunks").unwrap();
        assert!(node.contains(".length"), "node: {node}");

        let php = StreamingFieldResolver::accessor("chunks.length", "php", "chunks").unwrap();
        assert!(php.starts_with("count("), "php: {php}");
    }

    #[test]
    fn accessor_chunks_length_zig_uses_items_len() {
        let zig = StreamingFieldResolver::accessor("chunks.length", "zig", "chunks").unwrap();
        assert_eq!(zig, "chunks.items.len", "zig chunks.length: {zig}");
    }

    #[test]
    fn accessor_stream_content_zig_uses_content_items() {
        let zig = StreamingFieldResolver::accessor("stream_content", "zig", "chunks").unwrap();
        assert_eq!(zig, "chunks_content.items", "zig stream_content: {zig}");
    }

    #[test]
    fn collect_snippet_zig_drains_via_ffi() {
        let snip = StreamingFieldResolver::collect_snippet("zig", "_stream_handle", "chunks").unwrap();
        assert!(snip.contains("std.ArrayList([]u8)"), "zig collect: {snip}");
        assert!(snip.contains("chat_stream_next(_stream_handle)"), "zig collect: {snip}");
        assert!(snip.contains("chunks_content"), "zig collect: {snip}");
        assert!(
            snip.contains("chunks.append(std.heap.c_allocator"),
            "zig collect: {snip}"
        );
        assert!(snip.contains(".empty;"), "zig collect (Zig 0.16 unmanaged): {snip}");
    }

    #[test]
    fn accessor_stream_content_rust_uses_iterator() {
        let expr = StreamingFieldResolver::accessor("stream_content", "rust", "chunks").unwrap();
        assert!(expr.contains(".collect::<String>()"), "rust stream_content: {expr}");
    }

    #[test]
    fn accessor_no_chunks_after_done_returns_true() {
        for lang in ["rust", "go", "java", "php", "node", "wasm", "elixir"] {
            let expr = StreamingFieldResolver::accessor("no_chunks_after_done", lang, "chunks").unwrap();
            assert_eq!(expr, "true", "lang {lang}: expected 'true', got '{expr}'");
        }
    }

    #[test]
    fn accessor_elixir_chunks_length_uses_length_function() {
        let expr = StreamingFieldResolver::accessor("chunks.length", "elixir", "chunks").unwrap();
        assert_eq!(expr, "length(chunks)", "elixir chunks.length: {expr}");
    }

    #[test]
    fn accessor_elixir_stream_content_uses_pipe() {
        let expr = StreamingFieldResolver::accessor("stream_content", "elixir", "chunks").unwrap();
        assert!(expr.contains("|> Enum.join"), "elixir stream_content: {expr}");
        assert!(expr.contains("|> Enum.map"), "elixir stream_content: {expr}");
        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
        assert!(
            !expr.contains("choices[0]"),
            "elixir stream_content must not use bracket access on list: {expr}"
        );
        assert!(
            expr.contains("Enum.at("),
            "elixir stream_content must use Enum.at for list index: {expr}"
        );
    }

    #[test]
    fn accessor_elixir_stream_complete_uses_list_last() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "elixir", "chunks").unwrap();
        assert!(expr.contains("List.last(chunks)"), "elixir stream_complete: {expr}");
        assert!(expr.contains("finish_reason != nil"), "elixir stream_complete: {expr}");
        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
        assert!(
            !expr.contains("choices[0]"),
            "elixir stream_complete must not use bracket access on list: {expr}"
        );
        assert!(
            expr.contains("Enum.at("),
            "elixir stream_complete must use Enum.at for list index: {expr}"
        );
    }

    #[test]
    fn accessor_elixir_finish_reason_uses_list_last() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "elixir", "chunks").unwrap();
        assert!(expr.contains("List.last(chunks)"), "elixir finish_reason: {expr}");
        assert!(expr.contains("finish_reason"), "elixir finish_reason: {expr}");
        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
        assert!(
            !expr.contains("choices[0]"),
            "elixir finish_reason must not use bracket access on list: {expr}"
        );
        assert!(
            expr.contains("Enum.at("),
            "elixir finish_reason must use Enum.at for list index: {expr}"
        );
    }

    #[test]
    fn collect_snippet_elixir_uses_enum_to_list() {
        let snip = StreamingFieldResolver::collect_snippet("elixir", "result", "chunks").unwrap();
        assert!(snip.contains("Enum.to_list(result)"), "elixir: {snip}");
        assert!(snip.contains("chunks ="), "elixir: {snip}");
    }

    #[test]
    fn collect_snippet_rust_uses_tokio_stream() {
        let snip = StreamingFieldResolver::collect_snippet("rust", "result", "chunks").unwrap();
        assert!(snip.contains("tokio_stream::StreamExt::collect"), "rust: {snip}");
        assert!(snip.contains("let chunks"), "rust: {snip}");
        // Items are Result<ChatCompletionChunk, _> — unwrap so chunks is Vec<ChatCompletionChunk>
        assert!(snip.contains(".expect("), "rust must unwrap Result items: {snip}");
    }

    #[test]
    fn collect_snippet_go_drains_channel() {
        let snip = StreamingFieldResolver::collect_snippet("go", "stream", "chunks").unwrap();
        assert!(snip.contains("for chunk := range stream"), "go: {snip}");
    }

    #[test]
    fn collect_snippet_java_uses_iterator() {
        let snip = StreamingFieldResolver::collect_snippet("java", "result", "chunks").unwrap();
        // Must call .iterator() on the Stream<T> before using hasNext()/next() —
        // Stream does not implement those methods directly.
        assert!(
            snip.contains(".iterator()"),
            "java snippet must call .iterator() on stream: {snip}"
        );
        assert!(snip.contains("hasNext()"), "java: {snip}");
        assert!(snip.contains(".next()"), "java: {snip}");
    }

    #[test]
    fn collect_snippet_php_decodes_json_or_iterates() {
        let snip = StreamingFieldResolver::collect_snippet("php", "result", "chunks").unwrap();
        // PHP binding's chat_stream_async returns a JSON string today; collect-snippet
        // decodes it.  iterator_to_array is retained as the fallback branch so a
        // future binding that exposes a real iterator continues to work without
        // regenerating the e2e tests.
        assert!(snip.contains("json_decode"), "php must decode JSON: {snip}");
        assert!(
            snip.contains("iterator_to_array"),
            "php must keep iterator_to_array fallback: {snip}"
        );
        assert!(snip.contains("$chunks ="), "php must bind $chunks: {snip}");
    }

    #[test]
    fn collect_snippet_node_uses_for_await() {
        let snip = StreamingFieldResolver::collect_snippet("node", "result", "chunks").unwrap();
        assert!(snip.contains("for await"), "node: {snip}");
    }

    #[test]
    fn collect_snippet_python_uses_async_for() {
        let snip = StreamingFieldResolver::collect_snippet("python", "result", "chunks").unwrap();
        assert!(snip.contains("async for chunk in result"), "python: {snip}");
        assert!(snip.contains("chunks.append(chunk)"), "python: {snip}");
    }

    #[test]
    fn accessor_stream_content_python_uses_join() {
        let expr = StreamingFieldResolver::accessor("stream_content", "python", "chunks").unwrap();
        assert!(expr.contains("\"\".join("), "python stream_content: {expr}");
        assert!(expr.contains("c.choices"), "python stream_content: {expr}");
    }

    #[test]
    fn accessor_stream_complete_python_uses_finish_reason() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "python", "chunks").unwrap();
        assert!(
            expr.contains("finish_reason is not None"),
            "python stream_complete: {expr}"
        );
    }

    #[test]
    fn accessor_finish_reason_python_uses_last_chunk() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "python", "chunks").unwrap();
        assert!(expr.contains("chunks[-1]"), "python finish_reason: {expr}");
        // Must wrap in str() so FinishReason enum objects support .strip() comparisons
        assert!(
            expr.starts_with("(str(") || expr.contains("str(chunks"),
            "python finish_reason must wrap in str(): {expr}"
        );
    }

    #[test]
    fn accessor_tool_calls_python_uses_list_comprehension() {
        let expr = StreamingFieldResolver::accessor("tool_calls", "python", "chunks").unwrap();
        assert!(expr.contains("for c in chunks"), "python tool_calls: {expr}");
        assert!(expr.contains("tool_calls"), "python tool_calls: {expr}");
    }

    #[test]
    fn accessor_usage_python_uses_last_chunk() {
        let expr = StreamingFieldResolver::accessor("usage", "python", "chunks").unwrap();
        assert!(
            expr.contains("chunks[-1].usage"),
            "python usage: expected chunks[-1].usage, got: {expr}"
        );
    }

    #[test]
    fn accessor_usage_total_tokens_does_not_route_via_chunks() {
        // `usage` is intentionally NOT a streaming-virtual root (it overlaps the
        // non-streaming response shape). The accessor must return None so the
        // assertion falls through to the normal field-path codegen.
        assert!(StreamingFieldResolver::accessor("usage.total_tokens", "python", "chunks").is_none());
    }

    #[test]
    fn accessor_unknown_field_returns_none() {
        assert_eq!(
            StreamingFieldResolver::accessor("nonexistent_field", "rust", "chunks"),
            None
        );
    }

    // -----------------------------------------------------------------------
    // Deep-path tests: tool_calls[0].function.name and tool_calls[0].id
    // -----------------------------------------------------------------------

    #[test]
    fn is_streaming_virtual_field_recognizes_deep_tool_calls_paths() {
        assert!(
            is_streaming_virtual_field("tool_calls[0].function.name"),
            "tool_calls[0].function.name should be recognized"
        );
        assert!(
            is_streaming_virtual_field("tool_calls[0].id"),
            "tool_calls[0].id should be recognized"
        );
        assert!(
            is_streaming_virtual_field("tool_calls[1].function.arguments"),
            "tool_calls[1].function.arguments should be recognized"
        );
        // bare root still recognized
        assert!(is_streaming_virtual_field("tool_calls"));
        // unrelated deep path must NOT be recognized
        assert!(!is_streaming_virtual_field("tool_calls_extra.name"));
        assert!(!is_streaming_virtual_field("nonexistent[0].field"));
    }

    /// Snapshot: `tool_calls[0].function.name` for Rust, Kotlin, TypeScript.
    ///
    /// These three languages cover the main accessor styles:
    /// - Rust: snake_case field, explicit `[0]` index on collected Vec
    /// - Kotlin: camelCase method calls with `.first()` for index 0
    /// - TypeScript/Node: camelCase properties with `[0]` bracket
    #[test]
    fn deep_tool_calls_function_name_snapshot_rust_kotlin_ts() {
        let field = "tool_calls[0].function.name";

        let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
        // Rust: Option-aware chain over the iterator — `.nth(0)` then `.and_then`
        // on each Option-wrapped field (function is Option<StreamFunctionCall>,
        // name is Option<String>). Final `.unwrap_or("")` yields `&str`.
        assert!(
            rust.contains(".nth(0)"),
            "rust deep tool_calls: expected .nth(0) iterator index, got: {rust}"
        );
        assert!(
            rust.contains("x.function.as_ref()"),
            "rust deep tool_calls: expected Option-aware function access, got: {rust}"
        );
        assert!(
            rust.contains("x.name.as_deref()"),
            "rust deep tool_calls: expected Option-aware name leaf, got: {rust}"
        );
        assert!(
            !rust.contains("// skipped"),
            "rust deep tool_calls: must not emit skip comment, got: {rust}"
        );

        let kotlin = StreamingFieldResolver::accessor(field, "kotlin", "chunks").unwrap();
        // Kotlin: uses .first() for index 0, then .function().name()
        assert!(
            kotlin.contains(".first()"),
            "kotlin deep tool_calls: expected .first() for index 0, got: {kotlin}"
        );
        assert!(
            kotlin.contains(".function()"),
            "kotlin deep tool_calls: expected .function() method call, got: {kotlin}"
        );
        assert!(
            kotlin.contains(".name()"),
            "kotlin deep tool_calls: expected .name() method call, got: {kotlin}"
        );

        let ts = StreamingFieldResolver::accessor(field, "node", "chunks").unwrap();
        // TypeScript/Node: uses [0] then .function.name (camelCase)
        assert!(
            ts.contains("[0]"),
            "ts/node deep tool_calls: expected [0] index, got: {ts}"
        );
        assert!(
            ts.contains(".function"),
            "ts/node deep tool_calls: expected .function segment, got: {ts}"
        );
        assert!(
            ts.contains(".name"),
            "ts/node deep tool_calls: expected .name segment, got: {ts}"
        );
    }

    #[test]
    fn deep_tool_calls_id_snapshot_all_langs() {
        let field = "tool_calls[0].id";

        let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
        assert!(rust.contains(".nth(0)"), "rust: {rust}");
        assert!(rust.contains("x.id.as_deref()"), "rust: {rust}");

        let go = StreamingFieldResolver::accessor(field, "go", "chunks").unwrap();
        assert!(go.contains("[0]"), "go: {go}");
        // Go: ID is a well-known initialism → uppercase
        assert!(go.contains(".ID"), "go: expected .ID initialism, got: {go}");

        let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
        assert!(python.contains("[0]"), "python: {python}");
        assert!(python.contains(".id"), "python: {python}");

        let php = StreamingFieldResolver::accessor(field, "php", "chunks").unwrap();
        assert!(php.contains("[0]"), "php: {php}");
        assert!(php.contains("->id"), "php: expected ->id, got: {php}");

        let java = StreamingFieldResolver::accessor(field, "java", "chunks").unwrap();
        assert!(java.contains(".get(0)"), "java: expected .get(0), got: {java}");
        assert!(java.contains(".id()"), "java: expected .id() method call, got: {java}");

        let csharp = StreamingFieldResolver::accessor(field, "csharp", "chunks").unwrap();
        assert!(csharp.contains("[0]"), "csharp: {csharp}");
        assert!(
            csharp.contains(".Id"),
            "csharp: expected .Id (PascalCase), got: {csharp}"
        );

        let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
        assert!(elixir.contains("Enum.at("), "elixir: expected Enum.at(, got: {elixir}");
        assert!(elixir.contains(".id"), "elixir: {elixir}");
    }

    #[test]
    fn deep_tool_calls_function_name_snapshot_python_elixir_zig() {
        let field = "tool_calls[0].function.name";

        let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
        assert!(python.contains("[0]"), "python: {python}");
        assert!(python.contains(".function"), "python: {python}");
        assert!(python.contains(".name"), "python: {python}");

        let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
        // Elixir: Enum.at(…, 0).function.name
        assert!(elixir.contains("Enum.at("), "elixir: {elixir}");
        assert!(elixir.contains(".function"), "elixir: {elixir}");
        assert!(elixir.contains(".name"), "elixir: {elixir}");

        // Zig stores chunks as JSON strings, not typed records — deep
        // tool_calls paths are unsupported and resolve to None so the
        // assertion site can skip them.
        assert!(
            StreamingFieldResolver::accessor(field, "zig", "chunks").is_none(),
            "zig: expected None for deep tool_calls path"
        );
    }

    #[test]
    fn parse_tail_parses_index_then_field_segments() {
        let segs = parse_tail("[0].function.name");
        assert_eq!(segs.len(), 3, "expected 3 segments, got: {segs:?}");
        assert_eq!(segs[0], TailSeg::Index(0));
        assert_eq!(segs[1], TailSeg::Field("function".to_string()));
        assert_eq!(segs[2], TailSeg::Field("name".to_string()));
    }

    #[test]
    fn parse_tail_parses_simple_index_field() {
        let segs = parse_tail("[0].id");
        assert_eq!(segs.len(), 2, "expected 2 segments, got: {segs:?}");
        assert_eq!(segs[0], TailSeg::Index(0));
        assert_eq!(segs[1], TailSeg::Field("id".to_string()));
    }

    #[test]
    fn parse_tail_handles_nonzero_index() {
        let segs = parse_tail("[2].function.arguments");
        assert_eq!(segs[0], TailSeg::Index(2));
        assert_eq!(segs[1], TailSeg::Field("function".to_string()));
        assert_eq!(segs[2], TailSeg::Field("arguments".to_string()));
    }

    // -----------------------------------------------------------------------
    // Swift-specific accessor tests
    // -----------------------------------------------------------------------

    #[test]
    fn accessor_chunks_length_swift_uses_count() {
        let swift = StreamingFieldResolver::accessor("chunks.length", "swift", "chunks").unwrap();
        assert_eq!(swift, "chunks.count", "swift chunks.length: {swift}");
    }

    #[test]
    fn accessor_stream_content_swift_uses_swift_closures() {
        let expr = StreamingFieldResolver::accessor("stream_content", "swift", "chunks").unwrap();
        // Must use Swift closure syntax (`{ ... }`) not JS arrow (`=>`)
        assert!(
            expr.contains("{ c in"),
            "swift stream_content must use Swift closure syntax, got: {expr}"
        );
        assert!(
            !expr.contains("=>"),
            "swift stream_content must not contain JS arrow `=>`, got: {expr}"
        );
        // Fields are accessed as first-class Codable struct properties (no parens).
        assert!(
            expr.contains("c.choices"),
            "swift stream_content must use property access for choices, got: {expr}"
        );
        assert!(
            expr.contains("ch.delta"),
            "swift stream_content must use property access for delta, got: {expr}"
        );
        assert!(
            expr.contains("ch.delta.content"),
            "swift stream_content must use property access for content, got: {expr}"
        );
        // First-class Codable struct fields are native Swift strings — no .toString() wrap.
        assert!(
            !expr.contains(".toString()"),
            "swift stream_content must NOT wrap first-class String fields with .toString(), got: {expr}"
        );
        assert!(
            expr.contains(".joined()"),
            "swift stream_content must join with .joined(), got: {expr}"
        );
        // Must not use JS .length or .join('')
        assert!(
            !expr.contains(".length"),
            "swift stream_content must not use JS .length, got: {expr}"
        );
        assert!(
            !expr.contains(".join("),
            "swift stream_content must not use JS .join(, got: {expr}"
        );
    }

    #[test]
    fn accessor_stream_complete_swift_uses_swift_syntax() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "swift", "chunks").unwrap();
        // Must use Swift isEmpty / last! syntax, not JS .length
        assert!(
            expr.contains("isEmpty"),
            "swift stream_complete must use .isEmpty, got: {expr}"
        );
        assert!(
            expr.contains(".last!"),
            "swift stream_complete must use .last!, got: {expr}"
        );
        // Property access for first-class fields (no parens, camelCase).
        assert!(
            expr.contains(".choices.first"),
            "swift stream_complete must use property access on choices, got: {expr}"
        );
        assert!(
            expr.contains("finishReason"),
            "swift stream_complete must reference lowerCamelCase finishReason, got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "swift stream_complete must not use JS .length, got: {expr}"
        );
        assert!(
            !expr.contains("!= null"),
            "swift stream_complete must not use JS `!= null`, got: {expr}"
        );
    }

    #[test]
    fn accessor_tool_calls_swift_uses_swift_flatmap() {
        let expr = StreamingFieldResolver::accessor("tool_calls", "swift", "chunks").unwrap();
        // Must use Swift closure syntax, not JS arrow
        assert!(
            !expr.contains("=>"),
            "swift tool_calls must not contain JS arrow `=>`, got: {expr}"
        );
        assert!(
            expr.contains("flatMap"),
            "swift tool_calls must use flatMap, got: {expr}"
        );
        // First-class struct property access (no parens, lowerCamelCase).
        assert!(
            expr.contains("c.choices.first"),
            "swift tool_calls must use property access on choices, got: {expr}"
        );
        assert!(
            expr.contains("ch.delta.toolCalls"),
            "swift tool_calls must use lowerCamelCase toolCalls property, got: {expr}"
        );
    }

    #[test]
    fn accessor_tool_calls_deep_path_swift_uses_method_calls_with_optional_chain() {
        // `tool_calls[0].function.name`: StreamToolCall is a first-class Codable
        // struct, so deep fields use lowerCamelCase property access. The first
        // field segment after `[N]` is non-optional (array index yields a value),
        // so `.function` uses plain `.`; subsequent segments chain with `?.`
        // because `function` itself is `Optional<StreamFunctionCall>`.
        let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "swift", "chunks").unwrap();
        assert!(
            expr.contains("[0].function"),
            "swift deep tool_calls must use plain `.function` directly after array index (non-optional), got: {expr}"
        );
        assert!(
            expr.contains("?.name"),
            "swift deep tool_calls must use ?.name property access, got: {expr}"
        );
        assert!(
            !expr.contains(".toString()"),
            "swift deep tool_calls must NOT wrap first-class String fields with .toString(), got: {expr}"
        );
        assert!(
            !expr.contains("=>"),
            "swift deep tool_calls must not use JS arrow syntax, got: {expr}"
        );
    }

    #[test]
    fn accessor_finish_reason_swift_uses_swift_syntax() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "swift", "chunks").unwrap();
        // Must use Swift isEmpty / last! syntax, not JS .length / undefined
        assert!(
            expr.contains("isEmpty"),
            "swift finish_reason must use .isEmpty, got: {expr}"
        );
        assert!(
            expr.contains(".last!"),
            "swift finish_reason must use .last!, got: {expr}"
        );
        assert!(
            expr.contains("finishReason"),
            "swift finish_reason must use lowerCamelCase finishReason property, got: {expr}"
        );
        // First-class Swift enum: use .rawValue for the serde wire string, not .toString().
        assert!(
            expr.contains(".rawValue"),
            "swift finish_reason must read enum .rawValue, got: {expr}"
        );
        assert!(
            !expr.contains("undefined"),
            "swift finish_reason must not use JS `undefined`, got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "swift finish_reason must not use JS .length, got: {expr}"
        );
    }

    #[test]
    fn accessor_usage_swift_uses_swift_syntax() {
        let expr = StreamingFieldResolver::accessor("usage", "swift", "chunks").unwrap();
        // Must use Swift isEmpty / last! syntax, not JS .length / undefined
        assert!(expr.contains("isEmpty"), "swift usage must use .isEmpty, got: {expr}");
        assert!(expr.contains(".last!"), "swift usage must use .last!, got: {expr}");
        // First-class Codable property access (no parens).
        assert!(
            expr.contains(".usage"),
            "swift usage must reference .usage property, got: {expr}"
        );
        assert!(
            !expr.contains("usage()"),
            "swift usage must NOT use method-call syntax, got: {expr}"
        );
        assert!(
            !expr.contains("undefined"),
            "swift usage must not use JS `undefined`, got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "swift usage must not use JS .length, got: {expr}"
        );
    }

    // ---------------------------------------------------------------------------
    // Bug regression: kotlin_android streaming assertions use property access
    // ---------------------------------------------------------------------------

    #[test]
    fn kotlin_android_collect_snippet_uses_flow_to_list() {
        let snip = StreamingFieldResolver::collect_snippet("kotlin_android", "result", "chunks").unwrap();
        // Flow.toList() — not Iterator.asSequence().toList()
        assert!(
            snip.contains("result.toList()"),
            "kotlin_android collect must use Flow.toList(), got: {snip}"
        );
        assert!(
            !snip.contains("asSequence()"),
            "kotlin_android collect must NOT use asSequence(), got: {snip}"
        );
    }

    #[test]
    fn kotlin_android_stream_content_uses_property_access() {
        let expr = StreamingFieldResolver::accessor("stream_content", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".choices"),
            "kotlin_android stream_content must use .choices property, got: {expr}"
        );
        assert!(
            !expr.contains(".choices()"),
            "kotlin_android stream_content must NOT use .choices() getter, got: {expr}"
        );
        assert!(
            expr.contains(".delta"),
            "kotlin_android stream_content must use .delta property, got: {expr}"
        );
        assert!(
            !expr.contains(".delta()"),
            "kotlin_android stream_content must NOT use .delta() getter, got: {expr}"
        );
        assert!(
            expr.contains(".content"),
            "kotlin_android stream_content must use .content property, got: {expr}"
        );
        assert!(
            !expr.contains(".content()"),
            "kotlin_android stream_content must NOT use .content() getter, got: {expr}"
        );
    }

    #[test]
    fn kotlin_android_finish_reason_uses_name_lowercase_not_get_value() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".finishReason"),
            "kotlin_android finish_reason must use .finishReason property, got: {expr}"
        );
        assert!(
            !expr.contains(".finishReason()"),
            "kotlin_android finish_reason must NOT use .finishReason() getter, got: {expr}"
        );
        assert!(
            expr.contains(".name"),
            "kotlin_android finish_reason must use .name for enum wire value, got: {expr}"
        );
        assert!(
            expr.contains(".lowercase()"),
            "kotlin_android finish_reason must use .lowercase(), got: {expr}"
        );
        assert!(
            !expr.contains(".getValue()"),
            "kotlin_android finish_reason must NOT use .getValue(), got: {expr}"
        );
    }

    #[test]
    fn kotlin_android_usage_uses_property_access() {
        let expr = StreamingFieldResolver::accessor("usage", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".usage"),
            "kotlin_android usage must use .usage property, got: {expr}"
        );
        assert!(
            !expr.contains(".usage()"),
            "kotlin_android usage must NOT use .usage() getter, got: {expr}"
        );
    }

    #[test]
    fn kotlin_android_deep_tool_calls_uses_property_access() {
        let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".function"),
            "kotlin_android deep tool_calls must use .function property, got: {expr}"
        );
        assert!(
            !expr.contains(".function()"),
            "kotlin_android deep tool_calls must NOT use .function() getter, got: {expr}"
        );
        assert!(
            expr.contains(".name"),
            "kotlin_android deep tool_calls must use .name property, got: {expr}"
        );
        assert!(
            !expr.contains(".name()"),
            "kotlin_android deep tool_calls must NOT use .name() getter, got: {expr}"
        );
    }

    // ---------------------------------------------------------------------------
    // Ruby-specific accessor tests
    // ---------------------------------------------------------------------------

    #[test]
    fn ruby_stream_content_uses_ruby_block_syntax() {
        let expr = StreamingFieldResolver::accessor("stream_content", "ruby", "chunks").unwrap();
        // Must use Ruby block syntax, not JS arrow function
        assert!(
            !expr.contains("=>"),
            "ruby stream_content must not contain JS arrow `=>`, got: {expr}"
        );
        assert!(
            expr.contains("{ |c|"),
            "ruby stream_content must use Ruby block `{{ |c|`, got: {expr}"
        );
        assert!(
            expr.contains(".join"),
            "ruby stream_content must use .join, got: {expr}"
        );
        assert!(
            expr.contains("c.choices"),
            "ruby stream_content must access .choices, got: {expr}"
        );
        assert!(
            expr.contains(".delta"),
            "ruby stream_content must access .delta, got: {expr}"
        );
        assert!(
            expr.contains(".content"),
            "ruby stream_content must access .content, got: {expr}"
        );
        // Must not use TypeScript optional-chaining syntax
        assert!(
            !expr.contains("?.["),
            "ruby stream_content must not use TS optional chaining `?.[`, got: {expr}"
        );
    }

    #[test]
    fn ruby_stream_complete_uses_ruby_nil_predicate() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "ruby", "chunks").unwrap();
        // Must use Ruby nil? not JS != null
        assert!(
            !expr.contains("!= null"),
            "ruby stream_complete must not use JS `!= null`, got: {expr}"
        );
        assert!(
            expr.contains(".nil?"),
            "ruby stream_complete must use .nil?, got: {expr}"
        );
        assert!(
            expr.contains(".empty?"),
            "ruby stream_complete must use .empty?, got: {expr}"
        );
        assert!(
            expr.contains("finish_reason"),
            "ruby stream_complete must reference finish_reason, got: {expr}"
        );
        // Must not use TypeScript optional-chaining syntax
        assert!(
            !expr.contains("?.["),
            "ruby stream_complete must not use TS optional chaining `?.[`, got: {expr}"
        );
    }

    #[test]
    fn ruby_tool_calls_uses_ruby_flat_map_block() {
        let expr = StreamingFieldResolver::accessor("tool_calls", "ruby", "chunks").unwrap();
        // Must use Ruby flat_map with block syntax, not JS flatMap with arrow
        assert!(
            !expr.contains("=>"),
            "ruby tool_calls must not contain JS arrow `=>`, got: {expr}"
        );
        assert!(
            expr.contains("flat_map"),
            "ruby tool_calls must use flat_map, got: {expr}"
        );
        assert!(
            expr.contains("{ |c|"),
            "ruby tool_calls must use Ruby block `{{ |c|`, got: {expr}"
        );
        assert!(
            expr.contains("tool_calls"),
            "ruby tool_calls must reference tool_calls, got: {expr}"
        );
        // Must not use TypeScript optional-chaining syntax
        assert!(
            !expr.contains("?.["),
            "ruby tool_calls must not use TS optional chaining `?.[`, got: {expr}"
        );
    }

    #[test]
    fn ruby_finish_reason_uses_to_s_not_get_value() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "ruby", "chunks").unwrap();
        // Must use Ruby .to_s, not JS undefined or TS syntax
        assert!(
            !expr.contains("undefined"),
            "ruby finish_reason must not use JS `undefined`, got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "ruby finish_reason must not use JS .length, got: {expr}"
        );
        assert!(
            expr.contains(".empty?"),
            "ruby finish_reason must use .empty?, got: {expr}"
        );
        assert!(
            expr.contains("finish_reason"),
            "ruby finish_reason must reference finish_reason, got: {expr}"
        );
        assert!(
            expr.contains(".to_s"),
            "ruby finish_reason must call .to_s on the enum, got: {expr}"
        );
    }
}
