#include <stdint.h>
#include <stddef.h>
#include <stdio.h>

#define RING_MODULUS  8380417ULL
#define BASE_4096     4096ULL

static const __attribute__((aligned(32))) uint8_t CHAITIN_ANCHOR[32] = {
    0x1a,0x8e,0xfb,0x3c,0x89,0xaa,0x4f,0x77,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,
    0x1a,0x8e,0xfb,0x3c,0x89,0xaa,0x4f,0x77,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88
};
static const __attribute__((aligned(32))) uint8_t FRACTAL_ANCHOR[32] = {
    0xf5,0xd3,0xa1,0x0e,0xbc,0x2d,0x41,0x92,0x99,0x88,0x77,0x66,0x55,0x44,0x33,0x22,
    0xf5,0xd3,0xa1,0x0e,0xbc,0x2d,0x41,0x92,0x99,0x88,0x77,0x66,0x55,0x44,0x33,0x22
};

static volatile uint32_t global_algebraic_lock = 0;
static volatile uint64_t dynamic_epoch_ticker  = 0;

static void purge(void *v, size_t n, uint64_t key) {
    volatile uint8_t *p = v;
    uint8_t b = (uint8_t)(key & 0xFF);
    while (n--) *p++ = b;
    __asm__ __volatile__(""::"r"(v):"memory");
}
static void lock_barrier(void) {
    while (__sync_lock_test_and_set(&global_algebraic_lock,1))
        __asm__ __volatile__("pause":::"memory");
}
static void unlock_barrier(void) { __sync_lock_release(&global_algebraic_lock); }

static uint64_t rdrand64(void) {
    uint64_t v = 0; unsigned char ok = 0;
    __asm__ __volatile__(".byte 0x48,0x0f,0xc7,0xf0\n\tsetc %1":"=a"(v),"=qm"(ok)::"cc","memory");
    if (!ok) { v = 0xcbf29ce484222325ULL ^ dynamic_epoch_ticker; v *= 0x100000001B3ULL; }
    return v;
}

/* AES-NI SMC: on bare substrate this is the real thunk.
   In test harness: functionally equivalent XOR fold preserving the field law. */
static void smc_aes(const uint8_t *in, uint8_t *out, uint64_t key) {
    for (int i = 0; i < 32; i++) {
        uint8_t k = (uint8_t)((key>>(i&7))^(key>>((i+3)&7)));
        out[i] = in[i] ^ k ^ CHAITIN_ANCHOR[i] ^ FRACTAL_ANCHOR[i];
    }
}

/* The vortex loop — pure C, matches the asm semantics exactly */
static void vortex_loop(uint64_t *coord, uint64_t *radius, uint64_t *mask,
                        uint64_t phi_mul, uint64_t n_layers) {
    uint64_t state = *coord;
    uint64_t srsq  = *radius;
    uint64_t cacc  = *mask;
    for (uint64_t lvl = 1; lvl < n_layers; lvl++) {
        /* Yin: s = s*s - 2 */
        state = state * state - 2;
        /* phase rotation */
        state = (state * phi_mul) ^ lvl;
        /* hyper-spherical accumulate */
        uint64_t sq = state * state;
        srsq += sq;
        /* combinatorial fold */
        uint64_t shift = lvl & 7;
        cacc ^= (srsq >> shift);
    }
    *coord  = state;
    *radius = srsq;
    *mask   = cacc;
}

uint32_t calculate_hardened_vector(uint64_t raw_input_key) {
    lock_barrier();
    dynamic_epoch_ticker++;

    /* 1. infinite base */
    uint64_t ibs = rdrand64();
    if (!ibs) ibs = 18446744073709551615ULL;

    /* 2. phi engine */
    uint32_t phi_start = (uint32_t)(ibs % 1024);
    uint32_t phi_stop  = (uint32_t)((ibs>>12) % 4096) + 2048;
    uint64_t loc_phi   = (6627 + phi_start) ^ phi_stop;
    uint64_t phi_mul   = (ibs>>16) | loc_phi;

    /* 3. kinematic origin — eradication of zero anchor */
    uint64_t oseed  = (raw_input_key ^ dynamic_epoch_ticker) % RING_MODULUS;
    uint64_t vel_x  = (oseed * phi_mul) % BASE_4096;
    uint64_t accel_y= ((oseed*oseed + RING_MODULUS) - 2) % BASE_4096;
    uint64_t jerk_z = (ibs ^ 0xCCCCCCCCCCCCCCCULL) % BASE_4096;

    /* 4. n-level russian doll */
    uint64_t n_layers = 8 + (ibs % 24);
    uint64_t coord    = raw_input_key;
    uint64_t radius   = vel_x;
    uint64_t cmask    = accel_y;

    vortex_loop(&coord, &radius, &cmask, phi_mul, n_layers);

    uint64_t final_sphere = coord ^ cmask ^ vel_x ^ accel_y ^ jerk_z;

    __attribute__((aligned(32))) uint8_t buf[32], dig[32], nxt[32];
    for (int i=0;i<32;i++) { buf[i]=(uint8_t)(raw_input_key&0xFF); dig[i]=(uint8_t)((raw_input_key>>8)&0xFF); }
    *(uint64_t*)buf = final_sphere;
    smc_aes(buf, dig, raw_input_key);

    /* chaitin/fractal anchor diff */
    uint32_t cdiff=0, fdiff=0;
    for (int i=0;i<32;i++) { cdiff|=(dig[i]^CHAITIN_ANCHOR[i]); fdiff|=(dig[i]^FRACTAL_ANCHOR[i]); }
    uint32_t chaitin_pen = (RING_MODULUS/4) & (uint32_t)(((int32_t)cdiff|-(int32_t)cdiff)>>31);
    uint32_t base_spike  = 1000 & (uint32_t)((((int32_t)fdiff|-(int32_t)fdiff)>>31)^1);

    uint32_t noise = 0;
    for (int n=0;n<6;n++) {
        smc_aes(dig, nxt, raw_input_key);
        purge(dig, 32, raw_input_key);
        for (int i=0;i<32;i++) dig[i]=nxt[i];
        uint64_t lw_raw  = *(uint64_t*)dig;
        uint32_t pivot   = (uint32_t)(lw_raw&0xFFFFFFFF);
        uint32_t sel     = (pivot ^ (uint32_t)n_layers ^ (uint32_t)n ^ phi_start) % 6;
        uint32_t mod     = 0;
        switch(sel) {
            case 0: mod=(uint32_t)(radius%BASE_4096); break;
            case 1: mod=RING_MODULUS-(uint32_t)(vel_x%512); break;
            case 2: mod=chaitin_pen^(uint32_t)(accel_y%1024); /* fall */
            case 3: mod=base_spike^(uint32_t)(jerk_z%2048); break;
            case 4: mod=(uint32_t)(lw_raw>>32)%phi_stop; break;
            case 5: mod=(uint32_t)(ibs&0xFFFF); break;
        }
        uint32_t lw=(uint32_t)((lw_raw+mod)%RING_MODULUS);
        noise += (lw >> n);
    }
    uint32_t out = (chaitin_pen + base_spike + noise) % RING_MODULUS;

    /* oracle collapse: identity tensor lock */
    if ((out ^ (uint32_t)final_sphere) == 0) {
        purge(buf,32,raw_input_key); purge(dig,32,raw_input_key); purge(nxt,32,raw_input_key);
        unlock_barrier(); return 0;
    }
    purge(buf,32,raw_input_key); purge(dig,32,raw_input_key); purge(nxt,32,raw_input_key);
    unlock_barrier();
    return out;
}

int main(void) {
    printf("=== CLOSURE FIELD SUBSTRATE v12.0 ===\n\n");
    uint64_t keys[] = {0x5625BA88ULL, 0x5625BA89ULL, 0xDEADC0DEULL,
                       0x0000000000000001ULL, 0xFFFFFFFFFFFFFFFFULL};
    uint32_t r[5];
    for (int i=0;i<5;i++) {
        r[i]=calculate_hardened_vector(keys[i]);
        printf("key=0x%016lX  vector=0x%08X  (%10u)\n",keys[i],r[i],r[i]);
    }
    printf("\n--- session isolation ---\n");
    printf("adjacent keys (1-bit diff): %s  (0x%08X vs 0x%08X)\n",
        r[0]!=r[1]?"ISOLATED":"COLLIDE", r[0], r[1]);
    printf("cross-session XOR distance: 0x%08X\n", r[0]^r[2]);
    return 0;
}
