;; Tests for cek-try sequential execution
;; Bug: hydrate-island fallback leaves hydrating? scope active

(defsuite
  "cek-try-sequential"
  (deftest
    "code after cek-try runs on success"
    (let
      ((result (list)))
      (append! result "before")
      (cek-try (fn () (append! result "body") 42) (fn (e) nil))
      (append! result "after")
      (assert= 3 (len result))
      (assert= "after" (nth result 2))))
  (deftest
    "code after cek-try runs on error"
    (let
      ((result (list)))
      (append! result "before")
      (cek-try (fn () (error "boom")) (fn (e) (append! result "caught")))
      (append! result "after")
      (assert= 3 (len result))
      (assert= "after" (nth result 2))))
  (deftest
    "error in error handler propagates — skips post-try code"
    (let
      ((result (list)))
      (append! result "before")
      (guard
        (outer-err (true (append! result "outer-caught")))
        (cek-try (fn () (error "boom")) (fn (e) (error "handler-boom")))
        (append! result "after-try"))
      (assert-true (contains? result "before"))
      (assert-true (contains? result "outer-caught"))
      (assert= false (contains? result "after-try"))))
  (deftest
    "scope-pop after cek-try executes on error"
    (scope-push! "test-scope" "value")
    (cek-try (fn () (error "boom")) (fn (e) nil))
    (scope-pop! "test-scope")
    (assert= nil (scope-peek "test-scope")))
  (deftest
    "scope-push/pop balanced across cek-try error"
    (let
      ((result nil))
      (scope-push! "bal-test" "pushed")
      (cek-try (fn () (error "fail")) (fn (e) nil))
      (set! result (scope-peek "bal-test"))
      (scope-pop! "bal-test")
      (assert= "pushed" result)
      (assert= nil (scope-peek "bal-test"))))
  (deftest
    "error handler that errors skips cleanup"
    (let
      ((cleaned false))
      (scope-push! "cleanup-test" "val")
      (guard
        (e (true nil))
        (cek-try (fn () (error "first")) (fn (e) (error "second")))
        (scope-pop! "cleanup-test")
        (set! cleaned true))
      (assert= false cleaned)
      (assert= "val" (scope-peek "cleanup-test"))
      (scope-pop! "cleanup-test"))))