;; SPDX-FileCopyrightText: 2026 Andrew Oberstar <andrew@ajoberstar.org>
;; SPDX-License-Identifier: AGPL-3.0-only

(in-package #:org.ajoberstar.quixote.openlibrary)

(defparameter headers `(("User-Agent" . ,(format nil "Quixote/~A (andrew@ajoberstar.org)"
                                                 (asdf:system-version (asdf:find-system "org.ajoberstar.quixote"))))))

(defun book-search (isbn)
  (handler-bind ((dex:http-request-not-found #'dex:ignore-and-continue))
    (let* ((json (dex:get (format nil "https://openlibrary.org/search.json?isbn=~A" isbn)
                          :headers headers))
           (data (jzon:parse json))
           (docs (gethash "docs" data))
           (doc (aref docs 0)))
      (when (gethash "numFoundExact" data)
        (model:make-book (gethash "title" doc)
                         (serapeum:string-join (gethash "author_name" doc) " and ")
                         (gethash "first_publish_year" doc)
                         nil
                         nil
                         isbn)))))

(defun cover (isbn)
  (handler-bind ((dex:http-request-not-found #'dex:ignore-and-continue))
    (dex:get (format nil "https://covers.openlibrary.org/b/isbn/~A-M.jpg" isbn
                     :headers headers))))
