///|
/// Outcome of inspecting/rewriting a `POST /v1/chat/completions` body.
pub(all) enum AssistOutcome {
  PassThrough
  Rewritten(body~ : Bytes, images~ : Int32, reused~ : Int32)
  Failed(@cache.VisionFailure)
}

///|
/// Precomputed byte templates for the configured entry/vision models and prompt.
pub struct VisionSpec {
  entry_model : String
  entry_model_lower : Bytes
  entry_model_quoted : Bytes
  vision_model : String
  vision_max_tokens : Int32
  vision_prompt : String
  vision_prompt_utf8 : Bytes
  vision_req_prefix : Bytes
  vision_req_suffix : Bytes
}

///|
let cached_spec : Ref[VisionSpec?] = Ref(None)

///|
fn ascii_lower_bytes(s : String) -> Bytes {
  let raw = @utf8.encode(s)
  let len = raw.length()
  let out = FixedArray::make(len, b'\x00')
  for i = 0; i < len; i = i + 1 {
    let c = raw[i]
    out[i] = if c >= b'A' && c <= b'Z' {
      (c.to_int() + 32).to_byte()
    } else {
      c
    }
  }
  out.unsafe_reinterpret_as_bytes()
}

///|
pub fn get_vision_spec(cfg : @config.Config) -> VisionSpec {
  match cached_spec.val {
    Some(s) if s.entry_model == cfg.entry_model &&
      s.vision_model == cfg.vision_model &&
      s.vision_max_tokens == cfg.vision_max_tokens &&
      s.vision_prompt == cfg.vision_prompt => s
    _ => {
      let entry_quoted = Json::string(cfg.entry_model).stringify(
        escape_slash=false,
      )
      let vision_quoted = Json::string(cfg.vision_model).stringify(
        escape_slash=false,
      )
      let prompt_quoted = Json::string(cfg.vision_prompt).stringify(
        escape_slash=false,
      )
      let prefix_str = "{\"model\":" +
        vision_quoted +
        ",\"stream\":false,\"max_tokens\":" +
        cfg.vision_max_tokens.to_string() +
        ",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":" +
        prompt_quoted +
        "},"
      let spec : VisionSpec = {
        entry_model: cfg.entry_model,
        entry_model_lower: ascii_lower_bytes(cfg.entry_model),
        entry_model_quoted: @utf8.encode(entry_quoted),
        vision_model: cfg.vision_model,
        vision_max_tokens: cfg.vision_max_tokens,
        vision_prompt: cfg.vision_prompt,
        vision_prompt_utf8: @utf8.encode(cfg.vision_prompt),
        vision_req_prefix: @utf8.encode(prefix_str),
        vision_req_suffix: b"]}]}",
      }
      cached_spec.val = Some(spec)
      spec
    }
  }
}

///|
/// Build a 502 `VisionFailure` matching `bad_caption` in `proxy.py`.
pub fn bad_caption_failure(message : String) -> @cache.VisionFailure {
  let err_json : Json = {
    "error": { "type": "vision_error", "message": Json::string(message) },
  }
  {
    status: 502,
    body: @utf8.encode(err_json.stringify(escape_slash=false)),
    headers: [("Content-Type", "application/json")],
  }
}

///|
/// Parse the vision upstream JSON response and extract a non-empty, non-`SKIP`
/// caption string (supporting both plain string and array-of-text content).
pub fn extract_caption_from_vision_response(
  raw : Bytes,
) -> Result[String, @cache.VisionFailure] {
  let text = @utf8.decode(raw) catch {
    _ =>
      return Err(
        bad_caption_failure(
          "The vision model returned no usable image description.",
        ),
      )
  }
  let doc = @json.parse(text) catch {
    _ =>
      return Err(
        bad_caption_failure(
          "The vision model returned no usable image description.",
        ),
      )
  }
  let extracted : String? = match doc {
    Object(root) =>
      match root.get("choices") {
        Some(Array(choices)) if choices.length() > 0 =>
          match choices[0] {
            Object(c0) =>
              match c0.get("message") {
                Some(Object(msg)) =>
                  match msg.get("content") {
                    Some(String(s)) => Some(s)
                    Some(Array(parts)) => {
                      let sb = StringBuilder()
                      let mut ok = true
                      for p in parts {
                        match p {
                          Object(po) =>
                            match po.get("type") {
                              Some(String("text")) =>
                                match po.get("text") {
                                  Some(String(t)) => sb.write_string(t)
                                  _ => {
                                    ok = false
                                    break
                                  }
                                }
                              _ => ()
                            }
                          _ => {
                            ok = false
                            break
                          }
                        }
                      }
                      if ok {
                        Some(sb.to_string())
                      } else {
                        None
                      }
                    }
                    _ => None
                  }
                _ => None
              }
            _ => None
          }
        _ => None
      }
    _ => None
  }
  match extracted {
    Some(raw_cap) => {
      let trimmed = raw_cap.clamped_view().trim()
      if trimmed.is_empty() || trimmed.equal_ignore_ascii_case("SKIP") {
        Err(
          bad_caption_failure(
            "The vision model returned no usable image description.",
          ),
        )
      } else {
        Ok(trimmed.to_owned())
      }
    }
    None =>
      Err(
        bad_caption_failure(
          "The vision model returned no usable image description.",
        ),
      )
  }
}

///|
priv struct FastImageSpan {
  part_s : Int32
  part_e : Int32
  kind_s : Int32
  kind_e : Int32
  url_s : Int32
  url_e : Int32
  is_data_url : Bool
}

///|
priv enum FastContentPart {
  TextInner(Int32, Int32)
  Image(FastImageSpan)
}

///|
priv struct FastUserMsg {
  arr_s : Int32
  arr_e : Int32
  parts : Array[FastContentPart]
}

///|
priv enum ScanResult {
  Skip
  UseFast(
    model_s~ : Int32,
    model_e~ : Int32,
    rewrite_model~ : Bool,
    msgs~ : Array[FastUserMsg],
  )
  UseFallback
}

///|
fn skip_ws(b : Bytes, pos : Int32, len : Int32) -> Int32 {
  let mut i = pos
  while i < len {
    let c = b[i]
    if c == b' ' || c == b'\t' || c == b'\r' || c == b'\n' {
      i += 1
    } else {
      break
    }
  }
  i
}

///|
fn eq_unquoted_ascii(b : Bytes, qs : Int32, qe : Int32, target : Bytes) -> Bool {
  let tlen = target.length()
  if qe - qs - 2 != tlen {
    return false
  }
  for i = 0; i < tlen; i = i + 1 {
    if b[qs + 1 + i] != target[i] {
      return false
    }
  }
  true
}

///|
fn eq_unquoted_ascii_icase(
  b : Bytes,
  qs : Int32,
  qe : Int32,
  target_lower : Bytes,
) -> Bool {
  let tlen = target_lower.length()
  if qe - qs - 2 != tlen {
    return false
  }
  for i = 0; i < tlen; i = i + 1 {
    let c = b[qs + 1 + i]
    let lc = if c >= b'A' && c <= b'Z' {
      (c.to_int() + 32).to_byte()
    } else {
      c
    }
    if lc != target_lower[i] {
      return false
    }
  }
  true
}

///|
fn eq_slice_exact(b : Bytes, s : Int32, e : Int32, target : Bytes) -> Bool {
  let tlen = target.length()
  if e - s != tlen {
    return false
  }
  for i = 0; i < tlen; i = i + 1 {
    if b[s + i] != target[i] {
      return false
    }
  }
  true
}

///|
fn is_quoted_data_url(b : Bytes, qs : Int32, qe : Int32) -> Bool {
  qe - qs >= 7 &&
  b[qs + 1] == b'd' &&
  b[qs + 2] == b'a' &&
  b[qs + 3] == b't' &&
  b[qs + 4] == b'a' &&
  b[qs + 5] == b':'
}

///|
fn skip_json_value(
  b : Bytes,
  pos : Int32,
  len : Int32,
  max_depth : Int32,
) -> Int32? {
  let i = skip_ws(b, pos, len)
  if i >= len {
    return None
  }
  let c = b[i]
  if c == b'"' {
    return @sha256.scan_json_string_fast(b, i, len)
  }
  if c == b'{' || c == b'[' {
    let mut depth = 1
    let mut p = i + 1
    while p < len && depth > 0 {
      if depth > max_depth {
        return None
      }
      let ch = b[p]
      if ch == b'"' {
        match @sha256.scan_json_string_fast(b, p, len) {
          Some(next_p) => p = next_p
          None => return None
        }
      } else {
        if ch == b'{' || ch == b'[' {
          depth += 1
        } else if ch == b'}' || ch == b']' {
          depth -= 1
        }
        p += 1
      }
    }
    return if depth == 0 { Some(p) } else { None }
  }
  // Primitive literal (number, true, false, null): validate non-empty token.
  let mut p = i
  while p < len {
    let ch = b[p]
    if ch == b',' ||
      ch == b'}' ||
      ch == b']' ||
      ch == b' ' ||
      ch == b'\t' ||
      ch == b'\r' ||
      ch == b'\n' {
      break
    }
    p += 1
  }
  if p == i {
    None
  } else {
    Some(p)
  }
}

///|
/// Inspect a single element inside `user.content` array `[ ... ]`.
/// Returns `Some((end_pos, part))` for standard `text` or `{type, image_url:{url}}`
/// objects, or `None` to trigger safe DOM fallback.
fn inspect_content_part(
  b : Bytes,
  pos : Int32,
  len : Int32,
) -> (Int32, FastContentPart)? {
  if pos >= len || b[pos] != b'{' {
    return None
  }
  let mut i = skip_ws(b, pos + 1, len)
  if i >= len || b[i] == b'}' {
    return None
  }
  let mut kind_s = -1
  let mut kind_e = -1
  let mut is_text = false
  let mut is_img = false
  let mut text_s = -1
  let mut text_e = -1
  let mut url_s = -1
  let mut url_e = -1
  let mut field_count = 0
  for ;; {
    let ks = i
    let ke = match @sha256.scan_json_string_fast(b, ks, len) {
      Some(e) => e
      None => return None
    }
    if @sha256.has_backslash_fast(b, ks + 1, ke - 1) {
      return None
    }
    i = skip_ws(b, ke, len)
    if i >= len || b[i] != b':' {
      return None
    }
    let vs = skip_ws(b, i + 1, len)
    if vs >= len {
      return None
    }
    field_count += 1
    if eq_unquoted_ascii(b, ks, ke, b"type") {
      if b[vs] != b'"' {
        return None
      }
      let ve = match @sha256.scan_json_string_fast(b, vs, len) {
        Some(e) => e
        None => return None
      }
      if @sha256.has_backslash_fast(b, vs + 1, ve - 1) {
        return None
      }
      kind_s = vs
      kind_e = ve
      if eq_unquoted_ascii(b, vs, ve, b"text") {
        is_text = true
      } else if eq_unquoted_ascii(b, vs, ve, b"image_url") ||
        eq_unquoted_ascii(b, vs, ve, b"image") {
        is_img = true
      } else {
        return None
      }
      i = skip_ws(b, ve, len)
    } else if eq_unquoted_ascii(b, ks, ke, b"text") {
      if b[vs] != b'"' {
        return None
      }
      let ve = match @sha256.scan_json_string_fast(b, vs, len) {
        Some(e) => e
        None => return None
      }
      text_s = vs
      text_e = ve
      i = skip_ws(b, ve, len)
    } else if eq_unquoted_ascii(b, ks, ke, b"image_url") {
      // Fast path handles standard `{"url": "..."}` with no extra keys/escapes;
      // bare-string `image_url`, `detail`, or escaped URLs fall back to DOM.
      if b[vs] != b'{' {
        return None
      }
      let uks = skip_ws(b, vs + 1, len)
      let uke = match @sha256.scan_json_string_fast(b, uks, len) {
        Some(e) => e
        None => return None
      }
      if @sha256.has_backslash_fast(b, uks + 1, uke - 1) ||
        !eq_unquoted_ascii(b, uks, uke, b"url") {
        return None
      }
      let ucolon = skip_ws(b, uke, len)
      if ucolon >= len || b[ucolon] != b':' {
        return None
      }
      let uvs = skip_ws(b, ucolon + 1, len)
      if uvs >= len || b[uvs] != b'"' {
        return None
      }
      let uve = match @sha256.scan_json_string_fast(b, uvs, len) {
        Some(e) => e
        None => return None
      }
      if @sha256.has_backslash_fast(b, uvs + 1, uve - 1) {
        return None
      }
      let uclose = skip_ws(b, uve, len)
      if uclose >= len || b[uclose] != b'}' {
        return None
      }
      url_s = uvs
      url_e = uve
      i = skip_ws(b, uclose + 1, len)
    } else {
      return None
    }
    if i >= len {
      return None
    }
    if b[i] == b',' {
      i = skip_ws(b, i + 1, len)
    } else if b[i] == b'}' {
      let part_e = i + 1
      if field_count != 2 || kind_s < 0 {
        return None
      }
      if is_text && text_s >= 0 {
        return Some((part_e, TextInner(text_s + 1, text_e - 1)))
      }
      if is_img && url_s >= 0 {
        let img : FastImageSpan = {
          part_s: pos,
          part_e,
          kind_s,
          kind_e,
          url_s,
          url_e,
          is_data_url: is_quoted_data_url(b, url_s, url_e),
        }
        return Some((part_e, Image(img)))
      }
      return None
    } else {
      return None
    }
  }
  None
}

///|
/// Inspect one message object inside `messages: [...]`.
/// Returns `Some((end_pos, Some(user_msg_with_images) | None))`, or `None` to trigger fallback.
fn inspect_message_object(
  b : Bytes,
  pos : Int32,
  len : Int32,
) -> (Int32, FastUserMsg?)? {
  if pos >= len || b[pos] != b'{' {
    return None
  }
  let mut i = skip_ws(b, pos + 1, len)
  if i >= len {
    return None
  }
  if b[i] == b'}' {
    return Some((i + 1, None))
  }
  let mut is_user = false
  let mut seen_role = false
  let mut arr_s = -1
  let mut arr_e = -1
  let mut has_image = false
  let mut content_parts : Array[FastContentPart]? = None
  let mut needs_fallback_if_user = false
  for ;; {
    let ks = i
    let ke = match @sha256.scan_json_string_fast(b, ks, len) {
      Some(e) => e
      None => return None
    }
    if @sha256.has_backslash_fast(b, ks + 1, ke - 1) {
      return None
    }
    i = skip_ws(b, ke, len)
    if i >= len || b[i] != b':' {
      return None
    }
    let vs = skip_ws(b, i + 1, len)
    if vs >= len {
      return None
    }
    if eq_unquoted_ascii(b, ks, ke, b"role") {
      if seen_role || b[vs] != b'"' {
        return None
      }
      seen_role = true
      let ve = match @sha256.scan_json_string_fast(b, vs, len) {
        Some(e) => e
        None => return None
      }
      if @sha256.has_backslash_fast(b, vs + 1, ve - 1) {
        return None
      }
      is_user = eq_unquoted_ascii(b, vs, ve, b"user")
      i = skip_ws(b, ve, len)
    } else if eq_unquoted_ascii(b, ks, ke, b"content") {
      if content_parts is Some(_) || arr_s >= 0 {
        // Duplicate content key -> let DOM fallback decide.
        return None
      }
      if b[vs] == b'"' {
        let ve = match @sha256.scan_json_string_fast(b, vs, len) {
          Some(e) => e
          None => return None
        }
        i = skip_ws(b, ve, len)
      } else if b[vs] == b'[' {
        if seen_role && !is_user {
          // Non-user message array content is never rewritten by `proxy.py`.
          let ve = match skip_json_value(b, vs, len, 64) {
            Some(e) => e
            None => return None
          }
          i = skip_ws(b, ve, len)
        } else {
          arr_s = vs
          let mut p = skip_ws(b, vs + 1, len)
          if p >= len {
            return None
          }
          let parts : Array[FastContentPart] = []
          if b[p] == b']' {
            arr_e = p + 1
            content_parts = Some(parts)
            i = skip_ws(b, arr_e, len)
          } else {
            for ;; {
              match inspect_content_part(b, p, len) {
                Some((pe, part)) => {
                  if part is Image(_) {
                    has_image = true
                  }
                  parts.push(part)
                  p = skip_ws(b, pe, len)
                }
                None => {
                  // Unrecognized part shape: skip array for now; if this turns
                  // out to be a `user` message, trigger DOM fallback.
                  needs_fallback_if_user = true
                  match skip_json_value(b, vs, len, 64) {
                    Some(ve) => {
                      arr_e = ve
                      i = skip_ws(b, ve, len)
                      break
                    }
                    None => return None
                  }
                }
              }
              if p >= len {
                return None
              }
              if b[p] == b',' {
                p = skip_ws(b, p + 1, len)
              } else if b[p] == b']' {
                arr_e = p + 1
                content_parts = Some(parts)
                i = skip_ws(b, arr_e, len)
                break
              } else {
                return None
              }
            }
          }
        }
      } else {
        let ve = match skip_json_value(b, vs, len, 64) {
          Some(e) => e
          None => return None
        }
        i = skip_ws(b, ve, len)
      }
    } else {
      let ve = match skip_json_value(b, vs, len, 64) {
        Some(e) => e
        None => return None
      }
      i = skip_ws(b, ve, len)
    }
    if i >= len {
      return None
    }
    if b[i] == b',' {
      i = skip_ws(b, i + 1, len)
    } else if b[i] == b'}' {
      let end_pos = i + 1
      if is_user && needs_fallback_if_user {
        return None
      }
      if is_user && has_image {
        match content_parts {
          Some(parts) => return Some((end_pos, Some({ arr_s, arr_e, parts, })))
          None => return None
        }
      }
      return Some((end_pos, None))
    } else {
      return None
    }
  }
  None
}

///|
/// Single-pass zero-DOM byte scanner over a Chat Completions JSON body.
fn scan_chat_body(body : Bytes, spec : VisionSpec) -> ScanResult {
  let len = body.length()
  let mut i = skip_ws(body, 0, len)
  if i >= len || body[i] != b'{' {
    return UseFallback
  }
  i = skip_ws(body, i + 1, len)
  if i >= len {
    return UseFallback
  }
  if body[i] == b'}' {
    let tail = skip_ws(body, i + 1, len)
    return if tail == len { Skip } else { UseFallback }
  }
  let mut seen_model = false
  let mut seen_messages = false
  let mut model_s = -1
  let mut model_e = -1
  let mut rewrite_model = false
  let user_msgs : Array[FastUserMsg] = []
  for ;; {
    let ks = i
    let ke = match @sha256.scan_json_string_fast(body, ks, len) {
      Some(e) => e
      None => return UseFallback
    }
    if @sha256.has_backslash_fast(body, ks + 1, ke - 1) {
      return UseFallback
    }
    i = skip_ws(body, ke, len)
    if i >= len || body[i] != b':' {
      return UseFallback
    }
    let vs = skip_ws(body, i + 1, len)
    if vs >= len {
      return UseFallback
    }
    if eq_unquoted_ascii(body, ks, ke, b"model") {
      if seen_model {
        return UseFallback
      }
      seen_model = true
      if body[vs] != b'"' {
        let ve = match skip_json_value(body, vs, len, 64) {
          Some(e) => e
          None => return UseFallback
        }
        // Non-string model -> never matches `ENTRY_MODEL`. If rest of JSON is
        // valid or invalid, `proxy.py` forwards unchanged either way!
        let _ = ve
        return Skip
      }
      let ve = match @sha256.scan_json_string_fast(body, vs, len) {
        Some(e) => e
        None => return UseFallback
      }
      if @sha256.has_backslash_fast(body, vs + 1, ve - 1) {
        return UseFallback
      }
      if !eq_unquoted_ascii_icase(body, vs, ve, spec.entry_model_lower) {
        // Fast exit: model is NOT `entry_model`, forward raw bytes unchanged!
        return Skip
      }
      model_s = vs
      model_e = ve
      rewrite_model = !eq_slice_exact(body, vs, ve, spec.entry_model_quoted)
      i = skip_ws(body, ve, len)
    } else if eq_unquoted_ascii(body, ks, ke, b"messages") {
      if seen_messages {
        return UseFallback
      }
      seen_messages = true
      if body[vs] != b'[' {
        let ve = match skip_json_value(body, vs, len, 64) {
          Some(e) => e
          None => return UseFallback
        }
        i = skip_ws(body, ve, len)
      } else {
        let mut p = skip_ws(body, vs + 1, len)
        if p >= len {
          return UseFallback
        }
        if body[p] == b']' {
          i = skip_ws(body, p + 1, len)
        } else {
          for ;; {
            match inspect_message_object(body, p, len) {
              Some((me, maybe_umsg)) => {
                match maybe_umsg {
                  Some(umsg) => user_msgs.push(umsg)
                  None => ()
                }
                p = skip_ws(body, me, len)
              }
              None => return UseFallback
            }
            if p >= len {
              return UseFallback
            }
            if body[p] == b',' {
              p = skip_ws(body, p + 1, len)
            } else if body[p] == b']' {
              i = skip_ws(body, p + 1, len)
              break
            } else {
              return UseFallback
            }
          }
        }
      }
    } else {
      let ve = match skip_json_value(body, vs, len, 64) {
        Some(e) => e
        None => return UseFallback
      }
      i = skip_ws(body, ve, len)
    }
    if i >= len {
      return UseFallback
    }
    if body[i] == b',' {
      i = skip_ws(body, i + 1, len)
    } else if body[i] == b'}' {
      let tail = skip_ws(body, i + 1, len)
      if tail != len {
        return UseFallback
      }
      break
    } else {
      return UseFallback
    }
  }
  if !seen_model || user_msgs.is_empty() {
    Skip
  } else {
    UseFast(model_s~, model_e~, rewrite_model~, msgs=user_msgs)
  }
}

///|
fn assemble_vision_req_slice(
  spec : VisionSpec,
  body : Bytes,
  part_s : Int32,
  part_e : Int32,
) -> Bytes {
  let plen = part_e - part_s
  let vp = spec.vision_req_prefix
  let vs = spec.vision_req_suffix
  let vp_len = vp.length()
  let vs_len = vs.length()
  let out = FixedArray::make(vp_len + plen + vs_len, b'\x00')
  out.blit_from_bytes(0, vp, 0, vp_len)
  out.blit_from_bytes(vp_len, body, part_s, plen)
  out.blit_from_bytes(vp_len + plen, vs, 0, vs_len)
  out.unsafe_reinterpret_as_bytes()
}

///|
async fn describe_image_with_cache(
  cache_key : String?,
  build_vision_req : () -> Bytes,
  store : @cache.CaptionStore,
  fetch_vision : async (Bytes) -> Result[Bytes, @cache.VisionFailure],
) -> Result[(String, Bool), @cache.VisionFailure] {
  match cache_key {
    None => {
      let req_bytes = build_vision_req()
      match fetch_vision(req_bytes) {
        Ok(raw_resp) =>
          match extract_caption_from_vision_response(raw_resp) {
            Ok(cap) => Ok((cap, false))
            Err(vf) => Err(vf)
          }
        Err(vf) => Err(vf)
      }
    }
    Some(key) =>
      match store.begin_lookup(key) {
        Hit(cap) => Ok((cap, true))
        Wait(slot) =>
          match slot.wait() {
            Ok(cap) => Ok((cap, true))
            Err(vf) => Err(vf)
          }
        Owner(slot) => {
          let req_bytes = build_vision_req()
          let res : Result[String, @cache.VisionFailure] = match
            fetch_vision(req_bytes) {
            Ok(raw_resp) => extract_caption_from_vision_response(raw_resp)
            Err(vf) => Err(vf)
          }
          store.finish_lookup(key, slot, res)
          match res {
            Ok(cap) => Ok((cap, false))
            Err(vf) => Err(vf)
          }
        }
      }
  }
}

///|
/// Encode `"【附图的视觉观察】\n" + caption` as JSON-escaped inner bytes (without outer quotes).
fn encode_caption_json_inner(caption : String) -> Bytes {
  let full = "【附图的视觉观察】\n" + caption
  let quoted = Json::string(full).stringify(escape_slash=false)
  @utf8.encode(quoted.clamped_view(start=1, end=quoted.length() - 1))
}

///|
/// Splice replacement spans `(start, end, replacement_bytes)` sorted by `start`
/// into a single freshly allocated `Bytes` buffer.
fn splice_replacements(
  body : Bytes,
  reps : Array[(Int32, Int32, Bytes)],
) -> Bytes {
  reps.sort_by((a, b) => a.0 - b.0)
  let len = body.length()
  let mut delta = 0
  for r in reps {
    delta += r.2.length() - (r.1 - r.0)
  }
  let out = FixedArray::make(len + delta, b'\x00')
  let mut src_pos = 0
  let mut dst_pos = 0
  for r in reps {
    let chunk_len = r.0 - src_pos
    if chunk_len > 0 {
      out.blit_from_bytes(dst_pos, body, src_pos, chunk_len)
      dst_pos += chunk_len
    }
    let rlen = r.2.length()
    if rlen > 0 {
      out.blit_from_bytes(dst_pos, r.2, 0, rlen)
      dst_pos += rlen
    }
    src_pos = r.1
  }
  let tail_len = len - src_pos
  if tail_len > 0 {
    out.blit_from_bytes(dst_pos, body, src_pos, tail_len)
  }
  out.unsafe_reinterpret_as_bytes()
}

///|
/// Serialize a `Json` value in Python `json.dumps(..., sort_keys=True)` canonical
/// ASCII format (`", "` / `": "` separators, `\uXXXX` for non-ASCII) so fallback
/// cache keys match `proxy.py` and the fast-path byte hash 100%.
pub fn canonical_python_json_bytes(v : Json) -> Bytes {
  let buf = @buffer.Buffer(capacity=256)
  write_canonical_python_json(buf, v)
  buf.to_bytes()
}

///|
fn write_hex4_lower(buf : @buffer.Buffer, code : Int32) -> Unit {
  let hex = b"0123456789abcdef"
  buf.write_byte(hex[(code >> 12) & 0xf])
  buf.write_byte(hex[(code >> 8) & 0xf])
  buf.write_byte(hex[(code >> 4) & 0xf])
  buf.write_byte(hex[code & 0xf])
}

///|
fn write_canonical_python_string(buf : @buffer.Buffer, s : String) -> Unit {
  buf.write_byte(b'"')
  let len = s.length()
  let mut i = 0
  while i < len {
    let cu = s.code_unit_at(i).to_int()
    match cu {
      0x22 => buf.write_bytesview(b"\\\"")
      0x5c => buf.write_bytesview(b"\\\\")
      0x08 => buf.write_bytesview(b"\\b")
      0x0c => buf.write_bytesview(b"\\f")
      0x0a => buf.write_bytesview(b"\\n")
      0x0d => buf.write_bytesview(b"\\r")
      0x09 => buf.write_bytesview(b"\\t")
      _ =>
        if cu >= 0x20 && cu <= 0x7e {
          buf.write_byte(cu.to_byte())
        } else {
          buf.write_bytesview(b"\\u")
          write_hex4_lower(buf, cu)
        }
    }
    i += 1
  }
  buf.write_byte(b'"')
}

///|
fn lexical_compare_str(a : String, b : String) -> Int32 {
  let alen = a.length()
  let blen = b.length()
  let min_len = if alen < blen { alen } else { blen }
  let mut i = 0
  while i < min_len {
    let ca = a.code_unit_at(i).to_int()
    let cb = b.code_unit_at(i).to_int()
    if ca != cb {
      return ca - cb
    }
    i += 1
  }
  alen - blen
}

///|
fn write_canonical_python_json(buf : @buffer.Buffer, v : Json) -> Unit {
  match v {
    Null => buf.write_bytesview(b"null")
    True => buf.write_bytesview(b"true")
    False => buf.write_bytesview(b"false")
    Number(_, repr~) =>
      match repr {
        Some(r) => buf.write_string_utf8(r)
        None => buf.write_string_utf8(v.stringify())
      }
    String(s) => write_canonical_python_string(buf, s)
    Array(arr) => {
      buf.write_byte(b'[')
      for idx = 0; idx < arr.length(); idx = idx + 1 {
        if idx > 0 {
          buf.write_bytesview(b", ")
        }
        write_canonical_python_json(buf, arr[idx])
      }
      buf.write_byte(b']')
    }
    Object(map) => {
      buf.write_byte(b'{')
      let keys : Array[String] = Array(capacity=map.length())
      for k, _ in map {
        keys.push(k)
      }
      keys.sort_by(lexical_compare_str)
      for idx = 0; idx < keys.length(); idx = idx + 1 {
        if idx > 0 {
          buf.write_bytesview(b", ")
        }
        let k = keys[idx]
        write_canonical_python_string(buf, k)
        buf.write_bytesview(b": ")
        match map.get(k) {
          Some(val) => write_canonical_python_json(buf, val)
          None => buf.write_bytesview(b"null")
        }
      }
      buf.write_byte(b'}')
    }
  }
}

///|
async fn rewrite_dom_fallback(
  body : Bytes,
  spec : VisionSpec,
  auth_bytes : Bytes?,
  store : @cache.CaptionStore,
  fetch_vision : async (Bytes) -> Result[Bytes, @cache.VisionFailure],
) -> AssistOutcome {
  let decoded = @utf8.decode(body) catch { _ => return PassThrough }
  let root = @json.parse(decoded) catch { _ => return PassThrough }
  guard root is Object(obj) else { return PassThrough }
  match obj.get("model") {
    Some(String(m)) =>
      if !m.clamped_view().equal_ignore_ascii_case(spec.entry_model) {
        return PassThrough
      }
    _ => return PassThrough
  }
  guard obj.get("messages") is Some(Array(messages)) else { return PassThrough }
  let mut total_images = 0
  let mut total_reused = 0
  for msg in messages {
    guard msg is Object(mobj) else { continue }
    guard mobj.get("role") is Some(String("user")) else { continue }
    guard mobj.get("content") is Some(Array(parts)) else { continue }
    let mut changed = false
    for idx = 0; idx < parts.length(); idx = idx + 1 {
      let part = parts[idx]
      guard part is Object(pobj) else { continue }
      let is_img = match pobj.get("type") {
        Some(String("image_url")) | Some(String("image")) => true
        _ => false
      }
      if !is_img {
        continue
      }
      let url_opt : String? = match pobj.get("image_url") {
        Some(Object(iu)) =>
          match iu.get("url") {
            Some(String(u)) => Some(u)
            _ => None
          }
        Some(String(u)) => Some(u)
        _ => None
      }
      let is_data = match url_opt {
        Some(u) => u.has_prefix("data:")
        None => false
      }
      let cache_key : String? = match (auth_bytes, is_data) {
        (Some(ab), true) => {
          let canon = canonical_python_json_bytes(part)
          Some(
            @sha256.cache_key_fallback_hex(ab, spec.vision_prompt_utf8, canon),
          )
        }
        _ => None
      }
      let build_req = () => {
        let payload : Json = {
          "model": Json::string(spec.vision_model),
          "stream": false,
          "max_tokens": Json::number(spec.vision_max_tokens.to_double()),
          "messages": [
            {
              "role": "user",
              "content": [
                { "type": "text", "text": Json::string(spec.vision_prompt) },
                part,
              ],
            },
          ],
        }
        @utf8.encode(payload.stringify(escape_slash=false))
      }
      match
        describe_image_with_cache(cache_key, build_req, store, fetch_vision) {
        Ok((caption, hit)) => {
          parts[idx] = {
            "type": "text",
            "text": Json::string("【附图的视觉观察】\n" + caption),
          }
          changed = true
          total_images += 1
          if hit {
            total_reused += 1
          }
        }
        Err(vf) => return Failed(vf)
      }
    }
    if changed {
      let mut all_text = true
      let texts : Array[String] = Array(capacity=parts.length())
      for p in parts {
        match p {
          Object(po) =>
            match (po.get("type"), po.get("text")) {
              (Some(String("text")), Some(String(t))) => texts.push(t)
              _ => {
                all_text = false
                break
              }
            }
          _ => {
            all_text = false
            break
          }
        }
      }
      if all_text {
        let joined = StringBuilder()
        for idx = 0; idx < texts.length(); idx = idx + 1 {
          if idx > 0 {
            joined.write_string("\n\n")
          }
          joined.write_string(texts[idx])
        }
        mobj["content"] = Json::string(joined.to_string())
      }
    }
  }
  if total_images == 0 {
    return PassThrough
  }
  obj["model"] = Json::string(spec.entry_model)
  Rewritten(
    body=@utf8.encode(root.stringify(escape_slash=false)),
    images=total_images,
    reused=total_reused,
  )
}

///|
/// Inspect a `POST /v1/chat/completions` request body; if it targets
/// `cfg.entry_model` and contains user images, caption each image (via cache,
/// coalesced in-flight slot, or `fetch_vision`) and splice the captions in.
pub async fn maybe_rewrite_vision_chat(
  body : Bytes,
  cfg : @config.Config,
  authorization : String?,
  store : @cache.CaptionStore,
  fetch_vision : async (Bytes) -> Result[Bytes, @cache.VisionFailure],
) -> AssistOutcome {
  if body.length() == 0 {
    return PassThrough
  }
  let spec = get_vision_spec(cfg)
  let auth_bytes : Bytes? = match authorization {
    Some(a) if !a.is_empty() => Some(@utf8.encode(a))
    _ => None
  }
  match scan_chat_body(body, spec) {
    Skip => PassThrough
    UseFallback =>
      rewrite_dom_fallback(body, spec, auth_bytes, store, fetch_vision)
    UseFast(model_s~, model_e~, rewrite_model~, msgs~) => {
      let replacements : Array[(Int32, Int32, Bytes)] = []
      if rewrite_model {
        replacements.push((model_s, model_e, spec.entry_model_quoted))
      }
      let mut total_images = 0
      let mut total_reused = 0
      for umsg in msgs {
        let msg_buf = @buffer.Buffer(capacity=512)
        msg_buf.write_byte(b'"')
        for idx = 0; idx < umsg.parts.length(); idx = idx + 1 {
          if idx > 0 {
            msg_buf.write_bytesview(b"\\n\\n")
          }
          match umsg.parts[idx] {
            TextInner(ts, te) =>
              if te > ts {
                msg_buf.write_bytesview(body[ts:te])
              }
            Image(img) => {
              let cache_key : String? = match (auth_bytes, img.is_data_url) {
                (Some(ab), true) =>
                  Some(
                    @sha256.cache_key_slices_hex(
                      ab,
                      spec.vision_prompt_utf8,
                      body,
                      img.url_s,
                      img.url_e - img.url_s,
                      img.kind_s,
                      img.kind_e - img.kind_s,
                    ),
                  )
                _ => None
              }
              let build_req = () => {
                assemble_vision_req_slice(spec, body, img.part_s, img.part_e)
              }
              match
                describe_image_with_cache(
                  cache_key, build_req, store, fetch_vision,
                ) {
                Ok((caption, hit)) => {
                  let cap_inner = encode_caption_json_inner(caption)
                  msg_buf.write_bytesview(cap_inner[:])
                  total_images += 1
                  if hit {
                    total_reused += 1
                  }
                }
                Err(vf) => return Failed(vf)
              }
            }
          }
        }
        msg_buf.write_byte(b'"')
        replacements.push((umsg.arr_s, umsg.arr_e, msg_buf.to_bytes()))
      }
      Rewritten(
        body=splice_replacements(body, replacements),
        images=total_images,
        reused=total_reused,
      )
    }
  }
}