///|
/// Cross-platform HTTP/HTTPS proxy discovery:
/// 1. Explicit `--proxy` / `--no-proxy` CLI flags
/// 2. Standard environment variables (`HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY`, `NO_PROXY`)
/// 3. OS system proxy settings (macOS `scutil --proxy`, Windows registry `Internet Settings`,
///    Linux GNOME `gsettings`)

///|
priv struct ProxyConfig {
  url : String
  source : String
  no_proxy : Array[String]
}

///|
fn split_csv_hosts(raw : String) -> Array[String] {
  let out : Array[String] = []
  let normalized = raw.replace_all(old=";", new=",")
  for part in normalized.split(",") {
    let s = part.trim().to_owned().to_lower()
    if !s.is_empty() {
      out.push(s)
    }
  }
  out
}

///|
fn extract_url_host(url : String) -> String {
  let after_scheme = match url.find("://") {
    Some(idx) => url[idx + 3:].to_owned()
    None => url
  }
  let authority = match after_scheme.find("/") {
    Some(idx) => after_scheme[:idx].to_owned()
    None => after_scheme
  }
  let host_port = match authority.rev_find("@") {
    Some(idx) => authority[idx + 1:].to_owned()
    None => authority
  }
  if host_port.has_prefix("[") {
    match host_port.find("]") {
      Some(idx) => host_port[1:idx].to_owned().to_lower()
      None => host_port.to_lower()
    }
  } else {
    match host_port.find(":") {
      Some(idx) => host_port[:idx].to_owned().to_lower()
      None => host_port.to_lower()
    }
  }
}

///|
fn host_matches_no_proxy(host : String, pattern : String) -> Bool {
  let h = host.to_lower()
  let mut p = pattern.trim().to_owned().to_lower()
  if p.is_empty() {
    return false
  }
  if p == "*" {
    return true
  }
  if p == "" {
    return !h.contains(".") ||
      h == "localhost" ||
      h == "127.0.0.1" ||
      h == "::1"
  }
  if p.has_prefix("*.") {
    p = p[1:].to_owned()
  }
  // Strip optional :port suffix from pattern
  match p.find(":") {
    Some(idx) => p = p[:idx].to_owned()
    None => ()
  }
  if p.has_prefix(".") {
    let bare = p[1:].to_owned()
    h == bare || h.has_suffix(p)
  } else {
    h == p || h.has_suffix(".\{p}")
  }
}

///|
fn should_use_proxy_for_url(proxy : ProxyConfig?, url : String) -> Bool {
  match proxy {
    None => false
    Some(p) => {
      let host = extract_url_host(url)
      if host == "127.0.0.1" || host == "localhost" || host == "::1" {
        return false
      }
      for rule in p.no_proxy {
        if host_matches_no_proxy(host, rule) {
          return false
        }
      }
      true
    }
  }
}

///|
fn normalize_proxy_url(raw : String) -> String? {
  let s = raw.trim().to_owned()
  if s.is_empty() {
    return None
  }
  let lower = s.to_lower()
  if lower.has_prefix("http://") || lower.has_prefix("https://") {
    return Some(s)
  }
  if lower.has_prefix("socks5://") ||
    lower.has_prefix("socks5h://") ||
    lower.has_prefix("socks4://") ||
    lower.has_prefix("socks://") {
    // core/async/http supports HTTP CONNECT proxies, not raw SOCKS handshakes.
    return None
  }
  if s.contains("://") {
    return None
  }
  Some("http://\{s}")
}

///|
fn parse_proxy_client_parts(
  proxy_url : String,
) -> (String, Map[@http.CaseInsensitiveString, String]) {
  let scheme_idx = match proxy_url.find("://") {
    Some(i) => i
    None => return ("http://\{proxy_url}", Map([]))
  }
  let scheme = proxy_url[:scheme_idx].to_owned()
  let rest = proxy_url[scheme_idx + 3:].to_owned()
  let authority = match rest.find("/") {
    Some(i) => rest[:i].to_owned()
    None => rest
  }
  match authority.rev_find("@") {
    None => ("\{scheme}://\{authority}", Map([]))
    Some(at) => {
      let userinfo = authority[:at].to_owned()
      let hostport = authority[at + 1:].to_owned()
      let b64 = @base64.encode(@utf8.encode(userinfo[:])[:])
      (
        "\{scheme}://\{hostport}",
        make_headers([("Proxy-Authorization", "Basic \{b64}")]),
      )
    }
  }
}

///|
fn redact_proxy_url(proxy_url : String) -> String {
  match proxy_url.find("://") {
    None => proxy_url
    Some(s) => {
      let rest = proxy_url[s + 3:].to_owned()
      match rest.rev_find("@") {
        None => proxy_url
        Some(at) =>
          "\{proxy_url[:s + 3].to_owned()}***@\{rest[at + 1:].to_owned()}"
      }
    }
  }
}

///|
fn parse_scutil_proxy_output(output : String) -> ProxyConfig? {
  let mut https_enable = false
  let mut https_host = ""
  let mut https_port = ""
  let mut http_enable = false
  let mut http_host = ""
  let mut http_port = ""
  let exceptions : Array[String] = []
  let mut in_exceptions = false
  for line_view in output.split("\n") {
    let line = line_view.trim().to_owned()
    if line.has_prefix("ExceptionsList") {
      in_exceptions = true
      continue
    }
    if in_exceptions {
      if line == "}" {
        in_exceptions = false
        continue
      }
      match line.find(":") {
        Some(colon) => {
          let val = line[colon + 1:].trim().to_owned()
          if !val.is_empty() {
            exceptions.push(val.to_lower())
          }
        }
        None => ()
      }
      continue
    }
    match line.find(":") {
      None => ()
      Some(colon) => {
        let key = line[:colon].trim().to_owned()
        let val = line[colon + 1:].trim().to_owned()
        match key {
          "HTTPSEnable" => https_enable = val == "1"
          "HTTPSProxy" => https_host = val
          "HTTPSPort" => https_port = val
          "HTTPEnable" => http_enable = val == "1"
          "HTTPProxy" => http_host = val
          "HTTPPort" => http_port = val
          _ => ()
        }
      }
    }
  }
  if https_enable && !https_host.is_empty() && !https_port.is_empty() {
    return Some({
      url: "http://\{https_host}:\{https_port}",
      source: "macOS system proxy",
      no_proxy: exceptions,
    })
  }
  if http_enable && !http_host.is_empty() && !http_port.is_empty() {
    return Some({
      url: "http://\{http_host}:\{http_port}",
      source: "macOS system proxy",
      no_proxy: exceptions,
    })
  }
  None
}

///|
fn parse_windows_proxy_server(raw : String) -> String? {
  let trimmed = raw.trim().to_owned()
  if trimmed.is_empty() {
    return None
  }
  if !trimmed.contains("=") {
    return normalize_proxy_url(trimmed)
  }
  let mut https_val : String? = None
  let mut http_val : String? = None
  for item in trimmed.split(";") {
    let s = item.trim().to_owned()
    match s.find("=") {
      Some(eq) => {
        let k = s[:eq].trim().to_owned().to_lower()
        let v = s[eq + 1:].trim().to_owned()
        if k == "https" && !v.is_empty() {
          https_val = normalize_proxy_url(v)
        } else if k == "http" && !v.is_empty() {
          http_val = normalize_proxy_url(v)
        }
      }
      None => ()
    }
  }
  match https_val {
    Some(u) => Some(u)
    None => http_val
  }
}

///|
fn parse_windows_reg_proxy_output(output : String) -> ProxyConfig? {
  let mut enabled = false
  let mut server_raw = ""
  let mut override_raw = ""
  for line_view in output.split("\n") {
    let line = line_view.trim().to_owned()
    if line.has_prefix("ProxyEnable") {
      if line.contains("0x1") {
        enabled = true
      }
    } else if line.has_prefix("ProxyServer") {
      match line.find("REG_SZ") {
        Some(idx) => server_raw = line[idx + 6:].trim().to_owned()
        None => ()
      }
    } else if line.has_prefix("ProxyOverride") {
      match line.find("REG_SZ") {
        Some(idx) => override_raw = line[idx + 6:].trim().to_owned()
        None => ()
      }
    }
  }
  if !enabled {
    return None
  }
  match parse_windows_proxy_server(server_raw) {
    Some(url) =>
      Some({
        url,
        source: "Windows system proxy",
        no_proxy: split_csv_hosts(override_raw),
      })
    None => None
  }
}

///|
fn get_env_first(names : Array[String]) -> (String, String)? {
  for name in names {
    match @env.get_env_var(name) {
      Some(v) if !v.trim().is_empty() =>
        return Some((name, v.trim().to_owned()))
      _ => ()
    }
  }
  None
}

///|
fn strip_quotes(s : String) -> String {
  let t = s.trim().to_owned()
  if t.length() >= 2 &&
    (
      (t.has_prefix("'") && t.has_suffix("'")) ||
      (t.has_prefix("\"") && t.has_suffix("\""))
    ) {
    t[1:t.length() - 1].to_owned()
  } else {
    t
  }
}

///|
async fn detect_macos_system_proxy() -> ProxyConfig? {
  let (code, out, _) = @process.collect_output("scutil", ["--proxy"]) catch {
    _ => return None
  }
  if code != 0 {
    return None
  }
  let txt = out.text() catch { _ => return None }
  parse_scutil_proxy_output(txt)
}

///|
async fn detect_windows_system_proxy() -> ProxyConfig? {
  let (code, out, _) = @process.collect_output("reg", [
    "query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
  ]) catch {
    _ => return None
  }
  if code != 0 {
    return None
  }
  let txt = out.text() catch { _ => return None }
  parse_windows_reg_proxy_output(txt)
}

///|
async fn detect_gnome_system_proxy() -> ProxyConfig? {
  let (mode_code, mode_out, _) = @process.collect_output("gsettings", [
    "get", "org.gnome.system.proxy", "mode",
  ]) catch {
    _ => return None
  }
  if mode_code != 0 {
    return None
  }
  let mode = strip_quotes(mode_out.text() catch { _ => "" })
  if mode != "manual" {
    return None
  }
  for proto in ["https", "http"] {
    let (host_code, host_out, _) = @process.collect_output("gsettings", [
      "get",
      "org.gnome.system.proxy.\{proto}",
      "host",
    ]) catch {
      _ => continue
    }
    let (port_code, port_out, _) = @process.collect_output("gsettings", [
      "get",
      "org.gnome.system.proxy.\{proto}",
      "port",
    ]) catch {
      _ => continue
    }
    if host_code == 0 && port_code == 0 {
      let host = strip_quotes(host_out.text() catch { _ => "" })
      let port = strip_quotes(port_out.text() catch { _ => "" })
      if !host.is_empty() && !port.is_empty() && port != "0" {
        return Some({
          url: "http://\{host}:\{port}",
          source: "GNOME system proxy",
          no_proxy: [],
        })
      }
    }
  }
  None
}

///|
async fn detect_proxy(
  cli_proxy : String?,
  no_proxy_flag : Bool,
) -> ProxyConfig? {
  if no_proxy_flag {
    return None
  }
  let env_no_proxy = match get_env_first(["NO_PROXY", "no_proxy"]) {
    Some((_, v)) => split_csv_hosts(v)
    None => []
  }
  match cli_proxy {
    Some(raw) if !raw.trim().is_empty() =>
      match normalize_proxy_url(raw) {
        Some(url) =>
          return Some({ url, source: "--proxy", no_proxy: env_no_proxy, })
        None =>
          fail("unsupported --proxy URL (expected http://host:port): \{raw}")
      }
    _ => ()
  }
  match
    get_env_first([
      "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy",
    ]) {
    Some((env_name, raw)) =>
      match normalize_proxy_url(raw) {
        Some(url) =>
          return Some({ url, source: env_name, no_proxy: env_no_proxy, })
        None => ()
      }
    None => ()
  }
  if is_windows() {
    match detect_windows_system_proxy() {
      Some(p) => return Some(p)
      None => ()
    }
  } else {
    match detect_macos_system_proxy() {
      Some(p) => return Some(p)
      None => ()
    }
    match detect_gnome_system_proxy() {
      Some(p) => return Some(p)
      None => ()
    }
  }
  None
}