///|
/// Edge Serverless Upstash HTTP `/pipeline` transport for `RedisClient`.
/// Batches queued RESP commands from `send_raw` into a single HTTP POST `/pipeline` round-trip
/// so Cloudflare Workers / Edge runtimes can use `RedisClient` and `RedisKey` SingleFlight without TCP.

///|
/// Portable HTTP POST callback: `(url, headers, body_bytes) -> (status_code, response_body_bytes)`.
pub type HttpPostFn = async (String, Array[(String, String)], Bytes) -> (
  Int32,
  Bytes,
) raise @codec.DataError

///|
fn strip_trailing_slashes(s : String) -> String {
  let mut end = s.length()
  while end > 0 && s.code_unit_at(end - 1) == '/' {
    end -= 1
  }
  s[:end].to_owned()
}

///|
fn resp_to_json_cmd_arg(v : @resp.RespValue) -> Json raise @codec.DataError {
  match v {
    @resp.RespValue::BulkString(b) => {
      let s = @utf8.decode(b[:]) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "Upstash HTTP transport requires UTF-8 command arguments",
          )
      }
      Json::string(s)
    }
    @resp.RespValue::SimpleString(s) => Json::string(s)
    @resp.RespValue::Integer(n) => Json::string(n.to_string())
    _ =>
      raise @codec.DataError::ProtocolError(
        "unsupported RESP value inside command array",
      )
  }
}

///|
fn json_to_resp_value(j : Json) -> @resp.RespValue {
  match j {
    Null => @resp.RespValue::Null
    True => @resp.RespValue::Boolean(true)
    False => @resp.RespValue::Boolean(false)
    Number(n, ..) =>
      if !(n.is_nan() || n.is_inf()) &&
        n >= -9007199254740991.0 &&
        n <= 9007199254740991.0 {
        let i = n.to_int64()
        if i.to_double() == n {
          @resp.RespValue::Integer(i)
        } else {
          @resp.RespValue::Double(n)
        }
      } else {
        @resp.RespValue::Double(n)
      }
    String(s) => @resp.RespValue::BulkString(@utf8.encode(s))
    Array(items) => @resp.RespValue::Array(items.map(json_to_resp_value))
    Object(m) => {
      let pairs : Array[(@resp.RespValue, @resp.RespValue)] = []
      m.each((k, v) => {
        pairs.push(
          (@resp.RespValue::BulkString(@utf8.encode(k)), json_to_resp_value(v)),
        )
      })
      @resp.RespValue::Map(pairs)
    }
  }
}

///|
/// Upstash REST `/pipeline` implementation of `RedisTransport`.
pub struct UpstashHttpTransport {
  priv pipeline_url : String
  priv auth_header : String
  priv post : HttpPostFn
  priv replies : Array[@resp.RespValue]
  priv mut read_idx : Int32
  priv mut closed : Bool
}

///|
pub fn UpstashHttpTransport::UpstashHttpTransport(
  url~ : String,
  token~ : String,
  post~ : HttpPostFn,
) -> UpstashHttpTransport {
  let base = strip_trailing_slashes(url)
  {
    pipeline_url: "\{base}/pipeline",
    auth_header: "Bearer \{token}",
    post,
    replies: [],
    read_idx: 0,
    closed: false,
  }
}

///|
pub impl RedisTransport for UpstashHttpTransport with fn send_raw(self, payload) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::ConnectionFailed("UpstashHttpTransport is closed")
  }
  let decoder = @resp.RespDecoder::RespDecoder()
  decoder.feed(payload[:])
  let cmds : Array[Json] = []
  for ;; {
    match decoder.next_frame() {
      Some(@resp.RespValue::Array(args)) => {
        let cmd_json : Array[Json] = []
        for a in args {
          cmd_json.push(resp_to_json_cmd_arg(a))
        }
        cmds.push(Json::array(cmd_json))
      }
      Some(_) =>
        raise @codec.DataError::ProtocolError(
          "expected RESP Array command frame in UpstashHttpTransport",
        )
      None => break
    }
  }
  if cmds.is_empty() {
    return
  }
  let body = @utf8.encode(Json::array(cmds).stringify())
  let headers : Array[(String, String)] = [
    ("authorization", self.auth_header),
    ("content-type", "application/json"),
  ]
  let (status, resp_bytes) = (self.post)(self.pipeline_url, headers, body)
  let resp_text = @utf8.decode(resp_bytes[:]) catch {
    _ =>
      raise @codec.DataError::ProtocolError(
        "non-UTF-8 response from Upstash endpoint",
      )
  }
  if status < 200 || status >= 300 {
    raise @codec.DataError::ConnectionFailed(
      "Upstash HTTP \{status}: \{resp_text}",
    )
  }
  let parsed = @json.parse(resp_text) catch {
    err =>
      raise @codec.DataError::ProtocolError(
        "invalid JSON from Upstash /pipeline: \{err}",
      )
  }
  match parsed {
    Array(items) => {
      if items.length() != cmds.length() {
        raise @codec.DataError::ProtocolError(
          "Upstash /pipeline returned \{items.length()} replies for \{cmds.length()} commands",
        )
      }
      for item in items {
        match item {
          Object(m) =>
            match m.get("error") {
              Some(String(err_msg)) =>
                self.replies.push(@resp.RespValue::SimpleError(err_msg))
              _ =>
                match m.get("result") {
                  Some(res) => self.replies.push(json_to_resp_value(res))
                  None => self.replies.push(@resp.RespValue::Null)
                }
            }
          _ =>
            raise @codec.DataError::ProtocolError(
              "expected object entry in Upstash /pipeline response",
            )
        }
      }
    }
    _ =>
      raise @codec.DataError::ProtocolError(
        "expected JSON array from Upstash /pipeline",
      )
  }
}

///|
pub impl RedisTransport for UpstashHttpTransport with fn recv_resp(self) -> @resp.RespValue raise @codec.DataError {
  @async.pause()
  if self.read_idx < self.replies.length() {
    let v = self.replies[self.read_idx]
    self.read_idx += 1
    if self.read_idx >= self.replies.length() {
      self.replies.clear()
      self.read_idx = 0
    }
    v
  } else {
    raise @codec.DataError::ConnectionFailed(
      "UpstashHttpTransport reply queue empty",
    )
  }
}

///|
pub impl RedisTransport for UpstashHttpTransport with fn close(self) -> Unit {
  @async.pause()
  self.closed = true
  self.replies.clear()
  self.read_idx = 0
}