"""
virtual_gpu_driver/src/memory/memory.py
Unified memory, memory mapping, paging, and buffer management for the virtual GPU system.
Backed by SQLiteMemoryManager.
"""

from .duckdb_memory_manager import DuckDBMemoryManager

class UnifiedMemoryManager:
    def __init__(self, db_path, page_size=4096):
        self.duckdb = DuckDBMemoryManager(db_path)
        self.page_size = page_size
        self.mappings = {}  # virtual_addr -> (db_key, size, flags)
        self.next_addr = 0x10000000

    def alloc(self, size, flags=None):
        db_key = self.sqlite.allocate(size)
        vaddr = self.next_addr
        self.mappings[vaddr] = (db_key, size, flags)
        self.next_addr += ((size + self.page_size - 1) // self.page_size) * self.page_size
        return vaddr

    def free(self, vaddr):
        db_key, size, _ = self.mappings.pop(vaddr)
        self.sqlite.free(db_key)

    def map(self, vaddr, size):
        # For simulation, mapping is just a lookup
        return self.mappings.get(vaddr)

    def read(self, vaddr, offset, length):
        db_key, size, _ = self.mappings[vaddr]
        return self.sqlite.read(db_key, offset, length)

    def write(self, vaddr, offset, data):
        db_key, size, _ = self.mappings[vaddr]
        self.sqlite.write(db_key, offset, data)

    def page_fault(self, vaddr):
        # Simulate page fault handling
        if vaddr not in self.mappings:
            raise RuntimeError(f"Page fault at {hex(vaddr)}")

    def stats(self):
        return self.sqlite.stats()
