import numpy as np

class HDGL_VM_32:
    def __init__(self, blend_factor=0.05):
        self.phi = 1.6180339887
        self.D = np.zeros(32)
        self.blend_factor = blend_factor
        self.ip = 0
        self.fs = {}
        self.init_filesystem()
        self.halted = False

    # -------------------------
    # Step (dummy, no analog blending)
    # -------------------------
    def step(self):
        # In a real lattice, you could implement analog blending here
        self.ip += 1

    # -------------------------
    # Full HDGL Shell
    # -------------------------
    def hdgl_shell_step(self):
        # Max buffer length = 16
        buffer = [int(d) for d in self.D[:16] if d != 0]
        if not buffer:
            return  # nothing to execute

        # Tokenize
        tokens = []
        current_token = ""
        for val in buffer:
            c = chr(val)
            if c == " ":
                if current_token:
                    tokens.append(current_token)
                    current_token = ""
            else:
                current_token += c
        if current_token:
            tokens.append(current_token)

        if not tokens:
            return

        # Dispatch command
        cmd = tokens[0]
        args = tokens[1:]

        if cmd == "echo":
            print(" ".join(args))
        elif cmd == "ls":
            print(list(self.fs.keys()))
        elif cmd == "cat":
            if args:
                print(self.fs.get(args[0], f"File '{args[0]}' not found."))
            else:
                print("cat requires filename")
        elif cmd == "exit":
            self.halted = True
        else:
            print(f"Unknown command '{cmd}'")

        # Clear input buffer after execution
        for i in range(16):
            self.D[i] = 0

    # -------------------------
    # Interactive REPL for testing
    # -------------------------
    def run_shell(self):
        print("HDGL 32-Slot Lattice Shell. Type 'exit'.")
        while not self.halted:
            cmd = input("HDGL> ")
            # Load command into D1-D16 as ASCII integers
            for i, c in enumerate(cmd[:16]):
                self.D[i] = ord(c)
            self.hdgl_shell_step()

    # -------------------------
    # Filesystem init
    # -------------------------
    def init_filesystem(self):
        self.fs['readme.txt'] = "Welcome to HDGL 32-Slot Lattice VM Shell"
        self.fs['notes.txt'] = "This is a fully lattice-native interactive shell."
        self.fs['boot.cfg'] = "kernel=hdgl-kernel.bin"

# -------------------------
# Launch
# -------------------------
if __name__ == "__main__":
    vm = HDGL_VM_32()
    vm.run_shell()
