import subprocess
import os
import numpy as np
from grub9 import HDGL_VM_32  # Your HDGL VM

# -------------------------
# VM → Linux Kernel Bootstrap
# -------------------------
class HDGL_Linux_Bridge:
    def __init__(self, vm: HDGL_VM_32, kernel_path='bzImage', initrd_path=None):
        self.vm = vm
        self.kernel_path = kernel_path
        self.initrd_path = initrd_path
        self.qemu_cmd = None

    # -------------------------
    # Map D1–D32 to VM hardware config
    # -------------------------
    def map_lattice_to_hardware(self):
        # For demo purposes, we map:
        # D1-D4 → CPU cores (max 4)
        # D5-D8 → RAM (in GB)
        cpu_cores = max(1, min(4, int(np.sum(self.vm.D[0:4])) or 1))
        ram_gb = max(1, min(8, int(np.sum(self.vm.D[4:8])) or 1))
        return cpu_cores, ram_gb

    # -------------------------
    # Build QEMU command
    # -------------------------
    def build_qemu_cmd(self):
        cpu, ram = self.map_lattice_to_hardware()
        cmd = [
            'qemu-system-x86_64',
            '-kernel', self.kernel_path,
            '-m', f'{ram}G',
            '-smp', f'{cpu}',
            '-nographic',   # Console-only
            '-append', 'console=ttyS0'  # Kernel console to QEMU stdout
        ]
        if self.initrd_path:
            cmd += ['-initrd', self.initrd_path]
        self.qemu_cmd = cmd

    # -------------------------
    # Launch Linux kernel
    # -------------------------
    def launch_kernel(self):
        self.build_qemu_cmd()
        print(f"Launching Linux with VM-seeded hardware: {self.qemu_cmd}")
        subprocess.run(self.qemu_cmd)

# -------------------------
# Example: Bootstrap
# -------------------------
if __name__=="__main__":
    vm = HDGL_VM_32()
    # Seed VM lattice (simulate analog superposition propagation)
    for _ in range(50):
        vm.step()
    vm.show_state()

    # Launch Linux kernel
    bridge = HDGL_Linux_Bridge(vm, kernel_path='bzImage', initrd_path=None)
    bridge.launch_kernel()
