;; lib/flow/api.sx — flow runtime entry points.
;;
;; Builds a Scheme env preloaded with the flow combinators (lib/flow/spec.sx),
;; the durable store + lifecycle (lib/flow/store.sx), the fed-sx remote layer
;; (lib/flow/remote.sx), and the host integration ABI (lib/flow/host.sx), and
;; provides SX helpers to run flow programs.
;;
;; Scheme-level API (available inside flow programs):
;;   (flow/start flow input) — run a flow; raw result if it completes, else
;;                             (flow-suspended id tag). Defined in store.sx.
;;   (flow/resume id value)  — resume a suspended flow (store.sx)
;;   (flow/cancel id)        — cancel a flow (store.sx)
;;   (suspend tag)           — suspension point (spec.sx)
;;   (request kind payload)  — host request envelope over suspend (host.sx)
;;   (remote-node addr fn)   — node executed on a federation peer (remote.sx)
;;
;; SX-level helpers (for hosts and tests):
;;   (flow-make-env)        — fresh standard env + combinators + store + remote + host
;;   (flow-run src)         — eval a Scheme program string in a reset shared env
;;   (flow-run-in env src)  — eval a Scheme program string in a given env
;;
;; flow-run reuses ONE env (building the full standard env is expensive) and
;; resets the mutable flow globals before each program, so tests stay isolated
;; without paying for a fresh standard env each time. flow-registry persists (it
;; models reloaded flow definitions surviving a restart).

(define
  flow-make-env
  (fn
    ()
    (let
      ((env (scheme-standard-env)))
      (flow-load-combinators! env)
      (flow-load-store! env)
      (flow-load-remote! env)
      (flow-load-host! env)
      env)))

(define
  flow-run-in
  (fn (env src) (scheme-eval-program (scheme-parse-all src) env)))

(define
  flow-reset-src
  "(set! flow-store (list)) (set! flow-next-id 0) (set! flow-replay-log (list)) (set! flow-suspend-k #f) (set! flow-timeout-budget -1) (set! flow-peers (list)) (set! flow-replicas (list))")

(define flow-env-cache false)

(define
  flow-shared-env
  (fn
    ()
    (begin
      (if flow-env-cache nil (set! flow-env-cache (flow-make-env)))
      flow-env-cache)))

(define
  flow-run
  (fn
    (src)
    (let
      ((env (flow-shared-env)))
      (begin
        (scheme-eval-program (scheme-parse-all flow-reset-src) env)
        (scheme-eval-program (scheme-parse-all src) env)))))
