///|
/// WASI Preview 2 (`wasi:http/types@0.2.0`, `wasi:io/streams@0.2.0`, `wasi:io/poll@0.2.0`)
/// streaming Component Model bridge.
/// Lazily wraps `incoming-body` as `@http.Body::Stream` (zero upfront buffering) and streams
/// `@http.Response` bodies (including SSE chunks) directly into `outgoing-body` + `finish`.

///|
/// Opaque WASI Preview 2 resource handle (`u32` / `Int32` in Canonical ABI).
#derive(Debug, Eq, Hash)
pub(all) struct WasiHandle(Int32)

///|
/// Result of a non-blocking or blocking `wasi:io/streams@0.2.0` read operation.
#non_exhaustive
#derive(Debug, Eq)
pub(all) enum WasiStreamRead {
  Chunk(Bytes)
  Closed
}

///|
/// Canonical ABI host operations for `wasi:http/types@0.2.0`, `wasi:io/streams@0.2.0`,
/// and `wasi:io/poll@0.2.0`. Production Wasmtime/Spin components wire this to host imports;
/// unit tests can run against `MockWasiStreamHost` across native, js, and wasm targets.
pub(open) trait WasiStreamHost {
  fn request_method(Self, req : WasiHandle) -> WasiMethod raise WasiErrorCode
  fn request_scheme(Self, req : WasiHandle) -> WasiScheme raise WasiErrorCode
  fn request_authority(Self, req : WasiHandle) -> String raise WasiErrorCode
  fn request_path_with_query(Self, req : WasiHandle) -> String raise WasiErrorCode
  fn request_headers(Self, req : WasiHandle) -> WasiFields raise WasiErrorCode
  fn request_consume_body(Self, req : WasiHandle) -> WasiHandle raise WasiErrorCode
  fn incoming_body_stream(Self, body : WasiHandle) -> WasiHandle raise WasiErrorCode
  fn input_stream_blocking_read(Self, stream : WasiHandle, max_len : Int64) -> WasiStreamRead raise WasiErrorCode
  fn drop_input_stream(Self, stream : WasiHandle) -> Unit
  fn incoming_body_finish(Self, body : WasiHandle) -> Unit
  fn new_outgoing_response(Self, status : Int32, headers : WasiFields) -> WasiHandle raise WasiErrorCode
  fn outgoing_response_body(Self, resp : WasiHandle) -> WasiHandle raise WasiErrorCode
  fn response_outparam_set_ok(Self, outparam : WasiHandle, resp : WasiHandle) -> Unit
  fn response_outparam_set_err(Self, outparam : WasiHandle, err : WasiErrorCode) -> Unit
  fn outgoing_body_write(Self, body : WasiHandle) -> WasiHandle raise WasiErrorCode
  fn output_stream_check_write(Self, stream : WasiHandle) -> Int64 raise WasiErrorCode
  fn output_stream_blocking_write_and_flush(
    Self,
    stream : WasiHandle,
    chunk : BytesView,
  ) -> Unit raise WasiErrorCode
  fn output_stream_subscribe(Self, stream : WasiHandle) -> WasiHandle
  fn pollable_block(Self, pollable : WasiHandle) -> Unit
  fn drop_pollable(Self, pollable : WasiHandle) -> Unit
  fn drop_output_stream(Self, stream : WasiHandle) -> Unit
  fn outgoing_body_finish(Self, body : WasiHandle) -> Unit raise WasiErrorCode
}

///|
fn write_chunked_to_wasi_stream(
  host : &WasiStreamHost,
  out_stream : WasiHandle,
  data : BytesView,
) -> Unit raise WasiErrorCode {
  let mut offset = 0
  let total = data.length()
  while offset < total {
    let mut budget = host.output_stream_check_write(out_stream)
    if budget <= 0L {
      let pollable = host.output_stream_subscribe(out_stream)
      host.pollable_block(pollable)
      host.drop_pollable(pollable)
      budget = host.output_stream_check_write(out_stream)
      if budget <= 0L {
        budget = 4096L
      }
    }
    let remaining = (total - offset).to_int64()
    let to_write = if budget < remaining {
      budget.to_int()
    } else {
      total - offset
    }
    let end = offset + to_write
    host.output_stream_blocking_write_and_flush(out_stream, data[offset:end])
    offset = end
  }
}

///|
/// Handles a WASI Preview 2 `wasi:http/incoming-handler@0.2.0` invocation using streaming
/// `incoming-body` -> `@http.Body::Stream` and chunked `outgoing-body` streaming (preserving SSE).
pub async fn handle_wasi_component_request(
  app : @core.App,
  host : &WasiStreamHost,
  incoming_req : WasiHandle,
  response_out : WasiHandle,
  env~ : @runtime.Env = @runtime.Env::Env(),
  read_chunk_bytes~ : Int64 = 16384L,
) -> Unit {
  ignore(app.freeze())
  let outparam_set = Ref(false)
  try {
    let meth = wasi_method_to_webstd(host.request_method(incoming_req))
    let scheme = host.request_scheme(incoming_req)
    let authority = host.request_authority(incoming_req)
    let raw_path = host.request_path_with_query(incoming_req)
    let path = if raw_path.has_prefix("/") { raw_path } else { "/\{raw_path}" }
    let full_url = "\{scheme.as_str()}://\{authority}\{path}"
    let wasi_headers = host.request_headers(incoming_req)
    let headers = @http.Headers::Headers()
    for pair in wasi_headers.entries {
      let val = @utf8.decode(pair.1[:]) catch { _ => "" }
      headers.append(pair.0, val)
    }

    let in_body_handle = host.request_consume_body(incoming_req)
    let in_stream_handle = host.incoming_body_stream(in_body_handle)
    let in_closed = Ref(false)
    let close_input_once = () => {
      if !in_closed.val {
        in_closed.val = true
        host.drop_input_stream(in_stream_handle)
        host.incoming_body_finish(in_body_handle)
      }
    }
    let req_body : @http.Body = if meth == @http.Method::Get ||
      meth == @http.Method::Head {
      close_input_once()
      @http.Body::Empty
    } else {
      @http.Body::Stream(
        @http.ByteStream::ByteStream(
          next_chunk=() => {
            if in_closed.val {
              return None
            }
            match
              host.input_stream_blocking_read(
                in_stream_handle, read_chunk_bytes,
              ) {
              WasiStreamRead::Chunk(bytes) => Some(bytes)
              WasiStreamRead::Closed => {
                close_input_once()
                None
              }
              WasiStreamRead::.. => {
                close_input_once()
                None
              }
            }
          },
          cancel=_ => close_input_once(),
        ),
      )
    }

    let web_req = @http.Request::Request(
      meth~,
      url=full_url,
      headers~,
      body=req_body,
    ) catch {
      _ => {
        close_input_once()
        raise WasiErrorCode::HttpRequestUriInvalid
      }
    }
    let exec_ctx = @runtime.ExecutionContext::ExecutionContext()
    let resp = app.fetch(web_req, env~, exec_ctx~) catch {
      err => {
        close_input_once()
        raise WasiErrorCode::InternalError(err.to_string())
      }
    }
    close_input_once()

    let out_fields = WasiFields::WasiFields()
    for pair in resp.headers.entries() {
      out_fields.append_str(pair.0, pair.1)
    }
    for c in resp.cookies {
      let line = c.to_set_cookie_header()
      if !line.is_empty() {
        out_fields.append_str("set-cookie", line)
      }
    }

    let out_resp_handle = host.new_outgoing_response(resp.status, out_fields)
    let out_body_handle = host.outgoing_response_body(out_resp_handle)
    // Publish response headers before streaming body so SSE / chunked clients receive headers immediately
    host.response_outparam_set_ok(response_out, out_resp_handle)
    outparam_set.val = true

    let out_stream = host.outgoing_body_write(out_body_handle)
    let stream_dropped = Ref(false)
    let drop_out_stream = () => {
      if !stream_dropped.val {
        stream_dropped.val = true
        host.drop_output_stream(out_stream)
      }
    }
    defer drop_out_stream()
    match resp.body {
      @http.Body::Empty => ()
      @http.Body::Text(s) =>
        if !s.is_empty() {
          write_chunked_to_wasi_stream(host, out_stream, @utf8.encode(s)[:])
        }
      @http.Body::Bytes(b) =>
        if !b.is_empty() {
          write_chunked_to_wasi_stream(host, out_stream, b[:])
        }
      @http.Body::Stream(stream) => {
        defer (stream.cancel)("wasi_stream_closed")
        for ;; {
          match ((stream.next_chunk)() catch { _ => None }) {
            Some(chunk) =>
              if !chunk.is_empty() {
                write_chunked_to_wasi_stream(host, out_stream, chunk[:])
              }
            None => break
          }
        }
      }
    }
    drop_out_stream()
    host.outgoing_body_finish(out_body_handle)
    exec_ctx.drain_background() catch {
      _ => ()
    }
  } catch {
    WasiErrorCode::HttpRequestUriInvalid as e =>
      if !outparam_set.val {
        host.response_outparam_set_err(response_out, e)
      }
    WasiErrorCode::HttpProtocolError as e =>
      if !outparam_set.val {
        host.response_outparam_set_err(response_out, e)
      }
    WasiErrorCode::InternalError(_) as e =>
      if !outparam_set.val {
        host.response_outparam_set_err(response_out, e)
      }
    WasiErrorCode::.. as e =>
      if !outparam_set.val {
        host.response_outparam_set_err(response_out, e)
      }
  }
}