// Hand-written core helpers that cannot be generated.
//
// The generator skips methods whose parameters are closures
// (`CommandBuffer::render_pass`, `CommandBuffer::compute_pass`), because a
// function type cannot cross the virtual backend boundary. They are implemented
// here instead: the callback receives a pass handle that carries the same id as
// the owning command buffer, and the backend forwards every
// `backend_render_pass_*` / `backend_compute_pass_*` call to the corresponding
// `backend_command_buffer_*` entry point.

///|
/// Record an offscreen pass: opens the render pass, runs `draw`, and always
/// closes the pass before re-raising a failure from the callback.
pub fn CommandBuffer::render_pass(
  self : CommandBuffer,
  colors : Array[@types.RenderTargetDesc],
  depth? : @types.DepthTargetDesc,
  draw : (RenderPass) -> Unit raise RhiError,
) -> Unit raise RhiError {
  let depth_desc = match depth {
    Some(d) => d
    None => @types.DepthTargetDesc::new(0)
  }
  self.begin_render_pass(colors, depth_desc)
  let pass : RenderPass = { id: self.id }
  let pending : RhiError? = try {
    draw(pass)
    None
  } catch {
    e => Some(e)
  }
  self.end_render_pass()
  match pending {
    Some(e) => raise e
    None => ()
  }
}

///|
pub fn CommandBuffer::compute_pass(
  self : CommandBuffer,
  encode : (ComputePass) -> Unit raise RhiError,
) -> Unit raise RhiError {
  let pass : ComputePass = { id: self.id }
  encode(pass)
}

///|
/// Upload several subregions with one call. The backend ABI cannot carry an
/// array of tuples, so the loop lives in the core and issues individual
/// `upload_subregion` calls.
pub fn Texture::upload_subregions(
  self : Texture,
  regions : Array[(Int, Int, Int, Int, Bytes)],
  layer? : Int = 0,
  mip_level? : Int = 0,
) -> Unit raise RhiError {
  for region in regions {
    let (x, y, width, height, pixels) = region
    self.upload_subregion(x, y, width, height, pixels, layer, mip_level)
  }
}

///|
/// Record a swapchain pass: opens the pass (clearing with `clear_color`), runs
/// `draw`, then closes it. Mirrors `render_pass` for the presented image.
pub fn CommandBuffer::swapchain_pass(
  self : CommandBuffer,
  swapchain : Swapchain,
  load_op : @types.LoadOp,
  clear_color : @types.ClearColor,
  draw : (RenderPass) -> Unit raise RhiError,
) -> Unit raise RhiError {
  self.begin_swapchain_pass(swapchain, load_op, clear_color)
  let pass : RenderPass = { id: self.id }
  let pending : RhiError? = try {
    draw(pass)
    None
  } catch {
    e => Some(e)
  }
  self.end_swapchain_pass()
  match pending {
    Some(e) => raise e
    None => ()
  }
}

///|
/// The shader blob format this device can consume (ADR-005 D7).
///
/// It is derived from `BackendKind` rather than stored in `DeviceCapabilities`
/// because it is not a *capability*: every WebGPU device takes WGSL and every
/// Vulkan device takes SPIR-V, and a device that could do neither would not be a
/// device. Keeping it a method also keeps the capability struct's literal
/// constructors in the backends untouched.
///
/// A renderer asks this before choosing which of its two shader sources to hand
/// over; `Dxil` is reported honestly so a renderer that only ships SPIR-V and
/// WGSL can refuse instead of submitting the wrong bytes.
pub fn Device::shader_language(self : Device) -> @types.ShaderLanguage {
  self.backend().shader_language()
}

///|
/// Convert a platform `@tycho_plat.Surface` (desktop window, iOS `CAMetalLayer`,
/// Android `ANativeWindow`, or web canvas) into an L1 `@types.ExternalSurface`
/// suitable for `SwapchainDesc::new(..., external_surface=...)`.
pub fn external_surface_from_plat(
  surface : @tycho_plat.Surface,
) -> @types.ExternalSurface {
  let kind = match surface.kind {
    @tycho_plat.SurfaceKind::Xlib => @types.ExternalSurfaceKind::Xlib
    @tycho_plat.SurfaceKind::Xcb => @types.ExternalSurfaceKind::Xcb
    @tycho_plat.SurfaceKind::Wayland => @types.ExternalSurfaceKind::Wayland
    @tycho_plat.SurfaceKind::Win32 => @types.ExternalSurfaceKind::Win32
    @tycho_plat.SurfaceKind::Metal => @types.ExternalSurfaceKind::MetalLayer
    @tycho_plat.SurfaceKind::Android =>
      @types.ExternalSurfaceKind::AndroidNativeWindow
    @tycho_plat.SurfaceKind::CanvasGpu => @types.ExternalSurfaceKind::WebCanvas
    @tycho_plat.SurfaceKind::Headless => @types.ExternalSurfaceKind::Headless
  }
  @types.ExternalSurface::new(kind, surface.a, surface.b)
}