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

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

(defvar *covers-dir* nil)

(defparameter +sides+ '((:front . "front")
                        (:back . "back")))

(defun sides ()
  (mapcar #'car +sides+))

(defclass cover ()
  ((id :initarg :id :reader cover-id)))

(defun make-cover (id)
  (make-instance 'cover :id id))

(defun cover-dir (cover)
  (merge-pathnames (format nil "~D/" (cover-id cover))
                   *covers-dir*))

(defun cover-path (cover side thumb-p)
  (let ((dir (cover-dir cover))
        (stem (cdr (assoc side +sides+))))
    (unless stem
      (error "Invalid side: ~A" side))

    (merge-pathnames (format nil "~A~A" stem (if thumb-p "_thumb.jpg" ".png"))
                     dir)))

(defun probe-cover-path (cover side thumb-p)
  (probe-file (cover-path cover side thumb-p)))

(defun ensure-cover-empty (cover)
  (delete-cover cover)
  (let ((dir (cover-dir cover)))
    (ensure-directories-exist dir)))

(defun delete-cover (cover)
  (let ((dir (cover-dir cover)))
    (uiop:delete-directory-tree
     dir
     :validate (lambda (path) (uiop:subpathp path *covers-dir*))
     :if-does-not-exist :ignore)))

(defun cover-exists-p (cover)
  (let ((files (loop for (side . thumb-p) in '((:front . nil) (:front . t) (:back . nil) (:back . t))
                     for path = (probe-file (cover-path cover side thumb-p))
                     when path
                       collect (cons (cons side thumb-p)  path))))
    (values (cond
              ((= 4 (length files))
               t)
              ((assoc '(:front . t) files :test #'equalp)
               :minimal)
              (t
               nil))
            files)))
