/**
 * DOOM for ESP32-S3 - Arduino Framework Port
 * Main entry point
 */

#include <Arduino.h>
#include <esp_task_wdt.h>

// Undefine C++ true/false before including DOOM headers
#undef true
#undef false

// External C functions from DOOM engine
extern "C" {
    #include "i_system.h"
    #include "i_main.h"
    #include "spi_lcd.h"
}

// DOOM task - needs large stack for texture loading
void doom_task(void *pvParameters) {
    const char *argv[] = {
        "doom", "-cout", "ICWEFDA"
    };

    Serial.println("DOOM task starting...");
    Serial.printf("Stack high water mark: %d bytes free\n", uxTaskGetStackHighWaterMark(NULL));

    // Initialize SPI LCD here, inside the task context
    Serial.println("Initializing display in DOOM task...");
    spi_lcd_init();

    doom_main(sizeof(argv) / sizeof(argv[0]), argv);

    // Should never reach here
    vTaskDelete(NULL);
}

void setup() {
    Serial.begin(115200);
    delay(1000);

    Serial.println("\n\n=== DOOM ESP32-S3 Arduino ===");
    Serial.println("Step 1: Disabling watchdogs...");

    // Disable all watchdogs
    esp_task_wdt_deinit();
    disableCore0WDT();
    disableCore1WDT();
    disableLoopWDT();

    Serial.println("Step 2: Watchdogs disabled");
    Serial.println("Step 3: Creating DOOM task...");

    // Create DOOM task on core 1 (Arduino runs on core 1)
    // Using 32KB stack for texture loading
    xTaskCreatePinnedToCore(
        doom_task,
        "doom",
        32768,          // 32KB stack
        NULL,
        5,
        NULL,
        1               // Core 1 (same as Arduino loop)
    );

    Serial.println("Step 4: DOOM task created");
}

void loop() {
    vTaskDelay(pdMS_TO_TICKS(1000));
}
