import numpy as np

class HDGLPage:
    """Represents a memory page (kernel or initramfs) flowing through HDGL."""
    def __init__(self, id, data: bytes):
        self.id = id
        self.data = np.frombuffer(data, dtype=np.uint8) / 255.0
        self.energy = np.mean(self.data)  # analog energy baseline
        self.tension = 0.0
        self.trace = self.data.copy()

    def evolve(self):
        # Analog harmonic decay and superposition
        self.trace = self.trace * 0.95 + self.data * 0.05
        self.energy = np.mean(self.trace)
        self.tension = self.energy ** 1.5  # naturally favors active pages


class HDGLInitRAMFS:
    """Dynamic initramfs mapped fully through HDGL."""
    def __init__(self, pages):
        self.pages = [HDGLPage(i, p) for i, p in enumerate(pages)]
        self.channels = [
            HDGLPage(i, np.zeros_like(pages[0])) for i in range(len(pages)//2)
        ]

    def map_pages(self):
        # Tension-driven allocation: highest tension page gets lowest tension channel
        for page in self.pages:
            ch = min(self.channels, key=lambda c: c.tension)
            ch.trace = page.trace.copy()
            ch.energy = page.energy
            ch.tension = page.tension

    def evolve(self):
        for ch in self.channels:
            ch.trace = ch.trace * 0.9 + np.mean([p.trace for p in self.pages], axis=0) * 0.1
            ch.energy = np.mean(ch.trace)
            ch.tension = ch.energy ** 1.5

    def status(self):
        return {f"channel-{ch.id}": ch.energy for ch in self.channels}


class HDGLKernel:
    """Kernel pages fully integrated into HDGL lattice."""
    def __init__(self, kernel_pages, initramfs_pages):
        self.kernel_pages = [HDGLPage(i, p) for i, p in enumerate(kernel_pages)]
        self.initramfs = HDGLInitRAMFS(initramfs_pages)
        self.channels = self.initramfs.channels + self.kernel_pages

    def boot(self):
        # Step 1: Map initramfs dynamically through lattice
        self.initramfs.map_pages()
        # Step 2: Harmonically evolve kernel and initramfs channels
        for _ in range(8):  # simulate initial bootstrap evolution
            for page in self.kernel_pages:
                page.evolve()
            self.initramfs.evolve()
        # Step 3: OS unaware; HDGL handles all page flow dynamically
        print("Debian initramfs boot routed fully through HDGL lattice.")

    def status(self):
        return {f"kernel-{p.id}": p.energy for p in self.kernel_pages} | self.initramfs.status()
