// Cardea Demo — Living DNA-Lattice Encryption (Phase 2)
//
// Creates a LivingKey (real FIPS 203 ML-KEM-768 keypair), evolves it through
// several generations, and demonstrates:
//   1. Encapsulate NOW → receive (ciphertext, fresh shared secret)
//   2. Evolve the key — its lattice keypair rotates every tick
//   3. Decapsulate the OLD ciphertext using the ARCHIVED past-generation sk
//   4. A "future" decapsulation attempt fails (age past archive window)
//
// Every generation the key physically changes: the DNA mutates, and the
// Kyber keypair is re-derived from the new DNA. Ciphertexts bound to the
// old generation can only be opened by the archived keypair that existed
// when they were sealed.
//
// Aislinn McCubbins, April 2026

use crypto::cardea
use crypto::dna

fn main() {
    println("══════════════════════════════════════════════════════════")
    println("  CARDEA — Living DNA-Lattice Encryption Demo (Phase 2)")
    println("  'The lock that was never the same twice.'")
    println("══════════════════════════════════════════════════════════")
    println("")

    // ── Birth ──
    println("Forging a new LivingKey from secure random entropy...")
    let key = livingkey_new()
    println("  Initial generation: 0")
    println("  Archive depth: " + int_to_str(livingkey_archive_depth(key)))

    // ── Encapsulate at generation 0 ──
    println("")
    println("── Sealing a secret at the current generation ──")
    let env_gen0 = livingkey_encapsulate(key)
    let ct_gen0 = array_get(env_gen0, 0)
    let ss_gen0 = array_get(env_gen0, 1)
    println("  Got ciphertext: " + int_to_str(cardea_ct_size()) + " bytes")
    println("  Got shared secret: " + int_to_str(cardea_ss_size()) + " bytes")
    println("  ss[0..8]:")
    let mut i = 0
    while i < 8 {
        let byte_val = t_index_get(ss_gen0, i)
        print_inline(int_to_str(byte_val) + " ")
        i = i + 1
    }
    println("")
    println("")

    // ── Evolution ──
    println("── Evolving the key through 5 ticks ──")
    let mut tick = 0
    while tick < 5 {
        key.evolve(1.0)
        tick = tick + 1
    }
    println("  After 5 ticks, generation: " + int_to_str(key.generation))
    println("  Archive depth now: " + int_to_str(livingkey_archive_depth(key)))

    // ── Encapsulate again at a NEW generation ──
    println("")
    println("── Sealing a second secret with the now-mutated key ──")
    let env_now = livingkey_encapsulate(key)
    let ct_now = array_get(env_now, 0)
    let ss_now = array_get(env_now, 1)
    println("  ss_now[0..8]:")
    let mut j = 0
    while j < 8 {
        let byte_val = t_index_get(ss_now, j)
        print_inline(int_to_str(byte_val) + " ")
        j = j + 1
    }
    println("")
    println("")

    // ── Decapsulate the CURRENT envelope with age=0 ──
    println("── Recovering the current-generation secret (age=0) ──")
    let recovered_now = livingkey_decapsulate(key, 0, ct_now)
    let sum_now = tensor_sum(recovered_now)
    if sum_now == 0.0 {
        println("  [!] decapsulation failed — bug.")
    } else {
        println("  recovered_now[0..8]:")
        let mut a = 0
        while a < 8 {
            let byte_val = t_index_get(recovered_now, a)
            print_inline(int_to_str(byte_val) + " ")
            a = a + 1
        }
        println("")
    }
    println("")

    // ── Decapsulate the OLD generation-0 envelope via archive ──
    // The gen-0 keypair lives at age = current generation (however many ticks fired).
    let age = key.generation
    println("── Recovering the old generation-0 secret via archive (age=" + int_to_str(age) + ") ──")
    let recovered_old = livingkey_decapsulate(key, age, ct_gen0)
    let sum_old = tensor_sum(recovered_old)
    if sum_old == 0.0 {
        println("  [!] archive lookup failed — bug.")
    } else {
        println("  recovered_old[0..8]:")
        let mut b = 0
        while b < 8 {
            let byte_val = t_index_get(recovered_old, b)
            print_inline(int_to_str(byte_val) + " ")
            b = b + 1
        }
        println("")
    }
    println("")

    // ── Attack: request secret from beyond archive window ──
    println("── Attack simulation: decapsulate at age 99 (beyond window) ──")
    let future_secret = livingkey_decapsulate(key, 99, ct_gen0)
    let future_sum = tensor_sum(future_secret)
    if future_sum == 0.0 {
        println("  BLOCKED — archive window refused. Good.")
    } else {
        println("  [!] returned something for age=99. Archive logic bug.")
    }
    println("")

    println("══════════════════════════════════════════════════════════")
    println("  Cardea Phase 2 demo complete.")
    println("  Real FIPS 203 ML-KEM-768 under the hood.")
    println("  The key lived. The key changed. The secret evolved.")
    println("  Every ciphertext is bound to the generation that sealed it.")
    println("══════════════════════════════════════════════════════════")
}
