/*
 * kido-resonate.h — Kido agent signaling on the resonant mesh.
 *
 * The kernel-side signaling layer: scheduler tasks are
 * transmitter-agents, signaling each other over frequency-keyed channels
 * with Lorentzian receptor selectivity. This is where Kido meets the
 * neural model — structurally, not mystically: transmit = release,
 * eta gate = resonance response, enqueue + counters = receiver state
 * change, recv + slot free = reuptake. Tasks are NOT neurons; there are
 * no activation variables here.
 *
 * ADDRESSING LAW: frequency IS the address (import://resonant-mesh).
 * transmit() addresses a band; every tuned task gets its own eta
 * evaluation. KIDO_BAND_BROADCAST evaluates all tuned tasks.
 *
 * DELIVERY LAW: eta_ji = 1/(1+(2*Q_i*(f_j-f_i)/f_i)^2), delivered iff
 * eta >= KIDO_RESONATE_DELIVERY_THRESHOLD (0.5, the half-power point).
 * Below threshold the signal is REJECTED — a result, not an error.
 * A deliverable signal that finds a full queue is DROPPED — loud.
 *
 * COOPERATIVE LAW: two delivery modes. SYNCHRONOUS (v1): delivery
 * evaluates inside transmit(); the receiver consumes at its own pace
 * via recv(). DEFERRED (this refinement): defer() releases an
 * UNEVALUATED signal into the mesh outbox; drain() delivers pending
 * entries at the caller's pace — the canonical caller is the courier
 * task (drain, yield, forever), so the mesh breathes once per
 * scheduler cycle. eta is evaluated at DRAIN time against the
 * receiver's then-current tuning (radio semantics: you hear what is
 * on when you are listening); arrival_ticks is stamped at drain.
 * No interrupts, no async, no scheduler hooks — preemption remains a
 * loud stub elsewhere. Signals never depend on kido-alloc (fenced):
 * all tables are static, including the outbox.
 *
 * Draft status: in-kernel single-hop signaling is REAL, in both modes.
 * Inter-kernel transport is DECLARED (no bus exists yet); the wire
 * shape is carried so it plugs in later. Decay is identity on one hop.
 * Coherence metrics are out of scope — the kernel signals; worlds
 * measure.
 */

#ifndef KIDO_RESONATE_H
#define KIDO_RESONATE_H

#include "kido-boot.h"   /* kido_status_t, kido_hal_t */
#include "kido-sched.h"  /* task ids, KIDO_SCHED_MAX_TASKS (include only) */

/* 515 Hz — N8toriousAi's forge constant (import://resonant-mesh). */
#define KIDO_RESONATE_FORGE_HZ 515u

/* Band 0 = untuned: never receives. Not an address. */
#define KIDO_BAND_UNTUNED 0u
/* Broadcast: every tuned task is evaluated on its own eta. */
#define KIDO_BAND_BROADCAST 0xFFFFFFFFu

/* Per-task pending queue depth. Static; the allocator is fenced. */
#define KIDO_RESONATE_QUEUE_DEPTH 8u

/* Mesh outbox depth: 4x the per-task queue depth. The mesh must hold
 * more than any single receiver can, or the door is the bottleneck
 * by construction. Static; the allocator stays fenced. */
#define KIDO_RESONATE_OUTBOX_DEPTH 32u

/* Delivery threshold: the half-power (-3 dB) point, where detuning =
 * f_rx / (2*Q). Below this, the signal is rejected. */
#define KIDO_RESONATE_DELIVERY_THRESHOLD 0.5f

/* Per-signal outcome. Rejection/dropping are results, not errors:
 * detuning is normal physics, and a full queue is a visible fact. */
typedef enum kido_sig_result {
    KIDO_SIG_DELIVERED = 0,
    KIDO_SIG_REJECTED  = 1,  /* eta below threshold — detuned        */
    KIDO_SIG_DROPPED   = 2   /* passed resonance, queue full — loud  */
} kido_sig_result_t;

/* The wire shape. Carried whole so a future inter-kernel transport
 * plugs in without changing the API. */
typedef struct kido_signal {
    uint32_t source_id;          /* transmitting task id            */
    uint32_t dest_band_hz;       /* addressed band (or BROADCAST)   */
    uint32_t type;               /* opaque message type tag         */
    uint32_t strength_permille;  /* 0..1000; decay is identity here */
    uint32_t freq_hz;            /* transmit frequency              */
    uint64_t arrival_ticks;      /* HAL timer at delivery (0 = none)*/
    float    eta;                /* computed receiver gain          */
} kido_signal_t;

/* Per-task observable signal state. This is what "receiver state
 * change" means for a task: queue contents + counters. */
typedef struct kido_resonate_stats {
    uint32_t band_hz;
    uint32_t q;
    uint32_t rx_delivered;
    uint32_t rx_rejected;
    uint32_t rx_dropped;
    uint32_t tx_sent;
    uint32_t pending;
} kido_resonate_stats_t;

/* ------------------------------------------------------------------ */
/* kido_resonate_init: reset bands (all UNTUNED), queues, counters.    */
/* hal: timer_ticks() stamps arrivals; NULL hal -> KIDO_ERR_EARLY_ENV. */
/* NULL timer_ticks -> tolerated, arrivals stamp 0 (documented).       */
/* ------------------------------------------------------------------ */
kido_status_t kido_resonate_init(const kido_hal_t *hal);

/* ------------------------------------------------------------------ */
/* kido_resonate_tune: give a task its address (band) and selectivity  */
/* (Q). Task must exist (not EMPTY). Q = 0 is defined: unselective     */
/* receiver, eta = 1.0 for all frequencies (the Lorentzian's limit).   */
/* ------------------------------------------------------------------ */
kido_status_t kido_resonate_tune(uint32_t task_id, uint32_t band_hz,
                                 uint32_t q);

/* ------------------------------------------------------------------ */
/* kido_resonate_eta: the Lorentzian receiver response, exposed for   */
/* tests and future callers. q = 0 -> 1.0f. f_rx = 0 -> 0.0f (an      */
/* untuned receiver binds nothing; never divide by zero).             */
/* float: AArch64 mandates FP; fixed-point would quantize the curve.   */
/* ------------------------------------------------------------------ */
float kido_resonate_eta(uint32_t q, uint32_t f_rx_hz, uint32_t f_tx_hz);

/* ------------------------------------------------------------------ */
/* kido_resonate_transmit: release a signal onto the mesh.             */
/* Evaluates every candidate receiver NOW (cooperative): for a band,   */
/* tasks tuned to it; for BROADCAST, every tuned task. Each computes   */
/* its own eta; >= threshold -> queued (DELIVERED), < threshold ->     */
/* REJECTED, full queue -> DROPPED. Aggregates go to the out counters  */
/* (all three required, non-NULL). src must be a live task; strength   */
/* must be <= 1000.                                                    */
/* ------------------------------------------------------------------ */
kido_status_t kido_resonate_transmit(uint32_t src_id, uint32_t dest_band_hz,
                                     uint32_t type, uint32_t strength_permille,
                                     uint32_t freq_hz,
                                     uint32_t *delivered_out,
                                     uint32_t *rejected_out,
                                     uint32_t *dropped_out);

/* ------------------------------------------------------------------ */
/* kido_resonate_recv: dequeue the oldest pending signal (reuptake:   */
/* the slot frees). KIDO_OK always on valid args; *got_out = 1 with   */
/* *out filled when a signal was pending, 0 when the queue is empty.  */
/* NULL out/got_out or unknown task -> KIDO_ERR_EARLY_ENV (loud, per   */
/* the codebase's arg-validation convention).                         */
/* ------------------------------------------------------------------ */
kido_status_t kido_resonate_recv(uint32_t task_id, kido_signal_t *out,
                                 uint8_t *got_out);

/* Observer for tests and the future world clock. */
kido_status_t kido_resonate_stats(uint32_t task_id,
                                  kido_resonate_stats_t *out);

/* ------------------------------------------------------------------ */
/* DEFERRED DELIVERY (D2 refinement, 2026-10-20). Release and delivery */
/* are split: defer() puts an UNEVALUATED signal into the mesh outbox; */
/* drain() delivers pending entries at the caller's pace. The         */
/* canonical caller is kido_resonate_courier (drain, yield, forever), */
/* so under round-robin the mesh breathes once per scheduler cycle.   */
/* No scheduler hooks: the courier is a plain task using public       */
/* create/yield. eta is evaluated at DRAIN time against live tuning;  */
/* arrival_ticks is stamped at drain.                                 */
/* ------------------------------------------------------------------ */

/* Mesh-level observable state. The door and the drain each keep
 * their own loud counters — nothing about a deferred signal is
 * silent. */
typedef struct kido_resonate_mesh_stats {
    uint32_t outbox_pending;  /* entries waiting in the mesh right now */
    uint32_t deferred_total;  /* accepted into the mesh, all time      */
    uint32_t mesh_dropped;    /* refused at the door: outbox full      */
    uint32_t dissipated;      /* drained with no tuned listener        */
} kido_resonate_mesh_stats_t;

/* ------------------------------------------------------------------ */
/* kido_resonate_defer: release a signal into the mesh WITHOUT        */
/* evaluating receivers. accepted_out = 1 (entered the mesh) or 0     */
/* (outbox full — the signal is DROPPED at the door, counted in the   */
/* mesh stats); dropped_out mirrors it. src must be a live task;      */
/* strength must be <= 1000; both out-params required non-NULL.       */
/* Accepted defers increment the sender's tx_sent (a send is a send); */
/* door-refusals do not (they never entered the mesh).                */
/* ------------------------------------------------------------------ */
kido_status_t kido_resonate_defer(uint32_t src_id, uint32_t dest_band_hz,
                                  uint32_t type, uint32_t strength_permille,
                                  uint32_t freq_hz,
                                  uint32_t *accepted_out,
                                  uint32_t *dropped_out);

/* ------------------------------------------------------------------ */
/* kido_resonate_drain: deliver every pending outbox entry, FIFO, at   */
/* the caller's pace. Each entry is evaluated against CURRENT         */
/* receiver tuning (same eta/threshold/queue-full rules as the        */
/* synchronous path — one evaluation path, no duplicated truth).      */
/* Entries with no tuned listener are consumed and counted as         */
/* dissipated. Aggregates go to the out counters (all three required, */
/* non-NULL). KIDO_OK when the outbox was walked.                     */
/* ------------------------------------------------------------------ */
kido_status_t kido_resonate_drain(uint32_t *delivered_out,
                                  uint32_t *rejected_out,
                                  uint32_t *dropped_out);

/* ------------------------------------------------------------------ */
/* kido_resonate_courier: the canonical drain-at-yield task body.     */
/* Loop: drain the mesh, yield, forever. Create it with                */
/* kido_sched_create like any task. It must NEVER return — a returned */
/* courier recycles its slot and the mesh stops breathing (that is a  */
/* bug, not a state). arg is unused.                                  */
/* ------------------------------------------------------------------ */
void kido_resonate_courier(void *arg);

/* Mesh observer for tests and the future world clock. */
kido_status_t kido_resonate_mesh_stats(kido_resonate_mesh_stats_t *out);

#endif /* KIDO_RESONATE_H */
