"""FlyBrain-256: reference implementation and sanity tests for the OP_FLYBRAIN proposal.

A 256-bit to 256-bit function whose wiring is the fruit fly connectome used by this
project (output/full_brain_cache.npz, built by simulation/full_brain.py from
neurons.csv.gz and connections_princeton.csv.gz). It is deterministic: no simulation,
no noise, only the wiring table.

    load    input bit i goes into every sensory neuron whose rank is i mod 256
    round   s'[j] = s[j] ^ XOR(excitatory inputs) ^ (XOR(even inhibitory inputs) &
                    XOR(odd inhibitory inputs)) ^ k[t][j]
    read    output bit i = XOR of every descending neuron whose rank is i mod 256

Neurons are ordered by Root ID. The tests here are sanity checks only. Passing them
does not show the function is secure; failing them would show it is broken.

Run:  python flybrain256.py            (all tests, writes test-results.json)
      python flybrain256.py <64 hex>   (hash one 32-byte value)
"""
import csv
import gzip
import hashlib
import json
import sys
import time
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
CACHE = ROOT / "output" / "full_brain_cache.npz"
NEURONS = ROOT / "neurons.csv.gz"

ALL = np.uint64(0xFFFFFFFFFFFFFFFF)
ONE = np.uint64(1)
SHIFTS = np.arange(64, dtype=np.uint64)
MAX_ROUNDS = 64
# Fixed round count. The tests below measure three lower limits (rounds until one flipped
# input bit changes half the output, rounds until the algebra can reach full degree, hops
# for a signal to reach every reachable neuron) and check ROUNDS is at least 3x the largest.
ROUNDS = 32
# Each round can at most double the degree, so 8 rounds could reach 256. The cube test shows
# the first round adds almost nothing (sensory neurons are nearly all excitatory, so the AND
# term has nothing to work on yet): degree 10 first appears at round 5, not 4. So 9, not 8.
DEGREE_FLOOR = 9


def splitmix64(x):
    x = (x + np.uint64(0x9E3779B97F4A7C15))
    x = (x ^ (x >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
    x = (x ^ (x >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
    return x ^ (x >> np.uint64(31))


class Wiring:
    """Connections grouped by target so one round is three XOR-reductions.
    Every state word holds 64 independent runs (one per bit)."""

    def __init__(self, n, pre, post, exc, sens, desc):
        self.n, self.sens, self.desc = n, sens, desc
        order = np.lexsort((pre, post))                 # by target, then by source
        pre, post, exc = pre[order], post[order], exc[order]
        self.pre, self.post, self.exc = pre, post, exc
        self.E = self._group(pre[exc], post[exc])
        ip, iq = pre[~exc], post[~exc]
        uniq, starts, counts = np.unique(iq, return_index=True, return_counts=True)
        rank = np.arange(len(iq)) - np.repeat(starts, counts)
        even = rank % 2 == 0
        self.I0 = self._group(ip[even], iq[even])
        self.I1 = self._group(ip[~even], iq[~even])
        self.inh_in = np.zeros(n, dtype=np.int64)
        self.inh_in[uniq] = counts
        self.exc_in = np.bincount(post[exc], minlength=n)
        with np.errstate(over="ignore"):
            g = splitmix64(np.arange(n, dtype=np.uint64))
        self.k = [np.where((g >> np.uint64(t)) & ONE, ALL, np.uint64(0)).astype(np.uint64)
                  for t in range(MAX_ROUNDS)]
        self.sens_slot = np.arange(len(sens)) % 256
        self.desc_slot = np.arange(len(desc)) % 256

    @staticmethod
    def _group(pre, post):
        uniq, starts = np.unique(post, return_index=True)
        return pre, uniq, starts

    def _xor_in(self, group, s):
        pre, uniq, starts = group
        out = np.zeros(self.n, dtype=np.uint64)
        if len(pre):
            out[uniq] = np.bitwise_xor.reduceat(s[pre], starts)
        return out

    def run(self, x, rounds, checkpoints=()):
        """x: 256 words, bit b of x[i] = input bit i of run b. Returns {round: 256 words}."""
        s = np.zeros(self.n, dtype=np.uint64)
        s[self.sens] = x[self.sens_slot]
        outs = {}
        for t in range(rounds):
            a = self._xor_in(self.E, s)
            b = self._xor_in(self.I0, s)
            c = self._xor_in(self.I1, s)
            s = s ^ a ^ (b & c) ^ self.k[t]
            if t + 1 in checkpoints or t + 1 == rounds:
                out = np.zeros(256, dtype=np.uint64)
                np.bitwise_xor.at(out, self.desc_slot, s[self.desc])
                outs[t + 1] = out
        return outs


def pack(bits):
    """bits: (64, 256) bool, one row per run -> 256 words."""
    return np.bitwise_or.reduce(bits.T.astype(np.uint64) << SHIFTS, axis=1)


def unpack(words):
    """256 words -> (64, 256) bool."""
    return (((words[:, None] >> SHIFTS) & ONE).astype(bool)).T


def to_bits(data):
    return np.unpackbits(np.frombuffer(data, dtype=np.uint8), bitorder="little").astype(bool)


def to_bytes(bits):
    return np.packbits(bits.astype(np.uint8), bitorder="little").tobytes()


def flybrain256(w, data, rounds):
    assert len(data) == 32
    bits = np.zeros((64, 256), dtype=bool)
    bits[0] = to_bits(data)
    return to_bytes(unpack(w.run(pack(bits), rounds)[rounds])[0])


def hash_many(w, items, rounds):
    """Hash a list of 32-byte values, 64 at a time."""
    out = []
    for i in range(0, len(items), 64):
        chunk = items[i:i + 64]
        bits = np.zeros((64, 256), dtype=bool)
        for b, d in enumerate(chunk):
            bits[b] = to_bits(d)
        o = unpack(w.run(pack(bits), rounds)[rounds])
        out.extend(to_bytes(o[b]) for b in range(len(chunk)))
    return out


def slow_reference(w, data, rounds):
    """The same function written as plain loops, one neuron at a time, to check the fast code."""
    M = 0xFFFFFFFFFFFFFFFF

    def sm(x):
        x = (x + 0x9E3779B97F4A7C15) & M
        x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & M
        x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & M
        return x ^ (x >> 31)

    n = w.n
    bits = to_bits(data)
    s = [0] * n
    for r, j in enumerate(w.sens.tolist()):
        s[j] = int(bits[r % 256])
    edges = list(zip(w.pre.tolist(), w.post.tolist(), w.exc.tolist()))
    g = [sm(j) for j in range(n)]
    for t in range(rounds):
        a, b, c, cnt = [0] * n, [0] * n, [0] * n, [0] * n
        for p, q, e in edges:
            if e:
                a[q] ^= s[p]
            elif cnt[q] % 2 == 0:
                b[q] ^= s[p]
                cnt[q] += 1
            else:
                c[q] ^= s[p]
                cnt[q] += 1
        s = [s[j] ^ a[j] ^ (b[j] & c[j]) ^ ((g[j] >> t) & 1) for j in range(n)]
    out = [0] * 256
    for r, j in enumerate(w.desc.tolist()):
        out[r % 256] ^= s[j]
    return to_bytes(np.array(out, dtype=bool))


def lamport_demo(w, rounds):
    """A one-time signature made only from this function: sign, check, and try a forgery.
    The secrets here are throwaway test values, never real wallet keys."""
    import secrets
    sk = [secrets.token_bytes(32) for _ in range(512)]
    t = time.time()
    pk = hash_many(w, sk, rounds)
    t_keygen = time.time() - t
    msg = to_bits(hashlib.sha256(b"pay 1 coin to Bob").digest())
    sig = [sk[2 * i + int(msg[i])] for i in range(256)]
    t = time.time()
    check = hash_many(w, sig, rounds)
    t_verify = time.time() - t
    ok = all(check[i] == pk[2 * i + int(msg[i])] for i in range(256))
    other = to_bits(hashlib.sha256(b"pay 1 coin to Eve").digest())
    forged = all(check[i] == pk[2 * i + int(other[i])] for i in range(256))
    return {"signature_checks_out": ok, "same_signature_accepted_for_other_message": forged,
            "bits_that_differ_between_messages": int((msg ^ other).sum()),
            "keygen_seconds": round(t_keygen, 2), "verify_seconds": round(t_verify, 2),
            "signature_bytes": 256 * 32, "public_key_bytes": 512 * 32}


def dedupe(n, pre, post, exc):
    keep = pre != post
    pre, post, exc = pre[keep], post[keep], exc[keep]
    _, first = np.unique(pre * n + post, return_index=True)
    return pre[first], post[first], exc[first]


def load():
    z = np.load(CACHE)
    ids = z["ids"]
    n = len(ids)
    order = np.argsort(ids)
    rank = np.empty(n, dtype=np.int64)
    rank[order] = np.arange(n)
    pre_raw = np.repeat(np.arange(n), np.diff(z["indptr"]))
    pre, post = rank[pre_raw], rank[z["indices"].astype(np.int64)]
    exc = z["data"] > 0
    rows = len(pre)
    pre, post, exc = dedupe(n, pre, post, exc)
    sens = np.sort(rank[np.nonzero(z["sensory"])[0]])
    sorted_ids = ids[order]
    desc = []
    with gzip.open(NEURONS, "rt", encoding="utf-8", newline="") as f:
        r = csv.reader(f)
        h = next(r)
        ci, cs = h.index("Root ID"), h.index("Super Class")
        for row in r:
            if row[cs].strip() == "descending":
                desc.append(int(row[ci]))
    desc = np.sort(np.searchsorted(sorted_ids, np.array(desc, dtype=np.uint64)))
    return n, pre, post, exc, sens, desc, rows


def table_hash(n, w):
    h = hashlib.sha256()
    h.update(np.uint32(n).tobytes())
    h.update(w.pre.astype("<u4").tobytes())
    h.update(w.post.astype("<u4").tobytes())
    h.update(w.exc.astype(np.uint8).tobytes())
    h.update(w.sens.astype("<u4").tobytes())
    h.update(w.desc.astype("<u4").tobytes())
    return h.hexdigest()


def avalanche(w, rounds, rng, bases=2):
    """Flip one input bit, count output bits that change, after every round."""
    cps = tuple(range(1, rounds + 1))
    per_round = {r: [] for r in cps}
    positions = np.arange(256)
    for _ in range(bases):
        base = rng.integers(0, 2, 256).astype(bool)
        for start in range(0, 256, 63):
            chunk = positions[start:start + 63]
            bits = np.tile(base, (64, 1))
            for b, p in enumerate(chunk, start=1):
                bits[b, p] ^= True
            outs = w.run(pack(bits), rounds, cps)
            for r in cps:
                o = unpack(outs[r])
                per_round[r].extend((o[1:len(chunk) + 1] ^ o[0]).sum(axis=1).tolist())
    return {r: (float(np.mean(v)) / 256, float(np.min(v)) / 256, float(np.max(v)) / 256)
            for r, v in per_round.items()}


def balance(w, rounds, rng, batches=50):
    ones = np.zeros(256, dtype=np.int64)
    seen = set()
    for _ in range(batches):
        x = rng.integers(0, 2 ** 64, 256, dtype=np.uint64)
        o = unpack(w.run(x, rounds)[rounds])
        ones += o.sum(axis=0)
        seen.update(to_bytes(row) for row in o)
    total = batches * 64
    frac = ones / total
    return {"samples": total, "mean": float(frac.mean()), "worst_bit": float(np.abs(frac - 0.5).max()),
            "expected_worst_if_random": float(3.0 * 0.5 / np.sqrt(total)), "distinct_outputs": len(seen)}


def cube(w, rounds, rng, dim=10, cubes=3, cps=()):
    """XOR the outputs over every setting of `dim` input bits. A function whose
    degree is below `dim` gives all zeros; a random-looking one gives about half ones."""
    cps = tuple(sorted(set(cps) | {rounds}))
    result = {r: [] for r in cps}
    for _ in range(cubes):
        pos = rng.choice(256, dim, replace=False)
        fixed = rng.integers(0, 2, 256).astype(bool)
        acc = {r: np.zeros(256, dtype=bool) for r in cps}
        for m in range(2 ** dim // 64):
            idx = m * 64 + np.arange(64)
            bits = np.tile(fixed, (64, 1))
            for q, p in enumerate(pos):
                bits[:, p] = (idx >> q) & 1
            outs = w.run(pack(bits), rounds, cps)
            for r in cps:
                acc[r] ^= (unpack(outs[r]).sum(axis=0) % 2).astype(bool)
        for r in cps:
            result[r].append(float(acc[r].mean()))
    return {r: v for r, v in result.items()}


def reach(n, pre, post, start):
    seen = np.zeros(n, dtype=bool)
    seen[start] = True
    hops = []
    while True:
        nxt = seen.copy()
        nxt[post[seen[pre]]] = True
        if nxt.sum() == seen.sum():
            break
        seen = nxt
        hops.append(float(seen.mean()))
    return hops


def main():
    t0 = time.time()
    n, pre, post, exc, sens, desc, rows = load()
    w = Wiring(n, pre, post, exc, sens, desc)
    if len(sys.argv) > 1:
        print(flybrain256(w, bytes.fromhex(sys.argv[1]), ROUNDS).hex())
        return
    rng = np.random.default_rng(20261203)
    res = {}
    indeg = np.bincount(w.post, minlength=n)
    keys = np.sort(w.pre * n + w.post)
    rev = w.post * n + w.pre
    hit = np.searchsorted(keys, rev)
    recip = float((keys[np.minimum(hit, len(keys) - 1)] == rev).mean())
    res["wiring"] = {
        "neurons": int(n), "rows_in_file": int(rows), "connections": int(len(w.pre)),
        "excitatory": int(w.exc.sum()), "inhibitory": int((~w.exc).sum()),
        "sensory_inputs": int(len(sens)), "descending_outputs": int(len(desc)),
        "neurons_with_no_input": int((indeg == 0).sum()),
        "in_degree_median": float(np.median(indeg)), "in_degree_max": int(indeg.max()),
        "neurons_with_nonlinear_term": int((w.inh_in >= 2).sum()),
        "output_neurons_with_no_input": int((indeg[desc] == 0).sum()),
        "output_neurons_with_nonlinear_term": int((w.inh_in[desc] >= 2).sum()),
        "reciprocal_connection_fraction": recip,
        "reach_from_sensory_by_hop": reach(n, w.pre, w.post, sens),
        "packed_table_megabytes": round(len(w.pre) * 37 / 8 / 1e6, 1),
        "table_sha256": table_hash(n, w),
    }
    print("wiring", json.dumps(res["wiring"], indent=1), f"[{time.time()-t0:.0f}s]", flush=True)

    probe = 16
    av = avalanche(w, probe, rng, bases=4)
    res["avalanche_fly"] = {str(r): v for r, v in av.items()}
    rp, rq, re_ = dedupe(n, w.pre, rng.permutation(w.post), w.exc)
    wr = Wiring(n, rp, rq, re_, sens, desc)
    avr = avalanche(wr, probe, rng, bases=4)
    res["avalanche_random_rewiring"] = {str(r): v for r, v in avr.items()}
    print("avalanche (round: fly mean/min | random-wiring mean/min)")
    for r in range(1, probe + 1):
        print(f"  {r:2d}: {av[r][0]:.3f} {av[r][1]:.3f} | {avr[r][0]:.3f} {avr[r][1]:.3f}")
    # 1024 samples per round: with a perfect function the lowest sample sits near 0.40 and
    # one below 0.33 is a 5-sigma event, so 0.33 separates real weakness from sampling noise.
    def settled(a):
        return next((r for r in range(1, probe + 1)
                     if all(abs(a[q][0] - 0.5) < 0.01 and a[q][1] > 0.33 for q in range(r, probe + 1))), None)
    full, full_r = settled(av), settled(avr)
    hops = len(res["wiring"]["reach_from_sensory_by_hop"])
    res["first_full_avalanche_round_fly"] = full
    res["first_full_avalanche_round_random"] = full_r
    res["rounds"] = rounds = ROUNDS
    res["round_floors"] = {"avalanche": full, "degree": DEGREE_FLOOR, "hops": hops}
    res["rounds_at_least_3x_every_floor"] = bool(full and rounds >= 3 * max(full, DEGREE_FLOOR, hops))
    print("full avalanche from round", full, "(random wiring:", full_r, ") hops", hops,
          "-> rounds =", rounds, "margin ok:", res["rounds_at_least_3x_every_floor"],
          f"[{time.time()-t0:.0f}s]", flush=True)
    if full:
        zero, count = bytes(32), bytes(range(32))
        res["test_vectors"] = {zero.hex(): flybrain256(w, zero, rounds).hex(),
                               count.hex(): flybrain256(w, count, rounds).hex()}
        t1 = time.time()
        many = hash_many(w, [count] * 3 + [zero] + [bytes([i]) * 32 for i in range(60)], rounds)
        res["seconds_per_batch_of_64"] = round(time.time() - t1, 2)
        res["slot_independent"] = many[0].hex() == many[2].hex() == res["test_vectors"][count.hex()] and \
            many[3].hex() == res["test_vectors"][zero.hex()]
        t2 = time.perf_counter()
        for i in range(256):
            hashlib.sha256(many[i % 64]).digest()
        res["seconds_for_256_sha256"] = round(time.perf_counter() - t2, 6)
        t1 = time.time()
        res["matches_plain_loop_version_2_rounds"] = \
            slow_reference(w, count, 2) == flybrain256(w, count, 2)
        print("vectors", res["test_vectors"], "batch s", res["seconds_per_batch_of_64"],
              "slot independent", res["slot_independent"],
              "matches plain loops", res["matches_plain_loop_version_2_rounds"],
              f"({time.time()-t1:.0f}s) [{time.time()-t0:.0f}s]", flush=True)
        res["lamport_demo"] = lamport_demo(w, rounds)
        print("lamport", res["lamport_demo"], f"[{time.time()-t0:.0f}s]", flush=True)
        res["balance"] = balance(w, rounds, rng)
        print("balance", res["balance"], f"[{time.time()-t0:.0f}s]", flush=True)
        cps = tuple(r for r in (2, 3, 4, 5, 6, 8, 10, 12) if r < rounds)
        res["cube_dim10"] = {str(r): v for r, v in cube(w, rounds, rng, cubes=4, cps=cps).items()}
        print("cube", res["cube_dim10"], f"[{time.time()-t0:.0f}s]", flush=True)
    (HERE / "test-results.json").write_text(json.dumps(res, indent=1))
    print(f"done in {time.time()-t0:.0f}s")


if __name__ == "__main__":
    main()
