/*
 * This program source code file is part of the KTag project.
 *
 * 🛡 <https://ktag.clubk.club> 🃞
 *
 * Copyright © 2024-2026 Joseph P. Kearney and the KTag developers.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 *
 * There should be a copy of the GNU Affero General Public License in the LICENSE
 * file in the root of this repository.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <SystemK.h>
#include <System_Events.h>
#include <string.h>
#include "esp_spiffs.h"

static const char *TAG = "SPIFFS";
const char *DEFAULT_CONFIG_FILE = "/spiffs/default_config.txt";

void Initialize_SPIFFS(void)
{
    KLOG_INFO(TAG, "Initializing SPI flash file system (SPIFFS)...");

    esp_vfs_spiffs_conf_t conf = {
        .base_path = "/spiffs",            // File path prefix associated with the filesystem. 
        .partition_label = NULL,           // If set to NULL, first partition with subtype=spiffs will be used. 
        .max_files = 5,                    // Maximum files that could be open at the same time. 
        .format_if_mount_failed = false};  // If true, it will format the file system if it fails to mount. 

    esp_err_t ret = esp_vfs_spiffs_register(&conf);

    if (ret != ESP_OK)
    {
        if (ret == ESP_FAIL)
        {
            KLOG_ERROR(TAG, "Failed to mount or format filesystem!");
        }
        else if (ret == ESP_ERR_NOT_FOUND)
        {
            KLOG_ERROR(TAG, "Failed to find SPIFFS partition!");
        }
        else
        {
            KLOG_ERROR(TAG, "Failed to initialize SPIFFS (%s)!", esp_err_to_name(ret));
        }
        return;
    }

    size_t total = 0;
    size_t used = 0;
    ret = esp_spiffs_info(NULL, &total, &used);
    if (ret != ESP_OK)
    {
        KLOG_ERROR(TAG, "Failed to get SPIFFS partition information (%s)!", esp_err_to_name(ret));
    }
    else
    {
        KLOG_INFO(TAG, "SPIFFS partition: %d bytes used out of %d total.", used, total);
    }

    FILE *f = fopen("/spiffs/boot_message.txt", "r");
    if (f == NULL)
    {
        KLOG_ERROR(TAG, "Failed to open boot_message.txt!");
        return;
    }

    char buf[64];
    memset(buf, 0, sizeof(buf));
    fread(buf, 1, sizeof(buf), f);
    fclose(f);

    KLOG_INFO(TAG, ">>> %s <<<", buf);

    xEventGroupSetBits(Get_System_Events(), SYS_SPIFFS_READY);
    KLOG_INFO(TAG, "SPIFFS initialized.");
}
