# grub4.py
import numpy as np

# -------------------------
# HDGL VM 32
# -------------------------
class HDGL_VM_32:
    def __init__(self, blend_factor=0.05):
        self.phi = 1.6180339887
        self.D = np.zeros(32)
        self.omega = 0.0
        self.ip = 0
        self.blend_factor = blend_factor
        self.resonance_map = [2,6,10,14,18,22,26,30]

        # History for plotting (optional)
        self.history_D = []
        self.history_omega = []

    # Step lattice once
    def step(self):
        D_prev = self.D.copy()
        for i in range(32):
            res_val = np.sum([D_prev[r] for r in self.resonance_map if r != i])
            self.D[i] = np.tanh(D_prev[i] + self.blend_factor*(D_prev[i]*self.phi + res_val + self.omega))
        self.omega += 0.01 * self.blend_factor
        self.ip += 1
        self.history_D.append(self.D.copy())
        self.history_omega.append(self.omega)

    # Print current state
    def show_state(self):
        return " ".join(f"D{i+1}:{val:.5f}" for i,val in enumerate(self.D))

# -------------------------
# Kernel-native REPL
# -------------------------
def hdgl_repl(vm):
    print("HDGL Kernel REPL Active")
    while True:
        try:
            cmd = input("HDGL> ").strip().split()
            if not cmd: continue
            instr = cmd[0].lower()
            if instr in ['exit','quit']:
                print("Halting kernel...")
                break
            elif instr=='state':
                print(vm.show_state())
            elif instr=='step':
                n = int(cmd[1]) if len(cmd)>1 else 1
                for _ in range(n):
                    vm.step()
                print(f"Stepped {n} times.")
            elif instr=='set' and len(cmd)==3:
                idx = int(cmd[1])-1
                val = float(cmd[2])
                vm.D[idx] = val
                print(f"D{idx+1} set to {val}")
            elif instr=='add' and len(cmd)==3:
                i,j = int(cmd[1])-1, int(cmd[2])-1
                vm.D[i] += vm.D[j]
                print(f"D{i+1} += D{j+1}")
            elif instr=='mul' and len(cmd)==3:
                i = int(cmd[1])-1
                val = float(cmd[2])
                vm.D[i] *= val
                print(f"D{i+1} *= {val}")
            else:
                print("Unknown command. Commands: state, step [n], set idx val, add i j, mul i val, exit")
        except Exception as e:
            print(f"Error: {e}")

# -------------------------
# Boot simulation
# -------------------------
def hdgl_kernel_boot():
    vm = HDGL_VM_32()
    # Seed lattice by stepping 20 times
    for _ in range(20):
        vm.step()
    # Launch REPL
    hdgl_repl(vm)

# -------------------------
# Launch
# -------------------------
if __name__=="__main__":
    hdgl_kernel_boot()
