#include <amd64/gdt.h>
#include <aux/elf.h>
#include <libk/list.h>
#include <libk/rbtree.h>
#include <libk/std.h>
#include <libk/string.h>
#include <limine/requests.h>
#include <mm/liballoc.h>
#include <mm/pmm.h>
#include <proc/proc.h>
#include <proc/resource.h>
#include <sync/spin_lock.h>
#include <sys/debug.h>

static atomic_int pids = 1;

struct proc* proc_from_elf (uint8_t* elf_contents) {
  struct limine_hhdm_response* hhdm = limine_hhdm_request.response;

  struct proc* proc = malloc (sizeof (*proc));
  if (proc == NULL)
    return NULL;

  memset (proc, 0, sizeof (*proc));

  proc->lock = SPIN_LOCK_INIT;
  atomic_store (&proc->state, PROC_READY);
  proc->pid = atomic_fetch_add (&pids, 1);

  proc->pd.lock = SPIN_LOCK_INIT;
  proc->pd.cr3_paddr = mm_alloc_user_pd_phys ();
  if (proc->pd.cr3_paddr == 0) {
    free (proc);
    return NULL;
  }

  int kstk_rid = atomic_fetch_add (&proc->rids, 1);
  struct proc_resource_mem_init kstk_mem_init = {.pages = KSTACK_SIZE / PAGE_SIZE};
  struct proc_resource* kstk_r =
      proc_create_resource (proc, kstk_rid, PR_MEM, RV_PRIVATE, (void*)&kstk_mem_init);
  if (kstk_r == NULL) {
    free (proc);
    return NULL;
  }

  proc->pdata.kernel_stack = kstk_r->u.mem.paddr + (uintptr_t)hhdm->offset + KSTACK_SIZE;

  int ustk_rid = atomic_fetch_add (&proc->rids, 1);
  struct proc_resource_mem_init ustk_mem_init = {.pages = USTACK_SIZE / PAGE_SIZE};
  struct proc_resource* ustk_r =
      proc_create_resource (proc, ustk_rid, PR_MEM, RV_PRIVATE, (void*)&ustk_mem_init);
  if (ustk_r == NULL) {
    kstk_r->ops.cleanup (kstk_r);
    free (kstk_r);
    free (proc);
    return NULL;
  }

  proc->pdata.user_stack = ustk_r->u.mem.paddr;

  proc_map (proc, proc->pdata.user_stack, PROC_USTACK_TOP - USTACK_SIZE, USTACK_SIZE / PAGE_SIZE,
            MM_PG_USER | MM_PG_PRESENT | MM_PG_RW);

  struct elf_aux aux = proc_load_segments (proc, elf_contents);

  proc->pdata.regs.ss = GDT_UDATA | 0x03;
  proc->pdata.regs.rsp = (uint64_t)PROC_USTACK_TOP;
  proc->pdata.regs.rflags = 0x202;
  proc->pdata.regs.cs = GDT_UCODE | 0x03;
  proc->pdata.regs.rip = aux.entry;

  return proc;
}

void proc_cleanup (struct proc* proc) {
  struct limine_hhdm_response* hhdm = limine_hhdm_request.response;

  proc_cleanup_resources (proc);

  struct list_node_link *mapping_link, *mapping_link_tmp;
  spin_lock (&proc->pd.lock);

  list_foreach (proc->mappings, mapping_link, mapping_link_tmp) {
    struct proc_mapping* mapping =
        list_entry (mapping_link, struct proc_mapping, proc_mappings_link);

    list_remove (proc->mappings, mapping_link);
    free (mapping);
  }

  spin_unlock (&proc->pd.lock);

  pmm_free (proc->pd.cr3_paddr, 1);

  pmm_free (proc->pdata.kernel_stack - (uintptr_t)hhdm->offset - KSTACK_SIZE,
            KSTACK_SIZE / PAGE_SIZE);
  pmm_free (proc->pdata.user_stack, USTACK_SIZE / PAGE_SIZE);

  free (proc);
}
