///|
/// Production Native `@runtime.HttpClient` built on `moonbitlang/core/async/http`.
/// Supports timeouts, cancellation propagation, bounded redirect following,
/// response size limits, and streaming SSE/NDJSON responses.

///|
fn webstd_method_to_std(m : @http.Method) -> @std_http.RequestMethod {
  match m {
    Get => @std_http.RequestMethod::Get
    Head => @std_http.RequestMethod::Head
    Post => @std_http.RequestMethod::Post
    Put => @std_http.RequestMethod::Put
    Delete => @std_http.RequestMethod::Delete
    Connect => @std_http.RequestMethod::Connect
    Options => @std_http.RequestMethod::Options
    Trace => @std_http.RequestMethod::Trace
    Patch => @std_http.RequestMethod::Patch
    Custom(s) => @std_http.RequestMethod::Extension(s)
  }
}

///|
fn is_redirect_status(code : Int32) -> Bool {
  code == 301 || code == 302 || code == 303 || code == 307 || code == 308
}

///|
fn is_streaming_content_type(ct : String) -> Bool {
  let lower = ct.to_lower()
  lower.contains("text/event-stream") || lower.contains("application/x-ndjson")
}

///|
fn resolve_redirect_url(current_url : String, location : String) -> String {
  let loc = location.trim().to_owned()
  if loc.has_prefix("http://") || loc.has_prefix("https://") {
    return loc
  }
  match current_url.find("://") {
    Some(scheme_end) => {
      let after_scheme = scheme_end + 3
      let origin = match current_url[after_scheme:].find("/") {
        Some(rel) => current_url[:after_scheme + rel].to_owned()
        None => current_url
      }
      if loc.has_prefix("//") {
        let scheme = current_url[:scheme_end].to_owned()
        "\{scheme}:\{loc}"
      } else if loc.has_prefix("/") {
        "\{origin}\{loc}"
      } else {
        "\{origin}/\{loc}"
      }
    }
    None => loc
  }
}

///|
fn extract_origin(url : String) -> String {
  match url.find("://") {
    Some(scheme_end) => {
      let after_scheme = scheme_end + 3
      match url[after_scheme:].find("/") {
        Some(rel) => url[:after_scheme + rel].to_owned().to_lower()
        None => url.to_lower()
      }
    }
    None => ""
  }
}

///|
fn std_cookie_to_webstd(c : @std_http.Cookie) -> @http.Cookie {
  let opts = @http.CookieOptions::CookieOptions(
    path?=c.path,
    domain?=c.domain,
    max_age?=c.max_age,
    expires?=c.expires_raw,
    secure=c.secure,
    http_only=c.http_only,
  )
  @http.Cookie::Cookie(c.name, c.value, options=opts)
}

///|
/// Native HTTP/HTTPS outbound client implementing `@runtime.HttpClient`.
pub struct NativeHttpClient {
  priv timeout_ms : Int32
  priv max_response_bytes : Int64
  priv max_redirects : Int32
}

///|
/// Creates a production Native `@runtime.HttpClient` with configurable timeout,
/// buffered response cap, and redirect limit.
pub fn native_http_client(
  timeout_ms~ : Int32 = 30_000,
  max_response_bytes~ : Int64 = 16_777_216L,
  max_redirects~ : Int32 = 5,
) -> NativeHttpClient {
  { timeout_ms, max_response_bytes, max_redirects, }
}

///|
async fn NativeHttpClient::send_once(
  _self : NativeHttpClient,
  meth : @http.Method,
  url : String,
  headers : @http.Headers,
  body_bytes : Bytes,
  body_stream : @http.ByteStream?,
) -> (@std_http.Client, @std_http.ResponseHeader, @std_http.ClientConnection) raise @runtime.RuntimeError {
  let std_headers : Map[@std_http.CaseInsensitiveString, String] = Map([])
  for pair in headers.entries() {
    let k = pair.0.to_lower()
    if k != "content-length" && k != "transfer-encoding" && k != "host" {
      std_headers[@std_http.CaseInsensitiveString(pair.0)] = pair.1
    }
  }
  let client = @std_http.Client::Client()
  let conn = client.request_stream(
    webstd_method_to_std(meth),
    url,
    extra_headers=std_headers,
  ) catch {
    err => {
      client.close()
      raise @runtime.RuntimeError::IoFailure(
        "HTTP request connect failed for \{url}: \{err}",
      )
    }
  }
  errdefer {
    conn.close()
    client.close()
  }
  match body_stream {
    Some(stream) => {
      defer (stream.cancel)("native_http_client_sent")
      for ;; {
        let chunk_opt = (stream.next_chunk)() catch {
          err =>
            raise @runtime.RuntimeError::IoFailure(
              "request body stream failed: \{err}",
            )
        }
        match chunk_opt {
          Some(chunk) =>
            if !chunk.is_empty() {
              conn.write(chunk[:]) catch {
                err =>
                  raise @runtime.RuntimeError::IoFailure(
                    "HTTP request body write failed: \{Repr(err)}",
                  )
              }
            }
          None => break
        }
      }
    }
    None =>
      if !body_bytes.is_empty() {
        conn.write(body_bytes[:]) catch {
          err =>
            raise @runtime.RuntimeError::IoFailure(
              "HTTP request body write failed: \{Repr(err)}",
            )
        }
      }
  }
  let resp_hdr = conn.end_request() catch {
    err =>
      raise @runtime.RuntimeError::IoFailure(
        "HTTP response header read failed for \{url}: \{err}",
      )
  }
  (client, resp_hdr, conn)
}

///|
async fn NativeHttpClient::execute(
  self : NativeHttpClient,
  req : @http.Request,
) -> @http.Response raise @runtime.RuntimeError {
  let mut cur_meth = req.meth
  let mut cur_url = req.url.to_string()
  let mut cur_headers = req.headers.clone()
  let (initial_bytes, initial_stream) : (Bytes, @http.ByteStream?) = match
    req.body {
    @http.Body::Empty => (b"", None)
    @http.Body::Text(s) => (@utf8.encode(s), None)
    @http.Body::Bytes(b) => (b, None)
    @http.Body::Stream(s) => (b"", Some(s))
  }
  let mut cur_bytes = initial_bytes
  let mut cur_stream = initial_stream
  let mut redirects_done = 0

  for ;; {
    let (client, resp_hdr, conn) = self.send_once(
      cur_meth, cur_url, cur_headers, cur_bytes, cur_stream,
    )
    let resp_headers = @http.Headers::Headers()
    resp_hdr.headers.each((k, v) => resp_headers.append(k.to_string(), v))
    let switches_to_get = resp_hdr.code == 303 ||
      (
        (resp_hdr.code == 301 || resp_hdr.code == 302) &&
        cur_meth == @http.Method::Post
      )
    let can_follow_body = cur_stream is None || switches_to_get
    if is_redirect_status(resp_hdr.code) &&
      redirects_done < self.max_redirects &&
      can_follow_body {
      match resp_headers.get("location") {
        Some(loc) if !loc.is_empty() => {
          conn.close()
          client.close()
          let next_url = resolve_redirect_url(cur_url, loc)
          if extract_origin(cur_url) != extract_origin(next_url) {
            cur_headers.remove("authorization")
            cur_headers.remove("cookie")
          }
          if switches_to_get {
            cur_meth = @http.Method::Get
            cur_bytes = b""
            cur_stream = None
            cur_headers.remove("content-type")
          }
          cur_url = next_url
          cur_headers = cur_headers.clone()
          redirects_done += 1
          continue
        }
        _ => ()
      }
    }

    let cookies : Array[@http.Cookie] = resp_hdr.cookies.map(
      std_cookie_to_webstd,
    )
    let content_type = resp_headers.get("content-type").unwrap_or("")
    if is_streaming_content_type(content_type) {
      let closed = Ref(false)
      let close_once = () => {
        if !closed.val {
          closed.val = true
          conn.close()
          client.close()
        }
      }
      let stream = @http.ByteStream::ByteStream(
        next_chunk=() => {
          if closed.val {
            return None
          }
          let chunk = conn.read() catch {
            _ => {
              close_once()
              None
            }
          }
          match chunk {
            Some(b) => Some(b)
            None => {
              close_once()
              None
            }
          }
        },
        cancel=_ => close_once(),
      )
      return @http.Response::Response(
        status=resp_hdr.code,
        headers=resp_headers,
        cookies~,
        body=@http.Body::Stream(stream),
      )
    }

    defer {
      conn.close()
      client.close()
    }
    if cur_meth == @http.Method::Head ||
      resp_hdr.code == 204 ||
      resp_hdr.code == 304 ||
      (resp_hdr.code >= 100 && resp_hdr.code < 200) {
      return @http.Response::Response(
        status=resp_hdr.code,
        headers=resp_headers,
        cookies~,
        body=@http.Body::Empty,
      )
    }
    let buf = Buffer()
    let mut total = 0L
    for ;; {
      let chunk = conn.read() catch {
        err =>
          raise @runtime.RuntimeError::IoFailure(
            "HTTP response body read failed: \{Repr(err)}",
          )
      }
      match chunk {
        Some(b) => {
          total += b.length().to_int64()
          if self.max_response_bytes > 0L && total > self.max_response_bytes {
            raise @runtime.RuntimeError::IoFailure(
              "HTTP response exceeded max_response_bytes (\{self.max_response_bytes})",
            )
          }
          buf.write_bytesview(b[:])
        }
        None => break
      }
    }
    let out_bytes = buf.to_bytes()
    let body : @http.Body = if out_bytes.is_empty() {
      @http.Body::Empty
    } else {
      @http.Body::Bytes(out_bytes)
    }
    return @http.Response::Response(
      status=resp_hdr.code,
      headers=resp_headers,
      cookies~,
      body~,
    )
  }
}

///|
pub impl @runtime.HttpClient for NativeHttpClient with fn send(self, req) -> @http.Response raise @runtime.RuntimeError {
  if self.timeout_ms > 0 {
    let opt = @async.with_timeout_opt(self.timeout_ms, () => self.execute(req)) catch {
      @runtime.RuntimeError::Unavailable(_) as e => raise e
      @runtime.RuntimeError::IoFailure(_) as e => raise e
      @runtime.RuntimeError::Timeout(_) as e => raise e
      err => raise @runtime.RuntimeError::IoFailure("\{err}")
    }
    match opt {
      Some(resp) => resp
      None =>
        raise @runtime.RuntimeError::Timeout(
          "HTTP request to \{req.url.to_string()} timed out after \{self.timeout_ms}ms",
        )
    }
  } else {
    self.execute(req)
  }
}