#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/logging/log_ctrl.h>
#include <fs_mgmt.h>
#include <audio.h>
#include <hal/nrf_i2s.h>
#include <lasertag_utils.h>

LOG_MODULE_REGISTER(MMS, LOG_LEVEL_INF);

int main(void)
{
    LOG_INF("Starting Audio Sample Application...");
    LOG_INF("Sleeping for one second to allow thread analyzer to initialize and log thread states before we start the test.");
    k_sleep(K_MSEC(1000));

    int err;
    LOG_INF("Audio test snippet");
    err = fs_mgmt_init();
    if (err)
    {
        LOG_ERR("Failed to initialize fs_mgmt: %d", err);
        return err;
    }

    err = audio_init();
    if (err)
    {
        LOG_ERR("Failed to initialize audio: %d", err);
        return err;
    }

    LOG_INF("Triggering NULL file playback to test error handling...");
    audio_play_file(NULL);
    while(log_process());
    LOG_INF("Triggering NULL sound to test error handling...");
    audio_play_sound(NULL);
    while(log_process());
    LOG_INF("Triggering nonexistent sound to test error handling...");
    audio_play_sound("nonexistent_file");
    k_sleep(K_MSEC(100));
    while(log_process());
    LOG_INF("Triggering very long file name to test error handling...");
    audio_play_sound("very_long_file_name_that_exceeds_the_maximum_length_allowed_by_the_system_to_test_error_handling");
    while(log_process());

    LOG_INF("Triggering first sound...");
    audio_play_sound("s1");
    k_sleep(K_MSEC(100));
    audio_stop();
    LOG_INF("Triggering second sound after abort...");
    audio_play_sound("s1");

    k_sleep(K_MSEC(100));
    // Directly stop the I2S peripheral to simulate an abrupt stop that
    // might occur with a DMA failure or similar issue. This will cause the
    // next playback attempt to hit the slab timeout and trigger the I2S
    // reset logic in the audio thread.
    LOG_INF("Simulating failure by stopping I2S directly...");
    NRF_I2S0->TASKS_STOP = 1;
    NRF_I2S0->ENABLE = 0;
    LOG_INF("Triggering third sound after failure simulation...");
    audio_play_sound("s1");
    LOG_INF(FORMAT_GREEN_BOLD("If you made it to this point, the test completed successfully and everything should work fine!"));
    LOG_INF(FORMAT_BRIGHT_BOLD("More output might follow due to the async nature of the audio playback."));

    return 0;
}
