///|
/// Streaming HTTPS/HTTP downloader with:
/// - System/env/CLI HTTP CONNECT proxy support
/// - Manual redirect following (301/302/303/307/308)
/// - HTTP Range resume from `.part` file
/// - Exponential-backoff retries on transient network failures
/// - Single-line in-place terminal progress bar (speed + ETA)
/// - Full SHA-256 verification before atomic commit
let download_user_agent : String = "mooncraft-launcher/0.0.1-alpha"

///|
let max_http_redirects : Int32 = 10

///|
let max_download_attempts : Int32 = 3

///|
fn make_headers(
  pairs : Array[(String, String)],
) -> Map[@http.CaseInsensitiveString, String] {
  let m : Map[@http.CaseInsensitiveString, String] = Map([])
  for p in pairs {
    m[@http.CaseInsensitiveString(p.0)] = p.1
  }
  m
}

///|
fn header_get(
  headers : Map[@http.CaseInsensitiveString, String],
  name : String,
) -> String? {
  headers.get(@http.CaseInsensitiveString(name))
}

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

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

///|
async fn open_get_stream_following_redirects(
  initial_url : String,
  proxy : ProxyConfig?,
  extra_headers : Array[(String, String)],
) -> (@http.Response, @http.Client, String) {
  let mut url = initial_url
  for _ in 0..<=max_http_redirects {
    let req_headers : Array[(String, String)] = [
      ("User-Agent", download_user_agent),
    ]
    for h in extra_headers {
      req_headers.push(h)
    }
    let (resp, client) = if should_use_proxy_for_url(proxy, url) {
      let p = proxy.unwrap()
      let (proxy_addr, proxy_hdrs) = parse_proxy_client_parts(p.url)
      let proxy_client = @http.Client::Client(proxy_addr, headers=proxy_hdrs)
      @http.get_stream(
        url,
        headers=make_headers(req_headers),
        proxy=proxy_client,
      )
    } else {
      @http.get_stream(url, headers=make_headers(req_headers))
    }
    if is_redirect_code(resp.code) {
      let loc = header_get(resp.headers, "Location")
      client.close()
      match loc {
        Some(next) if !next.is_empty() => {
          url = resolve_redirect_url(url, next)
          continue
        }
        _ =>
          fail("HTTP \{resp.code} redirect without Location header for \{url}")
      }
    }
    return (resp, client, url)
  }
  fail("too many HTTP redirects while fetching \{initial_url}")
}

///|
async fn fetch_text_following_redirects(
  url : String,
  proxy : ProxyConfig?,
) -> String {
  let (resp, client, final_url) = open_get_stream_following_redirects(
    url,
    proxy,
    [],
  )
  defer client.close()
  if resp.code != 200 {
    fail("HTTP \{resp.code} \{resp.reason} fetching \{final_url}")
  }
  let bytes = client.read_all().binary()
  @utf8.decode(bytes[:]) catch {
    _ => fail("invalid UTF-8 response from \{final_url}")
  }
}

///|
fn format_mib(bytes : Int64) -> String {
  let tenths = bytes * 10L / 1048576L
  let whole = tenths / 10L
  let frac = tenths % 10L
  "\{whole}.\{frac} MiB"
}

///|
fn format_speed(bytes_per_sec : Int64) -> String {
  if bytes_per_sec >= 1048576L {
    let tenths = bytes_per_sec * 10L / 1048576L
    "\{tenths / 10L}.\{tenths % 10L} MiB/s"
  } else if bytes_per_sec >= 1024L {
    let tenths = bytes_per_sec * 10L / 1024L
    "\{tenths / 10L}.\{tenths % 10L} KiB/s"
  } else {
    "\{bytes_per_sec} B/s"
  }
}

///|
fn two_digits(n : Int64) -> String {
  if n < 10L {
    "0\{n}"
  } else {
    "\{n}"
  }
}

///|
fn format_eta(remaining_bytes : Int64, bytes_per_sec : Int64) -> String {
  if remaining_bytes <= 0L {
    return "00:00"
  }
  if bytes_per_sec <= 0L {
    return "--:--"
  }
  let secs = remaining_bytes / bytes_per_sec
  if secs >= 3600L {
    let h = secs / 3600L
    let m = secs % 3600L / 60L
    "\{h}h\{two_digits(m)}m"
  } else {
    let m = secs / 60L
    let s = secs % 60L
    "\{two_digits(m)}:\{two_digits(s)}"
  }
}

///|
fn render_progress_bar(done : Int64, total : Int64, width : Int32) -> String {
  let filled = if total > 0L {
    let raw = (done * width.to_int64() / total).to_int()
    raw.clamp(min=0, max=width)
  } else {
    0
  }
  let sb = StringBuilder(size_hint=width * 3 + 2)
  sb.write_char('[')
  for i in 0.. String {
  let bar = render_progress_bar(done, total, 24)
  if total > 0L {
    let tenths_pct = (done * 1000L / total).clamp(min=0L, max=1000L)
    let pct_str = "\{tenths_pct / 10L}.\{tenths_pct % 10L}%"
    let eta = format_eta(total - done, speed_bps)
    "  \{label} \{bar} \{pct_str}  \{format_mib(done)} / \{format_mib(total)}  \{format_speed(speed_bps)}  ETA \{eta}"
  } else {
    "  \{label} \{format_mib(done)}  \{format_speed(speed_bps)}"
  }
}

///|
async fn write_progress_inline(line : String, finish : Bool) -> Unit {
  let suffix = if finish { "      \n" } else { "      " }
  let payload = "\r\{line}\{suffix}"
  @stdio.stdout.write(@utf8.encode(payload[:])[:])
}

///|
fn parse_content_length(
  headers : Map[@http.CaseInsensitiveString, String],
) -> Int64 {
  match header_get(headers, "Content-Length") {
    Some(s) => parse_ascii_int64(s).unwrap_or(-1L)
    None => -1L
  }
}

///|
async fn hash_file_sha256(path : String) -> (Int64, String) {
  let f = @fs.open(path, mode=ReadOnly)
  defer f.close()
  let hasher = Sha256::new()
  let buf = FixedArray::make(65536, b'\x00')
  let mut total = 0L
  while true {
    let n = f.read(buf, offset=0, max_len=65536)
    if n <= 0 {
      break
    }
    hasher.update_fixed(buf, 0, n)
    total += n.to_int64()
  }
  (total, hasher.finalize_hex())
}

///|
/// Downloads one attempt (with HTTP Range resume from `part_path` if present).
async fn download_once_resumable(
  url : String,
  part_path : String,
  label : String,
  expected_size : Int64,
  proxy : ProxyConfig?,
) -> Int64 {
  let mut resume_from = 0L
  if @fs.exists(part_path) {
    let existing = @fs.file_size(part_path) catch { _ => 0L }
    if existing > 0L && (expected_size <= 0L || existing < expected_size) {
      resume_from = existing
    } else if expected_size > 0L && existing == expected_size {
      return existing
    } else {
      @fs.remove(part_path) catch {
        _ => ()
      }
    }
  }
  let extra : Array[(String, String)] = if resume_from > 0L {
    [("Range", "bytes=\{resume_from}-")]
  } else {
    []
  }
  let (resp, client, final_url) = open_get_stream_following_redirects(
    url, proxy, extra,
  )
  defer client.close()
  let resuming = resume_from > 0L && resp.code == 206
  if resp.code == 416 && resume_from > 0L {
    @fs.remove(part_path) catch {
      _ => ()
    }
    fail("HTTP 416 resuming \{final_url}; cleared partial file")
  }
  if resp.code != 200 && !resuming {
    fail("HTTP \{resp.code} \{resp.reason} downloading \{final_url}")
  }
  let content_len = parse_content_length(resp.headers)
  let start_offset = if resuming { resume_from } else { 0L }
  let total_hint = if content_len > 0L {
    start_offset + content_len
  } else {
    expected_size
  }
  if resuming {
    println("  Resuming \{label} from \{format_mib(start_offset)}...")
  }
  let out_file = if resuming {
    @fs.open(part_path, mode=WriteOnly, append=true, create_mode=OpenOrCreate)
  } else {
    @fs.open(part_path, mode=WriteOnly, create_mode=CreateOrTruncate)
  }
  defer out_file.close()
  let buf = FixedArray::make(65536, b'\x00')
  let mut downloaded = start_offset
  let session_start_ms = @env.now()
  let mut session_bytes = 0L
  let mut last_draw_ms = 0UL
  while true {
    let n = client.read(buf, offset=0, max_len=65536)
    if n <= 0 {
      break
    }
    let chunk = Bytes::from_array(buf[:n])
    out_file.write(chunk)
    downloaded += n.to_int64()
    session_bytes += n.to_int64()
    let now_ms = @env.now()
    if now_ms >= last_draw_ms + 120UL {
      last_draw_ms = now_ms
      let elapsed_ms = if now_ms > session_start_ms {
        (now_ms - session_start_ms).reinterpret_as_int64()
      } else {
        1L
      }
      let speed = session_bytes * 1000L / elapsed_ms.max(1L)
      write_progress_inline(
        format_progress_line(label, downloaded, total_hint, speed),
        false,
      )
    }
  }
  let end_ms = @env.now()
  let total_ms = if end_ms > session_start_ms {
    (end_ms - session_start_ms).reinterpret_as_int64()
  } else {
    1L
  }
  let avg_speed = session_bytes * 1000L / total_ms.max(1L)
  write_progress_inline(
    format_progress_line(label, downloaded, total_hint, avg_speed),
    true,
  )
  downloaded
}

///|
/// Streams a remote file to `dest_path` via `.part` with resume,
/// retries, progress bar, and SHA-256 verification.
async fn download_and_verify(
  url : String,
  dest_path : String,
  label : String,
  expected_size : Int64,
  expected_sha256 : String,
  proxy : ProxyConfig?,
) -> Unit {
  let part_path = "\{dest_path}.part"
  println("Downloading \{label}...")
  println("  URL: \{url}")
  let mut last_err : Error? = None
  for attempt in 1..<=max_download_attempts {
    try {
      let downloaded = download_once_resumable(
        url, part_path, label, expected_size, proxy,
      )
      if expected_size > 0L && downloaded != expected_size {
        if downloaded > expected_size {
          @fs.remove(part_path) catch {
            _ => ()
          }
        }
        fail(
          "incomplete download for \{label}: expected \{expected_size} bytes, got \{downloaded}",
        )
      }
      println("  Verifying SHA-256 for \{label}...")
      let (disk_size, got_sha) = hash_file_sha256(part_path)
      if expected_size > 0L && disk_size != expected_size {
        @fs.remove(part_path) catch {
          _ => ()
        }
        fail(
          "size mismatch for \{label}: expected \{expected_size} bytes, got \{disk_size}",
        )
      }
      if !expected_sha256.is_empty() && got_sha != expected_sha256 {
        @fs.remove(part_path) catch {
          _ => ()
        }
        fail(
          "SHA-256 mismatch for \{label}: expected \{expected_sha256}, got \{got_sha}",
        )
      }
      @fs.rename(part_path, dest_path, replace=true)
      println(
        "  Verified \{label} (\{format_mib(disk_size)}, sha256=\{got_sha[:12]}...)",
      )
      return
    } catch {
      e => {
        last_err = Some(e)
        if attempt < max_download_attempts {
          let wait_ms = 1000 * (1 << (attempt - 1))
          println(
            "  Attempt \{attempt}/\{max_download_attempts} failed (\{e}); retrying in \{wait_ms / 1000}s...",
          )
          @async.sleep(wait_ms)
        }
      }
    }
  }
  match last_err {
    Some(e) => raise e
    None => fail("download failed for \{label}")
  }
}