#include "BleSettings.h"
#include "FS.h"
#include <LittleFS.h>
#include <ArduinoJson.h>
#include "esp_log.h"

static const char *tag = "ble-settings";

// Global variables (initialized with defaults)
String BTDeviceName = DEFAULT_BT_DEVICE_NAME;
String BTServiceUUID = DEFAULT_BT_SERVICE;
String BTSP110ECharacteristicUUID = DEFAULT_BT_SP110E_CHAR;
String BTStickCharacteristicUUID = DEFAULT_BT_STICK_CHAR;
String BTUpgradeServiceUUID = DEFAULT_UPGRADE_SERVICE;
String BTUpgradeCharacteristic1UUID = DEFAULT_UPGRADE_CHAR1;
String BTUpgradeCharacteristic2UUID = DEFAULT_UPGRADE_CHAR2;

static String safeJsonString(JsonVariant obj, const char *key, const char *defVal) {
    if (!obj.is<JsonObject>()) return defVal;
    JsonVariant v = obj[key];
    if (!v.is<const char*>()) return defVal;
    const char *s = v.as<const char*>();
    if (!s || *s == '\0') return defVal;
    return String(s);
}

void Load_BLE_Settings(const String &configPath) {
    File file = LittleFS.open(configPath, "r");
    if (!file) {
        ESP_LOGW(tag, "Config %s not found. Using defaults.", configPath.c_str());
        return; // keep defaults
    }

    // Use a dynamic document sized to file length (clamped)
    size_t sz = file.size();
    if (sz == 0 || sz > 4096) { // protect against unrealistically large file
        ESP_LOGE(tag, "Invalid config size: %u", (unsigned)sz);
        file.close();
        return;
    }

    JsonDocument doc; // heuristic
    DeserializationError error = deserializeJson(doc, file);
    file.close();
    if (error) {
        ESP_LOGE(tag, "Deserialize error: %s", error.c_str());
        return; // keep previous / defaults
    }

    JsonObject root = doc.as<JsonObject>();
    if (root.isNull()) {
        ESP_LOGE(tag, "Empty JSON root");
        return;
    }

    // Map expected keys
    BTDeviceName                 = safeJsonString(root, "name", BTDeviceName.c_str());
    BTServiceUUID                = safeJsonString(root, "lights-service", BTServiceUUID.c_str());
    BTSP110ECharacteristicUUID   = safeJsonString(root, "lights-char", BTSP110ECharacteristicUUID.c_str());
    BTStickCharacteristicUUID    = safeJsonString(root, "stick-char", BTStickCharacteristicUUID.c_str());
    BTUpgradeServiceUUID         = safeJsonString(root, "upgrade-service", BTUpgradeServiceUUID.c_str());
    BTUpgradeCharacteristic1UUID = safeJsonString(root, "upgrade-char1", BTUpgradeCharacteristic1UUID.c_str());
    BTUpgradeCharacteristic2UUID = safeJsonString(root, "upgrade-char2", BTUpgradeCharacteristic2UUID.c_str());

    ESP_LOGI(tag, "Loaded BLE config: name=%s svc=%s char1=%s stick=%s upg_svc=%s upg1=%s upg2=%s",
             BTDeviceName.c_str(), BTServiceUUID.c_str(), BTSP110ECharacteristicUUID.c_str(),
             BTStickCharacteristicUUID.c_str(), BTUpgradeServiceUUID.c_str(),
             BTUpgradeCharacteristic1UUID.c_str(), BTUpgradeCharacteristic2UUID.c_str());
}