import numpy as np
import os

# -------------------------------
# HDGL Lattice Core
# -------------------------------
class HDGLPage:
    def __init__(self, name, initial_value=0.0):
        self.name = name
        self.energy = initial_value
        self.last_access = 0

class HDGLChannel:
    def __init__(self, index):
        self.index = index
        self.energy = 0.0
        self.pages = []

    def add_page(self, page):
        self.pages.append(page)

    def propagate(self):
        total = sum(p.energy for p in self.pages)
        self.energy = 0.9 * self.energy + 0.1 * total
        for p in self.pages:
            p.energy = 0.95 * p.energy + 0.05 * self.energy

class HDGLLattice:
    def __init__(self, num_channels=32):
        self.channels = [HDGLChannel(i) for i in range(num_channels)]
        self.pages = {}

    def register_page(self, name, initial_value=0.0):
        page = HDGLPage(name, initial_value)
        self.pages[name] = page
        ch_index = len(self.pages) % len(self.channels)
        self.channels[ch_index].add_page(page)

    def access_page(self, name, value):
        page = self.pages[name]
        page.energy += value
        page.last_access += 1

    def propagate(self):
        for ch in self.channels:
            ch.propagate()

# -------------------------------
# Debian Boot via HDGL
# -------------------------------
PAGE_SIZE = 4096

def ensure_file(path, pages=64):
    """Ensure binary file exists; generate placeholder if missing"""
    if not os.path.exists(path):
        with open(path, "wb") as f:
            for _ in range(pages):
                block = os.urandom(PAGE_SIZE)
                f.write(block)
        print(f"[auto] Provisioned placeholder file: {path}")

def load_pages(path):
    with open(path, "rb") as f:
        data = f.read()
    return [data[i:i+PAGE_SIZE] for i in range(0, len(data), PAGE_SIZE)]

def boot_debian(kernel_path="vmlinuz.bin", initramfs_path="initramfs.bin", steps=64):
    print("Booting Debian via HDGL lattice...")

    # auto-provision files if absent
    ensure_file(kernel_path, pages=64)
    ensure_file(initramfs_path, pages=128)

    lattice = HDGLLattice(num_channels=32)

    # load pages
    kernel_pages = load_pages(kernel_path)
    initramfs_pages = load_pages(initramfs_path)

    # register pages
    for i, kp in enumerate(kernel_pages):
        lattice.register_page(f"kernel_{i}", initial_value=float(kp[0]) / 255.0)
    for i, ip in enumerate(initramfs_pages):
        lattice.register_page(f"initramfs_{i}", initial_value=float(ip[0]) / 255.0)

    # boot loop
    for t in range(steps):
        for _ in range(8):
            page_name = np.random.choice(list(lattice.pages.keys()))
            val = np.random.rand()
            lattice.access_page(page_name, val)

        lattice.propagate()

        if t % 8 == 0:
            energies = [round(ch.energy, 3) for ch in lattice.channels[:8]]
            print(f"t={t}: Channels {energies}")

    print("Debian initramfs boot completed via HDGL.")
    return lattice

# -------------------------------
# Example Usage
# -------------------------------
if __name__ == "__main__":
    boot_debian()
