# harmonics2.py
import numpy as np

# -------------------------------
# HDGL Channel Definition
# -------------------------------
class HDGLChannel:
    def __init__(self, size):
        self.size = size
        self.buffer = bytearray(size)  # writable memory

    def read(self):
        return self.buffer

    def write(self, data_bytes):
        if len(data_bytes) != self.size:
            # pad or trim to fit
            data_bytes = data_bytes.ljust(self.size, b'\x00')[:self.size]
        self.buffer[:] = data_bytes

# -------------------------------
# HDGL Lattice Definition
# -------------------------------
class HDGL_Lattice:
    def __init__(self, channels):
        self.channels = channels

    def operate_on_channel(self, channel):
        # safe uint8 operations
        data = np.frombuffer(channel.read(), dtype=np.uint8).copy()
        data = (data + 1) % 256  # demo operation, avoids overflow
        channel.write(data.tobytes())

    def execute_all(self):
        for idx, ch in enumerate(self.channels):
            self.operate_on_channel(ch)
            print(f"Channel {idx+1}: first 8 bytes {list(ch.read()[:8])}")

# -------------------------------
# ELF / Initramfs Mapping
# -------------------------------
def map_bytes_to_channels(byte_data, channels, page_size=4096):
    num_pages = len(byte_data) // page_size + (len(byte_data) % page_size != 0)
    for i in range(num_pages):
        page = byte_data[i*page_size:(i+1)*page_size]
        channel = channels[i % len(channels)]  # round-robin / dynamic assignment
        channel.write(page.ljust(page_size, b'\x00'))  # pad last page

# -------------------------------
# Demo Setup: Simulated Debian ELF + Initramfs
# -------------------------------
NUM_CHANNELS = 64       # dynamic HDGL channels
PAGE_SIZE = 4096

# simulate kernel and initramfs bytes
kernel_bytes = bytearray([i % 256 for i in range(64*PAGE_SIZE)])
initramfs_bytes = bytearray([255 - (i % 256) for i in range(128*PAGE_SIZE)])

# create dynamic channels
channels = [HDGLChannel(PAGE_SIZE) for _ in range(NUM_CHANNELS)]

# map kernel + initramfs pages dynamically
map_bytes_to_channels(kernel_bytes, channels)
map_bytes_to_channels(initramfs_bytes, channels)

# -------------------------------
# Execute on HDGL Lattice
# -------------------------------
HDGL = HDGL_Lattice(channels)
print(f"Boot: Mapped {len(kernel_bytes)//PAGE_SIZE} kernel pages "
      f"and {len(initramfs_bytes)//PAGE_SIZE} initramfs pages")
HDGL.execute_all()
print("Simulation complete: Debian ELF/initramfs pages operated on successfully.")
