;; lib/mod/tests/wire.sx — Ext 14: decision wire format + federated transport.

(define mod-w-count 0)
(define mod-w-pass 0)
(define mod-w-fail 0)
(define mod-w-failures (list))

(define
  mod-w-test!
  (fn
    (name got expected)
    (begin
      (set! mod-w-count (+ mod-w-count 1))
      (if
        (= got expected)
        (set! mod-w-pass (+ mod-w-pass 1))
        (begin
          (set! mod-w-fail (+ mod-w-fail 1))
          (append!
            mod-w-failures
            (str name "\n    expected: " expected "\n    got:      " got)))))))

;; ── split-char ──

(mod-w-test! "split on pipe" (mod/split-char "a|b|c" "|") (list "a" "b" "c"))
(mod-w-test! "split single field" (mod/split-char "abc" "|") (list "abc"))
(mod-w-test!
  "split four fields"
  (len (mod/split-char "MOD1|r1|hide|spam-hide" "|"))
  4)

;; ── serialize ──

(define
  mod-w-dec
  (mod/decide-report
    (mod/mk-report "r1" "a" "bob" "this is spam")
    (list (mod/mk-report "r1" "a" "bob" "this is spam"))
    mod/default-rules))
(define mod-w-line (mod/decision->wire mod-w-dec))

(mod-w-test!
  "wire is versioned + delimited"
  mod-w-line
  "MOD1|r1|hide|spam-hide")
(mod-w-test!
  "wire-valid? accepts well-formed"
  (mod/wire-valid? mod-w-line)
  true)
(mod-w-test!
  "wire-valid? rejects junk"
  (mod/wire-valid? "not a wire line")
  false)
(mod-w-test!
  "wire-valid? rejects wrong version"
  (mod/wire-valid? "MOD9|r1|hide|x")
  false)

;; ── round-trip ──

(define mod-w-back (mod/wire->decision mod-w-line))
(mod-w-test! "round-trip report-id" (get mod-w-back :report-id) "r1")
(mod-w-test! "round-trip action" (get mod-w-back :action) "hide")
(mod-w-test! "round-trip rule" (get mod-w-back :rule) "spam-hide")
(mod-w-test! "round-trip tags :wire" (get mod-w-back :wire) true)
(mod-w-test! "malformed → nil" (mod/wire->decision "garbage") nil)

;; ── full federated transport: serialize → wire → deserialize → trust-gate ──

(mod/fed-reset!)
(define mod-w-peer-dec (mod/wire->decision mod-w-line))

;; untrusted peer: decision is advisory, not applied
(define mod-w-recv1 (mod/fed-receive-decision "peerX" mod-w-peer-dec))
(mod-w-test!
  "wired decision from untrusted peer → advisory"
  (get mod-w-recv1 :applied)
  false)
(mod-w-test!
  "untrusted wired decision not applied locally"
  (mod/fed-applied-action "r1")
  nil)

;; trusted peer: decision binds locally
(mod/grant-trust "peerY" :mod)
(define mod-w-recv2 (mod/fed-receive-decision "peerY" mod-w-peer-dec))
(mod-w-test!
  "wired decision from trusted peer → applied"
  (get mod-w-recv2 :applied)
  true)
(mod-w-test!
  "trusted wired decision binds locally"
  (get (mod/fed-applied-action "r1") :action)
  "hide")

(define mod-wire-tests-run! (fn () {:failures mod-w-failures :total mod-w-count :passed mod-w-pass :failed mod-w-fail}))
