#include <stdint.h>
#include <stddef.h>
#include <limine.h>
#include "bootinfo.h"
#include "hal/hal.h"

BootInfo BOOT_INFO;

#define DEFINE_REQ(partname, partid) \
  static volatile struct limine_##partname##_request partname##_req = \
    { .id = LIMINE_##partid##_REQUEST, .revision = 0 }

static volatile struct limine_paging_mode_request paging_req = {
  .id = LIMINE_PAGING_MODE_REQUEST,
  .revision = 0,
  .mode = LIMINE_PAGING_MODE_X86_64_4LVL,
};

DEFINE_REQ(kernel_address, KERNEL_ADDRESS);
DEFINE_REQ(hhdm, HHDM);
DEFINE_REQ(memmap, MEMMAP);
DEFINE_REQ(smp, SMP);
DEFINE_REQ(rsdp, RSDP);
DEFINE_REQ(framebuffer, FRAMEBUFFER);
DEFINE_REQ(module, MODULE);

void bootinfo_init(void) {
  if (framebuffer_req.response == NULL || framebuffer_req.response->framebuffer_count < 1) {
    hal_hang();
  }
  BOOT_INFO.fb = framebuffer_req.response->framebuffers[0];

  struct limine_module_response *modulesres= module_req.response;
  BOOT_INFO.modules = modulesres;

  struct limine_paging_mode_response *pagingres = paging_req.response;
  if (pagingres->mode != LIMINE_PAGING_MODE_X86_64_4LVL) {
    hal_hang();
  }

  struct limine_hhdm_response *hhdmres = hhdm_req.response;
  BOOT_INFO.hhdm_off = hhdmres->offset;

  struct limine_kernel_address_response *kernaddrres = kernel_address_req.response;
  BOOT_INFO.kern_virtbase = kernaddrres->virtual_base;
  BOOT_INFO.kern_physbase = kernaddrres->physical_base;

  struct limine_memmap_response *memmapres = memmap_req.response;
  BOOT_INFO.memmap_entries = memmapres->entries;
  BOOT_INFO.memmap_entrycount = memmapres->entry_count;

  BOOT_INFO.memmap_total = 0;
  for (size_t i = 0; i < memmapres->entry_count; i++) {
    struct limine_memmap_entry *entry = memmapres->entries[i];
    if (entry->type != LIMINE_MEMMAP_RESERVED) {
      BOOT_INFO.memmap_total += entry->length;
    }
  }

  struct limine_smp_response *smpres = smp_req.response;
  BOOT_INFO.smp = smpres;

  BOOT_INFO.smp_bspindex = (uint64_t)(-1);
  for (size_t i = 0; i < smpres->cpu_count; i++) {
    struct limine_smp_info *entry = smpres->cpus[i];
    if (entry->lapic_id == smpres->bsp_lapic_id) {
      BOOT_INFO.smp_bspindex = i;
    }
  }
  if (BOOT_INFO.smp_bspindex == (uint64_t)-1) {
    hal_hang();
  }

  struct limine_rsdp_response *rsdpres = rsdp_req.response;
  BOOT_INFO.rsdp = (size_t)rsdpres->address - BOOT_INFO.hhdm_off;
}
