;; content-on-sx — Markdown document export (frontmatter + body).
;;
;; content/markdown-doc emits a YAML-ish --- frontmatter block from the document
;; metadata (title/slug/tags) followed by the Markdown body, completing the
;; metadata round-trip with md/import (md/import ∘ content/markdown-doc keeps
;; title/slug/tags). With no metadata it is just asMarkdown.
;;
;; Requires (loaded by harness): doc.sx, meta.sx (doc-title/slug/tags),
;; markdown.sx (asMarkdown).

(define mdd-nl (str "\n"))

(define
  mdd-join
  (fn
    (sep parts)
    (cond
      ((= (len parts) 0) "")
      ((= (len parts) 1) (first parts))
      (else (str (first parts) sep (mdd-join sep (rest parts)))))))

(define
  content/-fm-parts
  (fn
    (doc)
    (append
      (append
        (if
          (= (doc-title doc) nil)
          (list)
          (list (str "title: " (doc-title doc))))
        (if
          (= (doc-slug doc) nil)
          (list)
          (list (str "slug: " (doc-slug doc)))))
      (let
        ((tags (doc-tags doc)))
        (if
          (= (len tags) 0)
          (list)
          (list (str "tags: " (mdd-join ", " tags))))))))

(define
  content/-frontmatter
  (fn
    (doc)
    (let
      ((parts (content/-fm-parts doc)))
      (if
        (= (len parts) 0)
        ""
        (str "---" mdd-nl (mdd-join mdd-nl parts) mdd-nl "---")))))

(define
  content/markdown-doc
  (fn
    (doc)
    (let
      ((fm (content/-frontmatter doc)))
      (if
        (= fm "")
        (asMarkdown doc)
        (str fm mdd-nl mdd-nl (asMarkdown doc))))))
