/*
 * kido-time.c — Kido monotonic clock.
 *
 * See kido-time.h for the conversion law, source law,
 * hz law, monotonicity law, init law, elapsed law, and
 * stats law. This file is the real logic in one
 * backend: the converter is pure arithmetic, the clock
 * is static BSS state plus the injected source. No asm
 * of its own exists in this leaf — its ARM64 content
 * is the timer's already-carried register reads — so
 * the hosted proof and the bare-metal build differ
 * only in which source the Gate binding names.
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror
 *        -DKIDO_HOSTED_TEST -DKIDO_TIME_SELFTEST
 *        kido-time.c -o time-selftest
 */
#include "kido-time.h"

#ifdef KIDO_TIME_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_TIME_SELFTEST needs KIDO_HOSTED_TEST."
#endif
#include <stdio.h>
#endif /* KIDO_TIME_SELFTEST */

#define KIDO_TIME_NS_PER_SEC (1000000000ULL)

/* Clock state. Static BSS: exists before any allocator.
 * The source pointer is borrowed, never owned: the
 * caller (the Gate binding's static table) outlives
 * every clock call by construction. */
static const kido_time_source_t *kido_time_src = (const kido_time_source_t *)0;
static uint32_t kido_time_hz_v = 0u;
static uint64_t kido_time_last_ns = 0u;
static uint64_t kido_time_reads = 0u;
static uint64_t kido_time_regressions = 0u;
static uint32_t kido_time_initialized = 0u;

/* ------------------------------------------------------------------ */
/* Pure converter. Both overflow guards, out untouched on             */
/* either refusal. Bound proof for the remainder multiply:            */
/* rem < hz <= 2^32 - 1, so rem * 1e9 < 4.3e18 < 2^64.                */
/* ------------------------------------------------------------------ */
kido_status_t kido_time_ticks_to_ns(uint64_t ticks, uint32_t hz,
                                     uint64_t *out)
{
    uint64_t sec;
    uint64_t sec_ns;
    uint64_t rem;
    uint64_t rem_ns;

    if (hz == 0u)
        return KIDO_ERR_EARLY_ENV;
    if (out == (uint64_t *)0)
        return KIDO_ERR_EARLY_ENV;
    sec = ticks / (uint64_t)hz;
    if (sec > (UINT64_MAX / KIDO_TIME_NS_PER_SEC))
        return KIDO_ERR_EARLY_ENV;
    sec_ns = sec * KIDO_TIME_NS_PER_SEC;
    rem = ticks % (uint64_t)hz;
    rem_ns = rem * KIDO_TIME_NS_PER_SEC / (uint64_t)hz;
    if (sec_ns > (UINT64_MAX - rem_ns))
        return KIDO_ERR_EARLY_ENV;
    *out = sec_ns + rem_ns;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Init. The source's hz failure propagates unchanged and             */
/* leaves the state untouched, so a corrected init can still          */
/* succeed. The frequency is read once: the epoch is single.          */
/* ------------------------------------------------------------------ */
kido_status_t kido_time_init(const kido_time_source_t *src)
{
    kido_status_t st;
    uint32_t hz = 0u;

    if (kido_time_initialized != 0u)
        return KIDO_ERR_EARLY_ENV;
    if (src == (const kido_time_source_t *)0)
        return KIDO_ERR_EARLY_ENV;
    if (src->now_fn == (kido_status_t (*)(uint64_t *))0)
        return KIDO_ERR_EARLY_ENV;
    if (src->hz_fn == (kido_status_t (*)(uint32_t *))0)
        return KIDO_ERR_EARLY_ENV;
    st = src->hz_fn(&hz);
    if (st != KIDO_OK)
        return st;
    if (hz == 0u)
        return KIDO_ERR_NO_TIMER;
    kido_time_src = src;
    kido_time_hz_v = hz;
    kido_time_last_ns = 0u;
    kido_time_reads = 0u;
    kido_time_regressions = 0u;
    kido_time_initialized = 1u;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Now. The clamp law: a backwards source step returns the            */
/* last value and counts a regression. A failed read counts           */
/* nothing and moves nothing.                                         */
/* ------------------------------------------------------------------ */
kido_status_t kido_time_now_ns(uint64_t *out)
{
    kido_status_t st;
    uint64_t ticks = 0u;
    uint64_t raw = 0u;

    if (kido_time_initialized == 0u)
        return KIDO_ERR_EARLY_ENV;
    if (out == (uint64_t *)0)
        return KIDO_ERR_EARLY_ENV;
    st = kido_time_src->now_fn(&ticks);
    if (st != KIDO_OK)
        return st;
    st = kido_time_ticks_to_ns(ticks, kido_time_hz_v, &raw);
    if (st != KIDO_OK)
        return st;
    if (raw < kido_time_last_ns) {
        kido_time_regressions++;
        *out = kido_time_last_ns;
    } else {
        kido_time_last_ns = raw;
        *out = raw;
    }
    kido_time_reads++;
    return KIDO_OK;
}

kido_status_t kido_time_now_us(uint64_t *out)
{
    kido_status_t st;
    uint64_t ns = 0u;

    if (out == (uint64_t *)0)
        return KIDO_ERR_EARLY_ENV;
    st = kido_time_now_ns(&ns);
    if (st != KIDO_OK)
        return st;
    *out = ns / 1000u;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Elapsed. The since-check runs after the read (the read              */
/* succeeded, so it counts), and refuses a future stamp               */
/* rather than returning the wrap complement.                         */
/* ------------------------------------------------------------------ */
kido_status_t kido_time_elapsed_ns(uint64_t since, uint64_t *out)
{
    kido_status_t st;
    uint64_t now = 0u;

    if (out == (uint64_t *)0)
        return KIDO_ERR_EARLY_ENV;
    st = kido_time_now_ns(&now);
    if (st != KIDO_OK)
        return st;
    if (since > now)
        return KIDO_ERR_EARLY_ENV;
    *out = now - since;
    return KIDO_OK;
}

kido_status_t kido_time_stats(kido_time_stats_t *out)
{
    if (kido_time_initialized == 0u)
        return KIDO_ERR_EARLY_ENV;
    if (out == (kido_time_stats_t *)0)
        return KIDO_ERR_EARLY_ENV;
    out->reads = kido_time_reads;
    out->regressions = kido_time_regressions;
    return KIDO_OK;
}

#ifdef KIDO_TIME_SELFTEST
/* ------------------------------------------------------------------ */
/* Self-test. The scripted sources live in this TU only:              */
/* the module under test never sees a test double except              */
/* through its public source table, exactly as the Gate               */
/* binding will present the real timer.                               */
/* ------------------------------------------------------------------ */
static uint64_t kido_test_count = 0u;

static kido_status_t kido_test_now_ok(uint64_t *out)
{
    *out = kido_test_count;
    return KIDO_OK;
}

static kido_status_t kido_test_hz_live(uint32_t *out)
{
    *out = 62500000u;
    return KIDO_OK;
}

static kido_status_t kido_test_hz_fail(uint32_t *out)
{
    (void)out;
    return KIDO_ERR_EARLY_ENV;
}

static kido_status_t kido_test_hz_zero(uint32_t *out)
{
    *out = 0u;
    return KIDO_OK;
}

static const kido_time_source_t kido_test_src_null_now = {
    (kido_status_t (*)(uint64_t *))0, kido_test_hz_live
};
static const kido_time_source_t kido_test_src_null_hz = {
    kido_test_now_ok, (kido_status_t (*)(uint32_t *))0
};
static const kido_time_source_t kido_test_src_fail_hz = {
    kido_test_now_ok, kido_test_hz_fail
};
static const kido_time_source_t kido_test_src_zero_hz = {
    kido_test_now_ok, kido_test_hz_zero
};
static const kido_time_source_t kido_test_src_live = {
    kido_test_now_ok, kido_test_hz_live
};

static int kido_test_checks = 0;
static int kido_test_failures = 0;

#define KIDO_CHECK(cond) do { \
    kido_test_checks++; \
    if (!(cond)) { \
        kido_test_failures++; \
        printf("FAIL line %d: %s\n", __LINE__, #cond); \
    } \
} while (0)

int kido_time_selftest_main(void)
{
    kido_status_t st;
    uint64_t v = 0u;
    uint64_t sentinel = 0u;
    kido_time_stats_t stats;

    /* Section 1: the pure converter. */
    st = kido_time_ticks_to_ns(0u, 62500000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 0u);
    st = kido_time_ticks_to_ns(62500000u, 62500000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 1000000000u);
    st = kido_time_ticks_to_ns(62500001u, 62500000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 1000000016u);
    st = kido_time_ticks_to_ns(31250000u, 62500000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 500000000u);
    st = kido_time_ticks_to_ns(1u, 1000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 1000000u);
    st = kido_time_ticks_to_ns(1500u, 1000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 1500000000u);
    st = kido_time_ticks_to_ns(1u, 3u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 333333333u);
    sentinel = 0xDEADBEEFDEADBEEFu;
    v = sentinel;
    st = kido_time_ticks_to_ns(123u, 0u, &v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV && v == sentinel);
    st = kido_time_ticks_to_ns(123u, 1000u, (uint64_t *)0);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    v = sentinel;
    st = kido_time_ticks_to_ns(UINT64_MAX, 1u, &v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV && v == sentinel);
    /* Guard two, constructed: hz = 4, sec at the cap
     * (18446744073), remainder 3 -> 750,000,000 ns
     * past a 709,551,615 ns slack. */
    v = sentinel;
    st = kido_time_ticks_to_ns(73786976295u, 4u, &v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV && v == sentinel);
    st = kido_time_ticks_to_ns(73786976292u, 4u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 18446744073000000000u);
    st = kido_time_ticks_to_ns(73786976293u, 4u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 18446744073250000000u);
    st = kido_time_ticks_to_ns(73786976294u, 4u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 18446744073500000000u);

    /* Section 2: init guards. A failed init must leave
     * the state untouched, so a corrected init succeeds. */
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_init((const kido_time_source_t *)0);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_init(&kido_test_src_null_now);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_init(&kido_test_src_null_hz);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_init(&kido_test_src_fail_hz);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_init(&kido_test_src_zero_hz);
    KIDO_CHECK(st == KIDO_ERR_NO_TIMER);
    st = kido_time_init(&kido_test_src_live);
    KIDO_CHECK(st == KIDO_OK);
    st = kido_time_init(&kido_test_src_live);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);

    /* Section 3: the clock over the scripted source
     * (hz 62,500,000; one tick = 16 ns). */
    kido_test_count = 0u;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_OK && v == 0u);
    kido_test_count = 62500000u;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_OK && v == 1000000000u);
    kido_test_count = 62500063u;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_OK && v == 1000001008u);
    /* Backwards step: clamped, counted, not refused. */
    kido_test_count = 62500000u;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_OK && v == 1000001008u);
    kido_test_count = 125000000u;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_OK && v == 2000000000u);
    /* Conversion overflow from the live source: no
     * read counted, floor untouched. */
    kido_test_count = UINT64_MAX;
    v = sentinel;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV && v == sentinel);
    kido_test_count = 125000000u;
    st = kido_time_now_ns(&v);
    KIDO_CHECK(st == KIDO_OK && v == 2000000000u);
    /* Microseconds truncate: 2000000000 ns -> 2000000 us. */
    st = kido_time_now_us(&v);
    KIDO_CHECK(st == KIDO_OK && v == 2000000u);
    kido_test_count = 125000063u;
    st = kido_time_now_us(&v);
    KIDO_CHECK(st == KIDO_OK && v == 2000001u);
    /* Elapsed: 2000001008 - 1000000000, then the
     * future-stamp refusal (the read still counts). */
    st = kido_time_elapsed_ns(1000000000u, &v);
    KIDO_CHECK(st == KIDO_OK && v == 1000001008u);
    v = sentinel;
    st = kido_time_elapsed_ns(2000001009u, &v);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV && v == sentinel);
    st = kido_time_elapsed_ns(0u, (uint64_t *)0);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    st = kido_time_now_ns((uint64_t *)0);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);
    /* Reads: 6 now_ns + 2 now_us + 2 elapsed = 10.
     * Regressions: the one backwards step. */
    st = kido_time_stats(&stats);
    KIDO_CHECK(st == KIDO_OK && stats.reads == 10u
               && stats.regressions == 1u);
    st = kido_time_stats((kido_time_stats_t *)0);
    KIDO_CHECK(st == KIDO_ERR_EARLY_ENV);

    printf("kido-time self-test: %d checks, %d failures\n",
           kido_test_checks, kido_test_failures);
    return kido_test_failures;
}

int main(void)
{
    return kido_time_selftest_main() != 0;
}
#endif /* KIDO_TIME_SELFTEST */
