/*
 * kido-boot.c — Kido outer-kernel boot sequence.
 *
 * Power-on -> first adaptive breath, in four stages:
 *   early  : verify a sane C environment (stack works, BSS zeroed).
 *   probe  : detect what the platform actually offers (caps).
 *   adapt  : select console/timer drivers from the HAL table by caps.
 *   breath : announce on the selected console, hand off to kido_main().
 *
 * PORTABILITY LAW (compensates BUBO's x86-bound heritage):
 *  - No port I/O, no BIOS/UEFI assumptions, no inline asm in this file.
 *  - Bare-metal entry shims live OUTSIDE this file (per-arch, STUBs).
 *  - This translation unit compiles hosted (-DKIDO_HOSTED_TEST) so the
 *    boot state machine is genuinely testable on the dev machine.
 *
 * ADAPTIVITY LAW (Kido is adaptive from birth):
 *  - Drivers are chosen at boot from probed capabilities, never baked in.
 *  - Every stage returns a status; any failure halts LOUD with a code.
 *
 * Draft: STUB markers show exactly what is not yet real.
 */

#include "kido-boot.h"

#ifdef KIDO_HOSTED_TEST
#include <stdio.h>
#include <string.h>
#endif

/* Gate-approved wiring (2026-10-14): on ARM64 bare metal, adapt() fills
 * the HAL from the real per-arch HAL instead of the stub table. Board
 * identity comes from the entry shim's firmware handoff
 * (kido_entry_bootinfo) — the shim is the single source of truth, and
 * an unknown board makes fill() fail LOUD (KIDO_ERR_NO_CONSOLE) rather
 * than scribbling at a guessed UART address. */
#if defined(KIDO_ARCH_ARM64) && !defined(KIDO_HOSTED_TEST)
#include "kido-hal-arm64.h"
#include "kido-entry-arm64.h"
#endif

/* Scheduler (integration 2026-10-14): kido_main is the multitasking
 * handoff. ARM64 bare-metal and hosted only — the scheduler refuses
 * other arches by its own #error, so x86_64 bare-metal keeps the loud
 * stub in kido_main below. */
#if defined(KIDO_HOSTED_TEST) || defined(KIDO_ARCH_ARM64)
#include "kido-sched.h"
#endif

/* ------------------------------------------------------------------ */
/* Stage 0: early — is the C environment sane?                         */
/* Bare-metal note: the per-arch entry shim must set up a stack and    */
/* zero BSS *before* calling kido_boot(). This stage verifies the      */
/* result portably: a deep-ish stack frame must work, and a known      */
/* BSS sentinel must read zero.                                        */
/* ------------------------------------------------------------------ */

static uint8_t kido_bss_sentinel[64]; /* must be zero on entry */

static int kido_stack_probe(int depth)
{
    volatile char frame[256];
    frame[0] = (char)(depth & 0xFF);
    frame[255] = (char)((depth >> 8) & 0xFF);
    if (depth <= 0)
        return (int)(frame[0] ^ frame[255]);
    return kido_stack_probe(depth - 1) + (frame[0] != 0 ? 0 : 0);
}

kido_status_t kido_boot_early(void)
{
    size_t i;
    for (i = 0; i < sizeof(kido_bss_sentinel); i++) {
        if (kido_bss_sentinel[i] != 0)
            return KIDO_ERR_EARLY_ENV; /* BSS not zeroed: entry shim bug */
    }
    /* 32 nested frames x 256 bytes = 8 KiB of stack sanity. */
    if (kido_stack_probe(32) < 0)
        return KIDO_ERR_EARLY_ENV;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Stage 1: probe — what does this platform actually offer?             */
/* Compile-time arch is authoritative for the ISA; everything else is  */
/* filled by the per-arch prober. Hosted draft uses fixed test values. */
/* ------------------------------------------------------------------ */

#ifdef KIDO_HOSTED_TEST
static kido_status_t kido_probe_hosted(kido_caps_t *caps)
{
    caps->arch_name = KIDO_ARCH_NAME;
    caps->mem_base  = 0x10000000u;          /* draft test region */
    caps->mem_size  = 64u * 1024u * 1024u;  /* 64 MiB            */
    caps->timer_hz  = 1000;                 /* 1 kHz test tick   */
    caps->has_fpu   = 1;
    caps->has_mmu   = 0;                    /* hosted: N/A       */
    return KIDO_OK;
}
#endif

/* ARM64: delegate to the Gate-approved HAL prober — real CNTFRQ_EL0,
 * ID_AA64PFR0_EL1 / ID_AA64MMFR0_EL1 reads, memory from the entry
 * shim's firmware bootinfo (kido-mem fills it from the DTB during the
 * fill step). No inline asm here: the boot module stays portable per
 * its PORTABILITY LAW. mem_valid == 0 -> KIDO_ERR_STUB_REACHED, loud,
 * exactly as the HAL header contracts.
 * (Integration 2026-10-14: the old STUB returned before adapt, so
 * kido_main was unreachable on bare metal. Needs Gate ratification.) */
#if defined(KIDO_ARCH_ARM64) && !defined(KIDO_HOSTED_TEST)
static kido_status_t kido_probe_arm64(kido_caps_t *caps)
{
    if (caps == NULL)
        return KIDO_ERR_EARLY_ENV;
    return kido_hal_arm64_probe(kido_entry_bootinfo(), caps);
}
#endif

#if defined(KIDO_ARCH_X86_64) && !defined(KIDO_HOSTED_TEST)
static kido_status_t kido_probe_x86_64(kido_caps_t *caps)
{
    (void)caps;
    return KIDO_ERR_STUB_REACHED; /* STUB: multiboot/e820 parse not written */
}
#endif

kido_status_t kido_boot_probe(kido_caps_t *caps)
{
    if (caps == NULL)
        return KIDO_ERR_EARLY_ENV;
#ifdef KIDO_HOSTED_TEST
    return kido_probe_hosted(caps);
#elif defined(KIDO_ARCH_ARM64)
    return kido_probe_arm64(caps);
#elif defined(KIDO_ARCH_X86_64)
    return kido_probe_x86_64(caps);
#else
    return KIDO_ERR_EARLY_ENV; /* unreachable: header errors first */
#endif
}

/* ------------------------------------------------------------------ */
/* Stage 2: adapt — choose drivers from the HAL table by capability.   */
/* This is Kido's defining move: selection happens at boot, from       */
/* probed reality, not from compile-time assumption.                   */
/* ------------------------------------------------------------------ */

#ifdef KIDO_HOSTED_TEST
static void kido_hosted_putc(char c)            { putchar((int)c); }
static void kido_hosted_puts(const char *s)    { fputs(s, stdout); }
static uint64_t kido_hosted_ticks(void)        { return 0u; } /* STUB: clock_gettime wiring */
static uint32_t kido_hosted_hz(void)          { return 1000; }
#endif

/* STUB: bare-metal driver tables for arches with no real HAL yet
 * (ARM64 now wires the real HAL in adapt(); see below). */
#if !defined(KIDO_HOSTED_TEST) && !defined(KIDO_ARCH_ARM64)
static void kido_stub_putc(char c)          { (void)c; }
static void kido_stub_puts(const char *s)   { (void)s; }
static uint64_t kido_stub_ticks(void)       { return 0u; }
static uint32_t kido_stub_hz(void)         { return 0; }
#endif

kido_status_t kido_boot_adapt(const kido_caps_t *caps, kido_hal_t *hal)
{
    if (caps == NULL || hal == NULL)
        return KIDO_ERR_EARLY_ENV;

    if (caps->mem_size == 0)
        return KIDO_ERR_NO_MEMORY;

#ifdef KIDO_HOSTED_TEST
    hal->console_putc = kido_hosted_putc;
    hal->console_puts = kido_hosted_puts;
    hal->timer_ticks  = kido_hosted_ticks;
    hal->timer_hz     = kido_hosted_hz;
#else
#if defined(KIDO_ARCH_ARM64)
    /* Gate-approved wiring: the real per-arch HAL fills the table.
     * A non-OK fill (unknown board, stubbed UART) propagates LOUD. */
    {
        kido_status_t st = kido_hal_arm64_fill(hal,
                                               kido_entry_bootinfo()->board_id);
        if (st != KIDO_OK)
            return st;
    }
#else
    /* STUB: board-specific selection for arches with no real HAL yet. */
    hal->console_putc = kido_stub_putc;
    hal->console_puts = kido_stub_puts;
    hal->timer_ticks  = kido_stub_ticks;
    hal->timer_hz     = kido_stub_hz;
#endif
#endif

    if (hal->console_putc == NULL || hal->console_puts == NULL)
        return KIDO_ERR_NO_CONSOLE;
    if (hal->timer_ticks == NULL || hal->timer_hz() == 0)
        return KIDO_ERR_NO_TIMER;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Stage 3: breath — announce on the selected console, then hand off.  */
/* ------------------------------------------------------------------ */

kido_status_t kido_boot_breath(kido_hal_t *hal)
{
    kido_status_t st;
    if (hal == NULL)
        return KIDO_ERR_EARLY_ENV;
    hal->console_puts("\n[Kido] outer kernel, first adaptive breath\n");
    hal->console_puts("[Kido] arch: ");
    hal->console_puts(KIDO_ARCH_NAME);
    hal->console_puts(" | handing off to kido_main...\n");
    st = kido_main(hal);
    if (st != KIDO_OK)
        return KIDO_ERR_HANDOFF;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* kido_main — the kernel proper, draft 1: the multitasking handoff.  */
/* Initializes the cooperative scheduler, creates the first tasks,   */
/* and enters the run loop. Minimal by design: this is the first      */
/* multitasking boot, not a shell.                                    */
/*                                                                    */
/* Bare metal: kido_sched_run() never returns — tasks interleave via  */
/* the real ARM64 context switch; an emptied queue halts LOUD.        */
/* Hosted: no real context switch exists (ARM64-only), so each task   */
/* body runs directly to completion. True interleaving is proven      */
/* under QEMU; the hosted path proves init/create/body/DONE/empty.    */
/* (Integration seam queued by the scheduler builder; implemented     */
/* 2026-10-14 — needs Gate ratification with the prober/discover      */
/* wiring above.)                                                     */
/* ------------------------------------------------------------------ */
#if defined(KIDO_HOSTED_TEST) || defined(KIDO_ARCH_ARM64)

/* Task bodies share the boot HAL for console output; the mark char
 * arrives via arg. Four prints with yields between them. */
static const kido_hal_t *kido_main_hal;

static void kido_main_task(void *arg)
{
    char mark = (char)(uintptr_t)arg;
    int i;
    for (i = 0; i < 4; i++) {
        kido_main_hal->console_putc(mark);
        kido_sched_yield();
    }
    /* Returning marks the task DONE (kido_task_start on bare metal). */
}

#endif

kido_status_t kido_main(kido_hal_t *hal)
{
#if defined(KIDO_HOSTED_TEST) || defined(KIDO_ARCH_ARM64)
    kido_status_t st;
    uint32_t id;

    if (hal == NULL)
        return KIDO_ERR_EARLY_ENV;
    kido_main_hal = hal;

    hal->console_puts("[Kido] kido_main: scheduler init\n");
    st = kido_sched_init(hal);
    if (st != KIDO_OK)
        return st;

    st = kido_sched_create(kido_main_task, (void *)(uintptr_t)'A',
                           "alpha", &id);
    if (st != KIDO_OK)
        return st;
    st = kido_sched_create(kido_main_task, (void *)(uintptr_t)'B',
                           "beta", &id);
    if (st != KIDO_OK)
        return st;
    st = kido_sched_create(kido_main_task, (void *)(uintptr_t)'C',
                           "gamma", &id);
    if (st != KIDO_OK)
        return st;
    hal->console_puts("[Kido] kido_main: 3 tasks created\n");

#ifdef KIDO_HOSTED_TEST
    /* Hosted drive loop: pick each READY task and run its body to
     * completion directly. (kido_task_start cannot be used here — its
     * backstop yield would hit the real kido_halt and spin.) */
    for (;;) {
        kido_task_t *t = kido_sched_pick_next();
        if (t == NULL)
            break;
        t->state = KIDO_TASK_RUNNING;
        t->entry(t->arg);
        t->state = KIDO_TASK_DONE;
    }
    hal->console_puts("[Kido] kido_main: all tasks complete (hosted)\n");
    return KIDO_OK;
#else
    hal->console_puts("[Kido] kido_main: entering scheduler (never returns)\n");
    kido_sched_run();
    /* NOTREACHED — the run loop exits only via loud halt. */
    return KIDO_ERR_STUB_REACHED;
#endif

#else
    /* x86_64 bare metal: the scheduler is ARM64/hosted-only. */
    (void)hal;
    return KIDO_ERR_STUB_REACHED; /* STUB: no scheduler for this arch */
#endif
}

/* ------------------------------------------------------------------ */
/* Full sequence + loud halt.                                          */
/* ------------------------------------------------------------------ */

void kido_halt(kido_status_t code)
{
    /* Best effort: if we have no console, there is nothing to say it on.
     * Spin forever; a debugger or watchdog will find the code. */
    (void)code;
    for (;;) {
#if defined(__aarch64__) || defined(__x86_64__)
        __asm__ volatile("" ::: "memory");
#endif
    }
}

kido_status_t kido_boot(void)
{
    kido_caps_t caps;
    kido_hal_t  hal;
    kido_status_t st;

    st = kido_boot_early();
    if (st != KIDO_OK) return st;
    st = kido_boot_probe(&caps);
    if (st != KIDO_OK) return st;
    st = kido_boot_adapt(&caps, &hal);
    if (st != KIDO_OK) return st;
    st = kido_boot_breath(&hal);
    if (st != KIDO_OK) return st;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Hosted test harness: runs the REAL boot state machine on the dev    */
/* machine. Proves the stage logic; bare-metal HAL is still STUB.      */
/* ------------------------------------------------------------------ */
#ifdef KIDO_HOSTED_TEST
int main(void)
{
    kido_status_t st = kido_boot();
    /* kido_main is REAL now: scheduler init + 3 tasks driven to
     * completion on hosted (true interleaving is the QEMU proof).
     * The honest expected result is KIDO_OK (0): every stage passed,
     * handoff accepted. */
    printf("[test] kido_boot() returned %d (expect 0 = OK)\n", (int)st);
    printf("[test] early/probe/adapt/breath/main stages: %s\n",
           st == KIDO_OK ? "PASS" : "FAIL");
    return st == KIDO_OK ? 0 : 1;
}
#endif
