
include Seppo_lib
open Assrt

let _test_fkt () =
  let bifu _rs _pqs dst _src =
    let pfrt _oc =

      Ok dst in
    let ( let* ) = Result.bind in
    let* _ = File.mkdir_p File.pDir dst in
    dst |> File.out_channel_replace pfrt
  in 
  let mmk rs t : (string, string) result =
    match Make.M2.find_rule rs t with
    | Some (r,v) ->
      let j_src' = r.prerequisites |> List.hd in
      let j_src = j_src' |> Make.Jig.make in
      let src = v |> Make.Jig.paste j_src |> Option.get in
      Logr.info (fun m -> m "%s.%s %s -> %s" "Make_test" "test_fkt.build" src t);
      src |> bifu rs r.prerequisites t
    | None -> Error "no rules found to make" in 
  let rs : Make.t list = [{
      target        = "%-%/index.xml";
      prerequisites = ["app/var/db/%/%.ix"];
      fresh         = Make.Outdated;
      command       = (fun _ _ _ _ -> Error "Not implemented");
    }] in
  "o/p-0/index.xml"
  |> mmk rs
  |> Result.get_ok
  |> Assrt.equals_string __LOC__ "o/p-0/index.xml"

let test_pat () =
  let ji = "a%b%c" |> Make.Jig.make in
  match Make.Jig.cut ji "aSomebThingc" with
  | Some ["Some";"Thing"] as v ->
    Option.bind v ("A_%_B_%_C" |> Make.Jig.make |> Make.Jig.paste)
    |> Option.value ~default:"-"
    |> Assrt.equals_string __LOC__ "A_Some_B_Thing_C"
  | _ -> "Ouch" |> Assrt.equals_string __LOC__ ""

module Jig = struct
  let test_make () =
    let jig_src = "%/%.ix" |> Make.Jig.make in
    let jig_dst = "%-%/index.xml" |> Make.Jig.make in
    "o/p/2.ix"
    |> Make.Jig.cut  jig_src
    |> Option.get
    |> Make.Jig.paste jig_dst
    |> Option.get
    |> Assrt.equals_string __LOC__ "o/p-2/index.xml"

  let test_paste () =
    let jig = "%/%/%.ix" |> Make.Jig.make in
    "foo/bar/baz.ix"
    |> Make.Jig.cut jig
    |> Option.get
    |> Make.Jig.paste jig
    |> Option.get
    |> equals_string __LOC__ "foo/bar/baz.ix"
end

let _test_mk1 () =
  Logr.info (fun m -> m "%s" __LOC__);
  let r : Make.t = {
    target        = {|a/b-%.xml|};
    fresh         = Make.Outdated;
    prerequisites = [{|c/d-%.ix|}];
    command       = (fun _ _r _rz t ->
        Logr.info (fun m -> m "%s '%s'" __LOC__ t);
        t |> Assrt.equals_string __LOC__ "a/b-37.xml";
        Ok t);
  } in
  Make.M2.make [r] "a/b-37.xml"
  |> Result.get_ok
  |> Assrt.equals_string __LOC__ "a/b-37.xml"

let () =
  (* _test_fkt (); *)
  test_pat ();
  Jig.test_make ();
  Jig.test_paste ();
  (*  _test_mk1 (); *)
  assert true
