;; Extension — durable collaborative replication (CRDT ops on persist).
;; Replicas log independently; converge merges the logs deterministically.

(st-bootstrap-classes!)
(content-bootstrap-blocks!)
(content-bootstrap-doc!)
(content-bootstrap-render!)

(define same? (fn (a b) (= (get a :elements) (get b :elements))))
(define B (persist/open))

;; replica "a" (origin): inserts h, p
(crdt/commit!
  B
  "doc"
  "a"
  (crdt-op-insert
    "h"
    "heading"
    (crdt-pos 1 0)
    (list (list "level" 1) (list "text" "T"))
    1
    1)
  1)
(crdt/commit!
  B
  "doc"
  "a"
  (crdt-op-insert
    "p"
    "text"
    (crdt-pos 2 0)
    (list (list "text" "Body"))
    1
    1)
  1)

;; replica "b" (concurrent): edits p, inserts x
(crdt/commit-all!
  B
  "doc"
  "b"
  (list
    (crdt-op-update "p" "text" "Edited" 5 2)
    (crdt-op-insert
      "x"
      "text"
      (crdt-pos 3 0)
      (list (list "text" "X"))
      6
      2))
  5)

;; ── durability ──
(content-test
  "replica a version"
  (crdt/replica-version B "doc" "a")
  2)
(content-test
  "replica b version"
  (crdt/replica-version B "doc" "b")
  2)
(content-test
  "replica a ops len"
  (len (crdt/replica-ops B "doc" "a"))
  2)

;; ── single-replica replay ──
(content-test
  "replay a order"
  (crdt-order (crdt/replay B "doc" "a"))
  (list "h" "p"))
(content-test
  "replay a == apply-all"
  (same?
    (crdt/replay B "doc" "a")
    (crdt-apply-all (crdt-empty) (crdt/replica-ops B "doc" "a")))
  true)

;; ── converge ──
(content-test
  "converge order"
  (crdt/order B "doc" (list "a" "b"))
  (list "h" "p" "x"))
(content-test
  "converge replica-order-independent"
  (same?
    (crdt/converge B "doc" (list "a" "b"))
    (crdt/converge B "doc" (list "b" "a")))
  true)
(content-test
  "converge LWW p edited"
  (str
    (blk-send (doc-find (crdt/document B "doc" (list "a" "b")) "p") "text"))
  "Edited")
(content-test
  "converged document render"
  (asHTML (crdt/document B "doc" (list "a" "b")))
  "<h1>T</h1><p>Edited</p><p>X</p>")

;; ── duplicate delivery is idempotent ──
(crdt/commit!
  B
  "doc"
  "a"
  (crdt-op-insert
    "p"
    "text"
    (crdt-pos 2 0)
    (list (list "text" "Body"))
    1
    1)
  1)
(content-test
  "duplicate op no effect on converge"
  (crdt/order B "doc" (list "a" "b"))
  (list "h" "p" "x"))
(content-test
  "duplicate keeps LWW value"
  (str
    (blk-send (doc-find (crdt/document B "doc" (list "a" "b")) "p") "text"))
  "Edited")

;; ── new op on a replica is reflected after re-converge ──
(crdt/commit! B "doc" "b" (crdt-op-delete "h") 9)
(content-test
  "delete reflected after reconverge"
  (crdt/order B "doc" (list "a" "b"))
  (list "p" "x"))

;; ── isolation: unknown doc converges to empty ──
(content-test
  "unknown doc empty"
  (crdt/order B "other" (list "a" "b"))
  (list))
(content-test
  "unknown replica empty ops"
  (len (crdt/replica-ops B "doc" "zzz"))
  0)
