#include <assert.h>
#include <mm/page.h>
#include <limine.h>
#include <mm/vmm.h>
#include <neobbo.h>
#include <stdatomic.h>
#include <kprint.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

struct page *pages; // "virtually sparse array", it holds all the pages between the start of the first usable address to the last one.

extern struct limine_memmap_response *memmap_response;

extern uint64_t hhdmoffset;

// Get the page object which is associated with the page that the address `addr` resides in
struct page *get_page(void *addr){
    void *canonical_addr = (void*)PAGE_ROUND_DOWN((uint64_t)addr);
    uint64_t phys_addr = kget_phys_addr(canonical_addr);

    if(phys_addr == 0){
        return NULL;
    }

    uint64_t index = phys_addr / PAGE_SIZE;
    return &pages[index];
}

void init_page_array(){

    struct limine_memmap_entry **entries = memmap_response->entries;

    size_t firstaddr = 0;
    size_t lastaddr = 0;

    for(size_t i = 0; i < memmap_response->entry_count; i++){
        switch(entries[i]->type){
            case LIMINE_MEMMAP_USABLE:
                if(firstaddr == 0){
                    firstaddr = entries[i]->base;
                    
                }else{
                    lastaddr = entries[i]->base + entries[i]->length;
                }
        }
    }

    size_t page_count = (lastaddr - firstaddr) / PAGE_SIZE;

    pages = va_alloc_contigious_pages((page_count * sizeof(struct page)) / PAGE_SIZE);

    assert(pages != NULL && "Couldn't allocate page structure");

    memset(pages, 0, (page_count * sizeof(struct page)) / PAGE_SIZE);

}