// main_playdate.c - Playdate entry point for Cell runtime
// This file provides the eventHandler entry point required by Playdate SDK
// and initializes the global Playdate API pointers used by other modules.

#include "cell.h"
#include "playdate/common.h"

// Global Playdate API pointers - used by all playdate integration modules
PlaydateAPI *pd = NULL;
const struct playdate_file *pd_file = NULL;
const struct playdate_sys *pd_sys = NULL;
const struct playdate_graphics *pd_gfx = NULL;
const struct playdate_sprite *pd_sprite = NULL;
const struct playdate_display *pd_display = NULL;
const struct playdate_sound *pd_sound = NULL;
const struct playdate_lua *pd_lua = NULL;
const struct playdate_json *pd_json = NULL;
const struct playdate_scoreboards *pd_scoreboards = NULL;
const struct playdate_network *pd_network = NULL;

// Forward declaration
extern int cell_init(int argc, char **argv);

// Playdate update callback
static int update(void *userdata)
{
    // The Cell runtime uses its own event loop, so we just return 1 to continue
    return 1;
}

// Playdate event handler - main entry point
#ifdef _WINDLL
__declspec(dllexport)
#endif
int eventHandler(PlaydateAPI *playdate, PDSystemEvent event, uint32_t arg)
{
    (void)arg;
    
    if (event == kEventInit) {
        // Store global API pointers
        pd = playdate;
        pd_file = playdate->file;
        pd_sys = playdate->system;
        pd_gfx = playdate->graphics;
        pd_sprite = playdate->sprite;
        pd_display = playdate->display;
        pd_sound = playdate->sound;
        pd_lua = playdate->lua;
        pd_json = playdate->json;
        pd_scoreboards = playdate->scoreboards;
        pd_network = playdate->network;
        
        // Set up the update callback
        pd_sys->setUpdateCallback(update, NULL);
        
        // Initialize Cell runtime with no arguments
        // On Playdate, we'll look for main.ce in the data folder
        char *argv[] = { "cell", "main.ce", NULL };
        cell_init(2, argv);
    }
    
    return 0;
}
