;; Bytecode + CEK state serialization
;; Uses SX s-expression format for portability across all hosts.

;; ── Bytecode serialization ────────────────────────────────────────

(define
  bytecode-serialize
  (fn (code) (str "(sxbc 2 " (serialize code) ")")))

(define
  bytecode-deserialize
  (fn
    (s)
    (let
      ((parsed (first (sx-parse s))))
      (if
        (and (list? parsed) (>= (len parsed) 3) (= (first parsed) "sxbc"))
        (nth parsed 2)
        (error "bytecode-deserialize: invalid sxbc format")))))

;; ── CEK state serialization ───────────────────────────────────────

(define
  cek-serialize
  (fn (state) (str "(cek-state 1 " (serialize state) ")")))

(define
  cek-deserialize
  (fn
    (s)
    (let
      ((parsed (first (sx-parse s))))
      (if
        (and
          (list? parsed)
          (>= (len parsed) 3)
          (= (first parsed) "cek-state"))
        (nth parsed 2)
        (error "cek-deserialize: invalid cek-state format")))))
