import pyopencl as cl
import numpy as np

# ----------------------------
# 1️⃣ Setup HDGL Lattice
# ----------------------------
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)

LATTICE_SIZE = 64 * 1024 * 1024  # 64 MB
lattice_mem = np.zeros(LATTICE_SIZE, dtype=np.uint8)
lattice_buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=lattice_mem)

print("[HDGL] Lattice initialized.")

# ----------------------------
# 2️⃣ Load Debian kernel (bzImage)
# ----------------------------
KERNEL_OFFSET = 0x100000  # 1 MB offset
with open("bzImage", "rb") as f:
    kernel_bytes = np.frombuffer(f.read(), dtype=np.uint8)

cl.enqueue_copy(queue, lattice_buf, kernel_bytes, device_offset=KERNEL_OFFSET)
print(f"[HDGL] Debian kernel loaded at 0x{KERNEL_OFFSET:X}, size: {len(kernel_bytes)} bytes.")

# ----------------------------
# 3️⃣ Minimal CPU state for real-mode
# ----------------------------
cpu_ip = 0x7C00          # typical BIOS bootloader entry
cpu_cs = 0x0000
cpu_regs = np.zeros(16, dtype=np.uint64)  # RAX-R15
cpu_flags = 0x0002        # initial FLAGS (bit 1 = reserved always set)

# ----------------------------
# 4️⃣ Real-mode instruction stub
# ----------------------------
def fetch_byte(addr):
    return lattice_mem[addr]

def execute_real_mode(opcode):
    # K.I.S.S.: Just detect JMP 0x0000:0x1000 (real mode → protected mode)
    if opcode == 0xEA:  # far JMP opcode
        # read next 4 bytes: offset (2) + segment (2)
        offset = lattice_mem[cpu_ip+1] | (lattice_mem[cpu_ip+2] << 8)
        segment = lattice_mem[cpu_ip+3] | (lattice_mem[cpu_ip+4] << 8)
        new_ip = segment << 4 | offset
        print(f"[HDGL] Far JMP to 0x{new_ip:X}")
        return new_ip
    return cpu_ip + 1

# ----------------------------
# 5️⃣ Minimal bootstrap loop
# ----------------------------
ticks = 0
while ticks < 100_000:
    opcode = fetch_byte(cpu_ip)
    cpu_ip = execute_real_mode(opcode)
    
    if ticks % 10_000 == 0:
        print(f"[Tick {ticks}] IP: 0x{cpu_ip:X}")

    ticks += 1

print("[HDGL] Minimal Debian real-mode bootstrap complete. Ready for protected mode transition.")
