(** HTTP fetcher for SX pages.

    Uses curl via Unix.open_process_in for simplicity.
    Fetches pages from sx.rose-ash.com with SX-Request headers. *)

let base_url = "https://sx.rose-ash.com"

(** Fetch a URL and return the response body as a string. *)
let fetch_url (url : string) : string =
  let cmd = Printf.sprintf
    "curl -s -L -H 'Accept: text/sx' -H 'SX-Request: true' '%s'" url in
  let ic = Unix.open_process_in cmd in
  let buf = Buffer.create 8192 in
  (try while true do Buffer.add_char buf (input_char ic) done
   with End_of_file -> ());
  ignore (Unix.close_process_in ic);
  Buffer.contents buf

(** Fetch an SX page by path (e.g. "/sx/" or "/sx/language"). *)
let fetch_page (path : string) : string =
  let url = if String.length path > 0 && path.[0] = '/' then
    base_url ^ path
  else if String.length path > 4 && String.sub path 0 4 = "http" then
    path
  else
    base_url ^ "/" ^ path
  in
  fetch_url url

(** Read a local .sx file. *)
let read_file (path : string) : string =
  let ic = open_in path in
  let n = in_channel_length ic in
  let buf = Bytes.create n in
  really_input ic buf 0 n;
  close_in ic;
  Bytes.to_string buf
