// Sans-IO HTTP model: case-insensitive multi-value headers, request/response,
// transport errors, UTF-8 helpers, and the Transport trait.

///|
/// Allocation-free ASCII case-insensitive string equality (for HTTP header names).
pub fn eq_ascii_ignore_case(a : String, b : String) -> Bool {
  let len = a.length()
  if len != b.length() {
    return false
  }
  for i in 0..= 0x41 && ca <= 0x5A {
      ca += 0x20
    }
    if cb >= 0x41 && cb <= 0x5A {
      cb += 0x20
    }
    if ca != cb {
      return false
    }
  }
  true
}

///|
fn is_sensitive_header_name(name : String) -> Bool {
  eq_ascii_ignore_case(name, "authorization") ||
  eq_ascii_ignore_case(name, "proxy-authorization") ||
  eq_ascii_ignore_case(name, "cookie") ||
  eq_ascii_ignore_case(name, "set-cookie") ||
  eq_ascii_ignore_case(name, "x-api-key")
}

///|
/// True for RFC 9110 hop-by-hop or transport-managed framing headers that
/// callers must not smuggle through an HTTP transport.
pub fn is_hop_by_hop_or_framing_header(name : String) -> Bool {
  eq_ascii_ignore_case(name, "host") ||
  eq_ascii_ignore_case(name, "content-length") ||
  eq_ascii_ignore_case(name, "transfer-encoding") ||
  eq_ascii_ignore_case(name, "connection") ||
  eq_ascii_ignore_case(name, "keep-alive") ||
  eq_ascii_ignore_case(name, "upgrade") ||
  eq_ascii_ignore_case(name, "proxy-connection") ||
  eq_ascii_ignore_case(name, "te") ||
  eq_ascii_ignore_case(name, "trailer")
}

///|
#derive(Debug)
priv struct RedactedHeaders {
  entries : Array[(String, String)]
}

///|
/// Case-insensitive multi-value header collection. Insertion order is
/// preserved; `get` returns the first matching value, `get_all` all of them.
/// Equality compares entries in order with ASCII case-insensitive header names.
/// `Debug` redacts sensitive headers (`Authorization`, `Proxy-Authorization`,
/// `Cookie`, `Set-Cookie`, `X-Api-Key`).
pub struct Headers {
  priv entries : Array[(String, String)]
}

///|
pub impl @debug.Debug for Headers with fn to_repr(self) {
  let redacted : Array[(String, String)] = []
  for entry in self.entries {
    let (k, v) = entry
    if is_sensitive_header_name(k) {
      redacted.push((k, ""))
    } else {
      redacted.push((k, v))
    }
  }
  @debug.Repr(({ entries: redacted, } : RedactedHeaders))
}

///|
pub impl Eq for Headers with fn equal(self, other) {
  if self.entries.length() != other.entries.length() {
    return false
  }
  for i in 0.. Headers {
  { entries: [], }
}

///|
/// Build headers from `(name, value)` pairs (names are stored as written).
pub fn Headers::of(pairs : Array[(String, String)]) -> Headers {
  { entries: pairs.copy(), }
}

///|
/// Return a shallow copy of this `Headers` collection.
pub fn Headers::copy(self : Headers) -> Headers {
  { entries: self.entries.copy(), }
}

///|
/// First value for `name` (ASCII case-insensitive).
pub fn Headers::get(self : Headers, name : String) -> String? {
  for entry in self.entries {
    let (k, v) = entry
    if eq_ascii_ignore_case(k, name) {
      return Some(v)
    }
  }
  None
}

///|
/// All values for `name` (ASCII case-insensitive), in insertion order.
pub fn Headers::get_all(self : Headers, name : String) -> Array[String] {
  let out : Array[String] = []
  for entry in self.entries {
    let (k, v) = entry
    if eq_ascii_ignore_case(k, name) {
      out.push(v)
    }
  }
  out
}

///|
/// Whether `name` is present (case-insensitive).
pub fn Headers::contains(self : Headers, name : String) -> Bool {
  self.get(name) is Some(_)
}

///|
/// Append a value without replacing existing ones (multi-value headers such
/// as `Set-Cookie`).
pub fn Headers::append(self : Headers, name : String, value : String) -> Unit {
  self.entries.push((name, value))
}

///|
/// Set (replace all existing values for `name` case-insensitively with one).
pub fn Headers::set(self : Headers, name : String, value : String) -> Unit {
  self.remove(name)
  self.entries.push((name, value))
}

///|
/// Remove all values for `name` (case-insensitive).
pub fn Headers::remove(self : Headers, name : String) -> Unit {
  let kept : Array[(String, String)] = []
  for entry in self.entries {
    let (k, _) = entry
    if !eq_ascii_ignore_case(k, name) {
      kept.push(entry)
    }
  }
  self.entries.clear()
  for entry in kept {
    self.entries.push(entry)
  }
}

///|
/// Copy of entries in insertion order.
pub fn Headers::entries(self : Headers) -> Array[(String, String)] {
  self.entries.copy()
}

///|
/// Number of header entries (including duplicate names).
pub fn Headers::length(self : Headers) -> Int32 {
  self.entries.length()
}

///|
/// True when no headers are present.
pub fn Headers::is_empty(self : Headers) -> Bool {
  self.entries.is_empty()
}

///|
/// HTTP request ready for a `Transport`. The URL is fully assembled by the
/// client/encoding layer.
#derive(Debug, Eq)
pub struct Request {
  http_method : String
  url : String
  headers : Headers
  mut body : Bytes?
}

///|
/// Create a new HTTP request with empty headers and no body.
pub fn Request::new(http_method~ : String, url~ : String) -> Request {
  { http_method, url, headers: Headers::new(), body: None, }
}

///|
/// HTTP method verb (e.g. `"GET"`, `"POST"`).
pub fn Request::http_method(self : Request) -> String {
  self.http_method
}

///|
/// Fully assembled request URL.
pub fn Request::url(self : Request) -> String {
  self.url
}

///|
/// Mutable header map attached to this request.
pub fn Request::headers(self : Request) -> Headers {
  self.headers
}

///|
/// Optional request body bytes.
pub fn Request::body(self : Request) -> Bytes? {
  self.body
}

///|
/// Set (replace) a request header and return `self` for chaining.
pub fn Request::with_header(
  self : Request,
  name : String,
  value : String,
) -> Request {
  self.headers.set(name, value)
  self
}

///|
/// Attach a body with an explicit `Content-Type` header.
pub fn Request::with_body(
  self : Request,
  content_type~ : String,
  body~ : Bytes,
) -> Request {
  self.headers.set("Content-Type", content_type)
  self.body = Some(body)
  self
}

///|
/// Attach raw bytes as the request body without modifying `Content-Type`.
pub fn Request::with_raw_body(self : Request, body : Bytes) -> Request {
  self.body = Some(body)
  self
}

///|
/// Return a shallow-body, deep-headers snapshot of this request.
pub fn Request::clone(self : Request) -> Request {
  {
    http_method: self.http_method,
    url: self.url,
    headers: self.headers.copy(),
    body: self.body,
  }
}

///|
/// Attach a UTF-8 JSON body (`Content-Type: application/json`).
pub fn Request::with_json_body(self : Request, json : @json.Json) -> Request {
  self.with_body(
    content_type="application/json",
    body=utf8_encode(json.stringify()),
  )
}

///|
/// HTTP response with a fully buffered body.
#derive(Debug, Eq)
pub struct Response {
  priv status : Int32
  priv headers : Headers
  priv body : Bytes
}

///|
/// Construct a buffered HTTP `Response` (defensively copying `headers`).
pub fn Response::new(
  status~ : Int32,
  headers~ : Headers,
  body~ : Bytes,
) -> Response {
  { status, headers: headers.copy(), body, }
}

///|
/// HTTP status code (e.g. `200`, `404`).
pub fn Response::status(self : Response) -> Int32 {
  self.status
}

///|
/// Defensive copy of the response headers.
pub fn Response::headers(self : Response) -> Headers {
  self.headers.copy()
}

///|
/// Raw buffered response body bytes.
pub fn Response::body(self : Response) -> Bytes {
  self.body
}

///|
/// Body decoded as UTF-8 text (lossy replacement on invalid bytes).
pub fn Response::text(self : Response) -> String {
  utf8_decode(self.body)
}

///|
/// Body decoded as strict UTF-8 text (raises on invalid UTF-8).
pub fn Response::text_strict(self : Response) -> String raise @utf8.Malformed {
  utf8_decode_strict(self.body)
}

///|
/// Body decoded strictly as UTF-8 and parsed as JSON with
/// `preserve_number_repr=true` so 64-bit integers preserve their exact wire
/// text for generated codecs. Raises `@utf8.Malformed` on invalid UTF-8 or
/// `@json.ParseError` on invalid JSON.
pub fn Response::json(self : Response) -> @json.Json raise {
  let text = self.text_strict()
  @json.parse(text, preserve_number_repr=true)
}

///|
/// Why a transport exchange failed. A non-2xx HTTP status is NOT a transport
/// error — responses are returned normally; status handling belongs to the
/// client error layer.
#derive(Debug, Eq)
pub(all) suberror TransportError {
  /// Connection-level failure (DNS, TCP connect, TLS, reset).
  Network(String)
  /// The URL or request could not be formed.
  InvalidUrl(String)
  /// The peer spoke invalid HTTP or an unexpected transport state occurred.
  Protocol(String)
  /// The exchange exceeded a configured timeout.
  Timeout
  /// The exchange was cancelled before a response arrived.
  Cancelled
}

///|
/// The sans-IO HTTP transport contract. Implementations perform one exchange
/// per call: send the request, buffer the response body, and return it.
/// Non-2xx HTTP statuses MUST be returned as `Response`, not raised.
pub(open) trait Transport {
  async fn send(Self, Request) -> Response raise TransportError
}

///|
/// UTF-8 encode a string into bytes.
pub fn utf8_encode(text : String) -> Bytes {
  @utf8.encode(text)
}

///|
/// UTF-8 decode bytes with replacement characters for invalid sequences.
pub fn utf8_decode(bytes : Bytes) -> String {
  @utf8.decode_lossy(bytes[:])
}

///|
/// Strict UTF-8 decode raising `@utf8.Malformed` on invalid byte sequences.
pub fn utf8_decode_strict(bytes : Bytes) -> String raise @utf8.Malformed {
  @utf8.decode(bytes[:])
}

///|
/// Whether `token` is a non-empty RFC 9110 HTTP token (`1*tchar`), valid for
/// HTTP methods and header field names.
pub fn is_valid_http_token(token : String) -> Bool {
  if token.length() == 0 {
    return false
  }
  for cu in token.code_units() {
    let code = cu.to_int()
    let ok = (code >= 0x30 && code <= 0x39) ||
      (code >= 0x41 && code <= 0x5A) ||
      (code >= 0x61 && code <= 0x7A) ||
      code == 0x21 ||
      code == 0x23 ||
      code == 0x24 ||
      code == 0x25 ||
      code == 0x26 ||
      code == 0x27 ||
      code == 0x2A ||
      code == 0x2B ||
      code == 0x2D ||
      code == 0x2E ||
      code == 0x5E ||
      code == 0x5F ||
      code == 0x60 ||
      code == 0x7C ||
      code == 0x7E
    if !ok {
      return false
    }
  }
  true
}

///|
/// Whether `value` is safe as an outbound HTTP header field value per RFC 9110
/// §5.5 (printable ASCII `0x20..=0x7E` plus horizontal tab `0x09`; rejects
/// `\r`, `\n`, `\0`, DEL, and non-ASCII `> 0x7E` that would crash JS `Headers`
/// or emit raw UTF-8 into HTTP/1.1 headers).
pub fn is_valid_header_value(value : String) -> Bool {
  for cu in value.code_units() {
    let c = cu.to_int()
    if !(c == 0x09 || (c >= 0x20 && c <= 0x7E)) {
      return false
    }
  }
  true
}