;; ==========================================================================
;; test-freeze.sx — Freeze scope and content addressing tests
;; ==========================================================================

(defsuite "freeze-scope"
  (deftest "freeze captures signal values"
    (let ((s (signal 42)))
      (freeze-scope "t1" (fn ()
        (freeze-signal "val" s)))
      (let ((frozen (cek-freeze-scope "t1")))
        (assert-equal "t1" (get frozen "name"))
        (assert-equal 42 (get (get frozen "signals") "val")))))

  (deftest "thaw restores signal values"
    (let ((s (signal 10)))
      (freeze-scope "t2" (fn ()
        (freeze-signal "x" s)))
      (let ((sx (freeze-to-sx "t2")))
        (reset! s 999)
        (assert-equal 999 (deref s))
        (thaw-from-sx sx)
        (assert-equal 10 (deref s)))))

  (deftest "multiple signals in scope"
    (let ((a (signal "hello"))
          (b (signal 42))
          (c (signal true)))
      (freeze-scope "t3" (fn ()
        (freeze-signal "a" a)
        (freeze-signal "b" b)
        (freeze-signal "c" c)))
      (let ((frozen (cek-freeze-scope "t3")))
        (assert-equal "hello" (get (get frozen "signals") "a"))
        (assert-equal 42 (get (get frozen "signals") "b"))
        (assert-equal true (get (get frozen "signals") "c")))))

  (deftest "freeze-to-sx round trip"
    (let ((s (signal "data")))
      (freeze-scope "t4" (fn ()
        (freeze-signal "s" s)))
      (let ((sx (freeze-to-sx "t4")))
        (assert-true (string? sx))
        (assert-true (contains? sx "data"))
        (reset! s "changed")
        (thaw-from-sx sx)
        (assert-equal "data" (deref s))))))

(defsuite "content-addressing"
  (deftest "content-hash deterministic"
    (assert-equal (content-hash "hello") (content-hash "hello")))

  (deftest "content-hash different for different input"
    (assert-false (= (content-hash "hello") (content-hash "world"))))

  (deftest "content-put and get"
    (let ((cid (content-put "test data")))
      (assert-equal "test data" (content-get cid))))

  (deftest "freeze-to-cid round trip"
    (let ((s (signal 77)))
      (freeze-scope "t5" (fn ()
        (freeze-signal "v" s)))
      (let ((cid (freeze-to-cid "t5")))
        (assert-true (string? cid))
        (reset! s 0)
        (assert-true (thaw-from-cid cid))
        (assert-equal 77 (deref s)))))

  (deftest "same state same cid"
    (let ((s (signal 42)))
      (freeze-scope "t6" (fn ()
        (freeze-signal "n" s)))
      (let ((cid1 (freeze-to-cid "t6"))
            (cid2 (freeze-to-cid "t6")))
        (assert-equal cid1 cid2)))))
