/*
 * kido-interop.h — Kido <-> BUBO inter-kernel protocol (outer seat side).
 *
 * The boundary between the doll layers. Kido holds the outer seat
 * (language ball); BUBO holds the inner seat (stable core). The protocol
 * is asymmetric by law: Kido adapts, BUBO announces. All probing, retry,
 * and solo-degradation live on Kido's side; BUBO owes the protocol one
 * behavior — answer ANNOUNCE with ANNOUNCE_ACK.
 *
 * ENVELOPE LAW: the interop envelope WRAPS kido_signal_t whole. The
 * resonate wire shape is carried, never rebuilt — kido-resonate.h is not
 * modified. Across the boundary the envelope adds exactly one routing
 * dimension: dest_kernel. Band addressing applies unchanged WITHIN the
 * destination kernel.
 *
 * DECAY LAW (MEDUSA: readable equation):
 *   strength_rx = strength_tx * (1000 - KIDO_INTEROP_HOP_LOSS_PERMILLE) / 1000
 * Applied by the RECEIVER on ingress, with hop_count incremented. The wire
 * carries what was sent (honest); decay is a receiver-measured fact.
 * In-kernel single-hop delivery stays identity (resonate's law); the
 * inter-kernel hop is the first true multi-hop.
 *
 * LINK LAW: the transport is a function-pointer table (kido_link_t), the
 * HAL pattern. No medium is named or guessed — bare metal has no driver
 * (loud stub by absence); hosted tests use a loopback pipe. Sends on an
 * uninitialized, unbound, peerless, or driverless link return loud status
 * codes from the Gate-approved set (documented mappings; no new codes —
 * a new header code is N8toriousAi's call).
 *
 * SOLO LAW: Kido boots and runs with no peer. ANNOUNCE with no ACK inside
 * the bounded wait -> SOLO state + one loud console note. Solo is a
 * state, not an error; absence is a fact.
 *
 * COOPERATIVE LAW: the ANNOUNCE wait is a bounded poll loop (max_rounds;
 * 0 = fire-and-forget, stays ANNOUNCED), never a blocking spin. No
 * ordering or duplicate guarantees are claimed — receivers must be
 * idempotent-tolerant by contract (sequence numbers would be fake
 * reliability on a link with no retransmission).
 *
 * Draft status: Kido's side is REAL and self-tested (loopback + simulated
 * peer). The real BUBO peer and the bare-metal transport medium are
 * DECLARED stubs. No bootable kernel is finalized without N8toriousAi; first
 * boot is his to witness.
 *
 * Build (hosted self-test):
 *   gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST \
 *       -DKIDO_INTEROP_SELFTEST modules/kido-interop.c -o /tmp/kido-interop-test
 */

#ifndef KIDO_INTEROP_H
#define KIDO_INTEROP_H

#include "kido-boot.h"      /* kido_status_t, kido_hal_t */
#include "kido-resonate.h"  /* kido_signal_t, the carried wire shape */

/* Envelope magic 'KIDP' + version. Mismatch -> rejected + counted. */
#define KIDO_INTEROP_MAGIC   0x4B494450u
#define KIDO_INTEROP_VERSION 1u

/* Per-hop loss in permille. 50 = 5% per inter-kernel hop. Draft value;
 * N8toriousAi tunes it. Integer math only (strength is permille). */
#define KIDO_INTEROP_HOP_LOSS_PERMILLE 50u

/* Kernel-level control packets carry no task: the kernel itself speaks. */
#define KIDO_INTEROP_KERNEL_SOURCE 0xFFFFFFFFu

/* Interop message types (the signal's `type` field). Minimal registry;
 * everything else is reserved, not guessed. */
#define KIDO_TYPE_ANNOUNCE     0x0001u
#define KIDO_TYPE_ANNOUNCE_ACK 0x0002u
#define KIDO_TYPE_SYS          0x0010u
#define KIDO_TYPE_LANG         0x0020u  /* language-ball material */

/* The two seats. Fixed; only the outer seat (Kido) adapts. */
typedef enum kido_kernel {
    KIDO_KERNEL_KIDO = 0u,  /* outer seat: this kernel */
    KIDO_KERNEL_BUBO = 1u   /* inner seat: the peer    */
} kido_kernel_t;

/* Link state machine. */
typedef enum kido_interop_state {
    KIDO_INTEROP_UNBOUND   = 0u,  /* init'd, no driver bound          */
    KIDO_INTEROP_ANNOUNCED = 1u,  /* ANNOUNCE sent, awaiting ACK      */
    KIDO_INTEROP_LINKED    = 2u,  /* peer answered; traffic may flow  */
    KIDO_INTEROP_SOLO      = 3u   /* bounded wait expired, no peer    */
} kido_interop_state_t;

/* The envelope. Wraps the resonate wire shape whole. */
typedef struct kido_packet {
    uint32_t     magic;        /* KIDO_INTEROP_MAGIC              */
    uint32_t     version;      /* KIDO_INTEROP_VERSION            */
    uint32_t     dest_kernel;  /* kido_kernel_t                   */
    uint32_t     src_kernel;   /* kido_kernel_t                   */
    uint32_t     hop_count;    /* incremented on ingress          */
    kido_signal_t signal;      /* the carried wire shape, whole   */
} kido_packet_t;

/* Link driver contract. Medium-agnostic; NULL table = no transport. */
typedef struct kido_link {
    kido_status_t (*send)(const kido_packet_t *pkt);
    kido_status_t (*recv)(kido_packet_t *pkt, uint8_t *got_out);
} kido_link_t;

/* Observable interop state. */
typedef struct kido_interop_stats {
    uint32_t state;             /* kido_interop_state_t            */
    uint32_t self_kernel;       /* kido_kernel_t                   */
    uint32_t tx_packets;        /* envelopes handed to the driver  */
    uint32_t rx_packets;        /* valid envelopes received        */
    uint32_t tx_failed;         /* driver-level send failures      */
    uint32_t rx_version_reject; /* magic/version mismatches        */
    uint32_t announces;         /* ANNOUNCE attempts               */
} kido_interop_stats_t;

/* ------------------------------------------------------------------ */
/* kido_interop_init: declare this kernel's seat. self must be a valid */
/* kido_kernel_t; hal NULL -> KIDO_ERR_EARLY_ENV. Resets all state to  */
/* UNBOUND (any bound link is dropped — re-bind after re-init).        */
/* ------------------------------------------------------------------ */
kido_status_t kido_interop_init(kido_kernel_t self, const kido_hal_t *hal);

/* ------------------------------------------------------------------ */
/* kido_interop_bind: attach the transport driver. NULL = unbind       */
/* (state -> UNBOUND). The table's function pointers are validated at  */
/* use, not at bind — a half-filled table fails loud on announce.     */
/* ------------------------------------------------------------------ */
kido_status_t kido_interop_bind(const kido_link_t *link);

/* ------------------------------------------------------------------ */
/* kido_interop_announce: the Kido side of the handshake. Sends       */
/* ANNOUNCE to BUBO, then polls up to max_rounds for ANNOUNCE_ACK.     */
/* max_rounds = 0: fire-and-forget, state stays ANNOUNCED.             */
/* ACK -> LINKED. Timeout -> SOLO + one loud console note.            */
/* Already LINKED -> KIDO_OK (idempotent). No driver (or half table)  */
/* -> KIDO_ERR_STUB_REACHED: the transport is a declared stub.        */
/* NOTE: the wait consumes whatever arrives (validated + counted);    */
/* real traffic starts after LINKED. Stated limitation, not hidden.    */
/* ------------------------------------------------------------------ */
kido_status_t kido_interop_announce(uint32_t max_rounds);

/* ------------------------------------------------------------------ */
/* kido_interop_send: wrap sig in the envelope and hand it to the      */
/* driver. Requires LINKED. UNBOUND -> KIDO_ERR_EARLY_ENV; ANNOUNCED / */
/* SOLO -> KIDO_ERR_STUB_REACHED (no peer yet / no peer — loud, never  */
/* a silent drop). sig NULL, bad dest, or strength > 1000 ->          */
/* KIDO_ERR_EARLY_ENV. Driver failure -> code propagated, tx_failed++. */
/* Refused sends (pre-driver) touch no counters: they never reached   */
/* the wire.                                                          */
/* ------------------------------------------------------------------ */
kido_status_t kido_interop_send(kido_kernel_t dest, const kido_signal_t *sig);

/* ------------------------------------------------------------------ */
/* kido_interop_recv: poll the driver for one envelope. Validates      */
/* magic + version (mismatch -> counted in rx_version_reject, got=0,  */
/* KIDO_OK — a counted result, not an error), then applies ingress    */
/* decay and hop_count++ before handing the packet out. UNBOUND or     */
/* driverless -> KIDO_ERR_EARLY_ENV. SOLO polls normally (got=0 when   */
/* the peer is absent — absence is a fact, not an error). NULL args -> */
/* KIDO_ERR_EARLY_ENV.                                                 */
/* ------------------------------------------------------------------ */
kido_status_t kido_interop_recv(kido_packet_t *out, uint8_t *got_out);

/* Observer for tests and the future world clock. */
kido_status_t kido_interop_stats(kido_interop_stats_t *out);

#endif /* KIDO_INTEROP_H */
