;; Tests of various ways that the beastie program is called.
;;
;; This is currently quite far from complete as an interface test.
;;
;; This file is part of Beastie <https://purl.org/nxg/dist/beastie>
;; SPDX-FileCopyrightText: 2025 Norman Gray <https://nxg.me.uk>
;; SPDX-License-Identifier: BSD-2-Clause

(module "s7unit.scm" 'json 'unicode)

;; the following locale setting is a no-op when we're not using
;; ICU, but with it, the POSIX order ensures that uppercase sorts
;; before lower
(unicode-set-locale! "en_US_POSIX")    ;to ensure the sort happens predictably

(define (grep re file)
  (with-input-from-file file
    (λ ()
      (let loop ((l (read-line))
                 (res '()))
        (cond ((eof-object? l) (reverse! res))
              ((regexp-match? re l) (loop (read-line) (cons l res)))
              (else (loop (read-line) res)))))))

(test-suite
 "beastie calls"

 (let* ((bib-output (subprocess "../beastie" "bib-t01-simple.bib"))
        (bib-form (with-input-from-string bib-output read)))
     (assert-equal (sort! (map car bib-form) symbol<?)
                   '(T1-2:UPPERCASE t1-1 t3 t4)))

 (let* ((json-output (subprocess "../beastie" "-Ojson" "-Len_US_POSIX" "bib-t01-simple.bib"))
        (j (parse-json-string json-output)))
   (assert-equal (sort! (map (λ (e) (e 'key)) j)
                        ustring<?)
                 '(#"T1-2:UPPERCASE" #"t1-1" #"t3" #"t4")))

 (with-output-to-temporary-file
  "tmp-call-aux.aux"
  (λ ()
    (printf "\\relax\n\\citation{*}\n\\bibstyle{bst-t01-minimal}\n\\bibdata{bib-t01-simple}\n")))

 (let ((stdout (subprocess "../beastie" "-Len_US_POSIX" "tmp-call-aux")))
   (assert-equal stdout "")
   (let ((bbl-output (grep (regexp "\\\\bibitem") "tmp-call-aux.bbl")))
     (assert-equal bbl-output
                   '("\\bibitem{T1-2:UPPERCASE}" "\\bibitem{t1-1}" "\\bibitem{t3}" "\\bibitem{t4}"))))

 ;; The next thing to do would be to repeat that, but redirecting
 ;; stdin from the .aux file -- that should result in the .bbl being
 ;; generated to stdout.  But (subprocess...) doesn't currently
 ;; support redirecting stdin.
 )
