(*---------------------------------------------------------------------------
   Copyright (c) 2023 Alex ␀ Maestas. All rights reserved.
   Distributed under the ISC license, see terms at the end of the file.


  ---------------------------------------------------------------------------*)

open Batteries
open Lwt
open Cohttp
open Cohttp_lwt_unix
open Protocol_conv_jsonm

module JUri = struct
  type t = Uri.t
  let to_jsonm s = Ezjsonm.string @@ Uri.to_string s
  let of_jsonm_exn s = Uri.of_string @@ Ezjsonm.get_string s
end

type follower = {
    id: string;
    username: string;
    acct: string;
    locked: bool;
    discoverable: bool option;
    note: string;
    created_at: string;
    url: JUri.t;
  } [@@deriving protocol ~driver:(module Jsonm)]

let cleanup note = String.concat "" Soup.(parse note |> trimmed_texts)

let discoverable s = match s.discoverable with
    | Some x -> string_of_bool x
    | None -> "null"

let follower_header =
  [| "id"
   ; "url"
   ; "acct"
   ; "locked"
   ; "discoverable"
   ; "created_at"
   ; "note"
  |]

let follower_to_row f =
  [| f.id
   ; Uri.to_string f.url
   ; f.acct
   ; string_of_bool f.locked
   ; discoverable f
   ; f.created_at
   ; f.note
  |]

let blocked_header =
  [| "acct"
   ; "locked"
   ; "discoverable"
   ; "created_at"
   ; "note"
  |]

let blocked_follower_to_row f =
  [| f.acct
   ; string_of_bool f.locked
   ; discoverable f
   ; f.created_at
   ; cleanup f.note
  |]


let https = Uri.make ~scheme:"https" ()
let api_path segments = String.(join "/" @@ "" :: "api" :: "v1" :: segments)
let verify_credentials = Uri.with_path https @@ api_path ["accounts"; "verify_credentials"]
let followers id = Uri.with_path https @@ api_path ["accounts"; id; "followers"]
let statuses = Uri.with_path https @@ api_path ["statuses"]

let token_basedir = Fpath.(v (XDGBaseDir.Config.user_dir ~exists:true ()) / "mastocaml")

let bearer_token_of_account account =
  let token_file = Fpath.(token_basedir / account) in
  let err m = ("Place a bearer token at " ^ Fpath.(to_string token_file) ^ " for " ^ account ^ " - " ^ m) in
  match Bos.OS.File.read_lines token_file with
  | Ok (token :: []) -> Cohttp.Auth.credential_of_string ("Bearer " ^ token)
  | Ok _ -> failwith (err "unpalatable file")
  | Error (`Msg m) -> failwith (err m)

let auth_headers ?additional_headers account =
  let token = bearer_token_of_account account in
  let headers = Option.(additional_headers |? Cohttp.Header.init ()) in
  Cohttp.Header.add_authorization headers token

let authenticated_get account ?additional_headers = Client.get ~headers:(auth_headers account ?additional_headers)
let authenticated_post account ?additional_headers = Client.post ~headers:(auth_headers account ?additional_headers)

let ensure_json_success resp body =
  let code = resp |> Response.status |> Code.code_of_status in
  let success = Code.is_success code in
  let%lwt raw_body = Cohttp_lwt.Body.to_string body in
  let json = Ezjsonm.from_string raw_body in
  if not success then
    failwith Ezjsonm.(find json ["error"] |> get_string)
  else
    Lwt.return json

let parts_of_account account =
  try String.split account ~by:"@"
  with Not_found -> failwith ("Accounts must be in the form user@host, not " ^ account)

let instance_of_account account =
  snd @@ parts_of_account account

let user_of_account account =
  fst @@ parts_of_account account

let id_of account =
  let host = instance_of_account account in
  let verify_credentials_uri = Uri.with_host verify_credentials (Some host) in
  let%lwt resp, body = authenticated_get account verify_credentials_uri in
  let%lwt json = ensure_json_success resp body in
  Lwt.return Ezjsonm.(find json ["id"] |> get_string)

(* this ensures there is either 0 or 1 `next` link. *)
let forward_link_of resp =
  let headers = Response.headers resp in
  let link_header = Option.(Header.get headers "link" |? "") in
  let all_links = Link.of_string link_header in
  let is_forward_link link =
    let link_path = Sexplib.Path.parse ".arc.relation.[0]" in
    let next_atom = Sexplib.Sexp.of_string "Next" in
    let s = Link.sexp_of_t link in
    Sexplib.(compare Path.(get ~path:link_path s) next_atom) == 0 in
  match List.filter is_forward_link all_links with
  | [] -> Uri.empty
  | link :: [] -> link.target
  | link :: links -> prerr_endline "Got too many links; returning one"; link.target

let followers_of account =
  let host = instance_of_account account in
  let%lwt id = id_of account in
  let instance_uri = Uri.with_host (followers id) (Some host) in
  let followers_uri = Uri.add_query_param instance_uri ("limit", ["100"]) in
  let do_one_page uri =
    if uri == Uri.empty then
      Lwt.return None
    else
      let%lwt resp, body = authenticated_get account uri in
      let%lwt json = ensure_json_success resp body in
      Lwt.return @@ Some (Ezjsonm.(get_list follower_of_jsonm_exn json), forward_link_of resp)
  in
  let%lwt followers = Lwt_seq.(unfold_lwt do_one_page followers_uri |> to_list) in
  Lwt.return List.(flatten followers)

let test_domain_block account blocked_instance =
  let would_be_blocked f = String.(ends_with f.acct blocked_instance) in
  let%lwt my_followers = followers_of account in
  let matching_followers = List.filter would_be_blocked my_followers in
  Lwt.return matching_followers

let form_element_of_option key opt : (string * string list) list =
  Option.(map (fun s -> (key, [s])) opt |> enum |> List.of_enum)

let status_to account ?cw ?in_reply_to status =
  let host = instance_of_account account in
  let statuses_uri = Uri.with_host statuses (Some host) in
  let form = List.flatten [
                 [("status", [status])]
               ; form_element_of_option "spoiler_text" cw
               ; form_element_of_option "in_reply_to_id" in_reply_to
               ] in
  let hashables = List.(flatten @@ map snd form) in
  let hash = Digestif.BLAKE2S.(digestv_string hashables |> to_hex) in
  let additional_headers = Cohttp.Header.init_with "Idempotency-Key" hash in
  let%lwt resp, body = authenticated_post account ~additional_headers ~body:(Cohttp_lwt.Body.of_form form) statuses_uri in
  ensure_json_success resp body

(*---------------------------------------------------------------------------
   Copyright (c) 2023 Alex ␀ Maestas

   Permission to use, copy, modify, and/or distribute this software for any
   purpose with or without fee is hereby granted, provided that the above
   copyright notice and this permission notice appear in all copies.

   THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  ---------------------------------------------------------------------------*)
