#pragma once

#include <efi.h>
#include <memory/pmm.h>
#include <common.h>
#include <string_utils.h>

#define TASK_STACK_SIZE  (PAGE_SIZE * 4)  // 16 KB kernel stack per task
#define TASK_MAX         32
#define TASK_NAME_LEN    32
#define TIME_SLICE_DEFAULT 5  // 5 ticks = 50ms at 100 Hz

typedef enum {
    TASK_STATE_READY,
    TASK_STATE_RUNNING,
    TASK_STATE_TERMINATED,
} task_state_t;

typedef struct task {
    UINT64          rsp;            // saved stack pointer (for context switch)
    UINT32          id;
    task_state_t    state;
    char            name[TASK_NAME_LEN];
    void*           stack_base;     // base address of kernel stack
    struct task*    next;           // circular linked list
    UINT32          time_slice;     // remaining ticks before preemption
} task_t;

// Create a new task. Returns task pointer or NULL on failure.
task_t* task_create(String name, void (*entry)(void));

// Yield CPU to next ready task (cooperative)
void yield(void);

// Start the scheduler — does not return. Picks first READY task and runs it.
void scheduler_run(void);

// Called by a task when it finishes — marks as TERMINATED and yields
void task_exit(void);

// Get current running task
task_t* scheduler_current(void);

// Timer tick handler — called by PIT IRQ 0, drives preemption
void scheduler_tick(void);
