/*
 * src/kernel/loader/fpf.c - Florid Package Format Execution Engine
 * Part of the monolithic core scaling architecture.
 */

#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "../../include/fpf.h"

// External references to our kernel logging and status mappings
extern void klog(const char* module, const char* msg);
extern void klog_status(const char* module, int status);

/* Simple memory space tracker for bare-metal app loading */
static uint64_t current_app_stack_base = 0x80000000; // Load user stacks high

/*
 * execute_fpf_package
 * Validates, maps, and executes an FPF binary directly from a memory buffer.
 */
int execute_fpf_package(uint8_t* raw_binary, size_t size) {
    klog("LOADER", "Interrogating binary payload for FPF compliance...");

    if (size < sizeof(fpf_header_t)) {
        klog("LOADER", "FATAL: Payload smaller than base FPF header schema.");
        return 11; // Buffer overflow/underflow
    }

    fpf_header_t* header = (fpf_header_t*)raw_binary;

    // Strict Magic Byte Verification
    if (header->magic[0] != 'F' || header->magic[1] != 'L' ||
        header->magic[2] != 'O' || header->magic[3] != 'R') {
        klog("LOADER", "FATAL: Magic bytes do not match 'FLOR'. Execution aborted.");
        return 4; // Invalid Magic
    }

    klog("LOADER", "Magic 'FLOR' verified. Parsing execution vectors...");

    // Determine payload offset (where the actual executable instructions begin)
    uint64_t code_offset = sizeof(fpf_header_t);
    uintptr_t entry_address = (uintptr_t)(raw_binary + code_offset + header->entry_point);

    // Verify context claims
    if (header->type == FPF_TYPE_DE) {
        klog("LOADER", "Context: Desktop Environment / Shell. Granting Framebuffer Access.");
    } else if (header->type == FPF_TYPE_APP) {
        klog("LOADER", "Context: Standard Application. Enforcing sandbox boundaries.");
    }

    klog("LOADER", "Transferring instruction pointer to FPF payload entry...");

    // Define a function pointer to the app's start address
    void (*app_entry)(void) = (void (*)(void))entry_address;

    // Execute the package (Handoff)
    app_entry();

    klog("LOADER", "FPF Package execution completed cleanly. Context returned to kernel.");
    return 0;
}