(ns sydnix-cli.commands.help
  (:require
   [babashka.process :as p]
   [sydnix-cli.mangen :as mangen]))

(defn adorn-with-help-option [wrapped-command-fn]
  (fn [{:keys [opts dispatch]}]
    (if (:help opts)
      (mangen/with-pipe
        (fn [man->]
          (mangen/write-man-for-command (mangen/find-dispatched dispatch)
                                        :out man->))
        (fn [->man]
          (p/shell {:in ->man}
                   "man -l -")))
      (wrapped-command-fn opts))))

(defn- view-man-for-command [command-spec]
  (mangen/with-pipe
    (fn [man->]
      (mangen/write-man-for-command command-spec :out man->))
    (fn [->man]
      (p/shell {:in ->man} "man -l -"))))

(defn- wrap-command-fn [wrapped-fn]
  (fn [info]
    (if (:help (:opts info))
      (do (mangen/render-docs-for-command
           (mangen/find-dispatched (:dispatch info)))
          #_
          (view-man-for-command (mangen/find-dispatched (:dispatch info))))
      (when-not (nil? wrapped-fn)
        (wrapped-fn info)))))

(defn adorn-with-help-option* [command-spec]
  (update command-spec :fn wrap-command-fn))

(defn- command-fn [_opts]
  (view-man-for-command (mangen/find-dispatched [])))

(def command
  {:cmds ["help"]
   :fn command-fn})
