;; content-on-sx — document normalization.
;;
;; A cleanup pass: drop empty text blocks and empty sections across the tree.
;; Sections are normalised first, so a section that becomes empty (all children
;; dropped) is itself dropped. For tidying imported/edited documents. Immutable.
;; Inline tree handling (no section.sx dep).
;;
;; Requires (loaded by harness): block.sx, doc.sx.

(define
  norm-section?
  (fn (b) (and (st-instance? b) (= (get b :class) "CtSection"))))
(define
  norm-empty-text?
  (fn (b) (and (= (blk-type b) "text") (= (str (blk-get b "text")) ""))))
(define
  norm-empty-section?
  (fn
    (b)
    (and
      (norm-section? b)
      (let
        ((ch (st-iv-get b "children")))
        (or (= ch nil) (= (len ch) 0))))))

(define
  norm-recurse
  (fn
    (b)
    (if
      (norm-section? b)
      (let
        ((ch (st-iv-get b "children")))
        (if (list? ch) (st-iv-set! b "children" (norm-blocks ch)) b))
      b)))

(define
  norm-keep?
  (fn
    (b)
    (if (norm-empty-text? b) false (if (norm-empty-section? b) false true))))

(define
  norm-blocks
  (fn (blocks) (filter norm-keep? (map norm-recurse blocks))))

(define
  content/normalize
  (fn (doc) (doc-with-blocks doc (norm-blocks (doc-blocks doc)))))
