#include "init.h"
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <WiFi.h>
#include "utils.h"

namespace esp32 {
namespace init {

// WiFi 配置变量
static String wifiSSID = "";
static String wifiPassword = "";
static String backendUrl = "";

// TFT 显示器引用 (在 initSystem 中设置)
static Adafruit_ST7735* tftPtr = nullptr;

// 在屏幕上打印日志
void tftLog(const char* msg, uint16_t color) {
    if (tftPtr == nullptr)
        return;
    tftPtr->setTextColor(color);
    tftPtr->println(msg);
    tftPtr->setCursor(tftPtr->getCursorX(),
                      tftPtr->getCursorY() + 2);  // 增加2像素行距
}

// 读取并解析配置文件
bool loadSettings() {
    if (!LittleFS.begin(true)) {
        tftLog("LittleFS mount failed!", RED);
        return false;
    }
    tftLog("LittleFS mounted", GREEN);

    File file = LittleFS.open("/settings.json", "r");
    if (!file) {
        tftLog("Can't open settings", RED);
        return false;
    }
    tftLog("Settings file opened", GREEN);

    // 使用 ArduinoJson 7.x 解析
    JsonDocument doc;
    DeserializationError error = deserializeJson(doc, file);
    file.close();

    if (error) {
        tftLog("JSON parse failed!", RED);
        return false;
    }

    // 读取 WiFi 配置
    wifiSSID = doc["wifi"]["ssid"].as<String>();
    wifiPassword = doc["wifi"]["password"].as<String>();

    // 读取后端接口（可选）
    if (doc.containsKey("backend")) {
        backendUrl = doc["backend"]["url"].as<String>();
    }
    if (backendUrl.isEmpty()) {
        // 回退：保持为空或设为默认
        backendUrl = "http://nf.xn--876a.net/api/data";
    }

    tftLog("Config loaded:", GREEN);
    tftPtr->print("  SSID: ");
    tftLog(wifiSSID.c_str(), WHITE);

    return true;
}

// 连接 WiFi
void connectWiFi() {
    if (wifiSSID.isEmpty()) {
        tftLog("WiFi SSID empty", RED);
        return;
    }

    tftPtr->print("Connecting: ");
    tftLog(wifiSSID.c_str(), WHITE);

    WiFi.mode(WIFI_STA);
    WiFi.begin(wifiSSID.c_str(), wifiPassword.c_str());

    int attempts = 0;
    while (WiFi.status() != WL_CONNECTED && attempts < 20) {
        delay(500);
        tftPtr->print(".");
        attempts++;
    }
    tftPtr->println();

    if (WiFi.status() == WL_CONNECTED) {
        tftLog("WiFi connected!", GREEN);
        tftPtr->print("IP: ");
        tftLog(WiFi.localIP().toString().c_str(), WHITE);
    } else {
        tftLog("WiFi failed!", RED);
    }
}

// 初始化系统
void initSystem(Adafruit_ST7735& tft) {
    tftPtr = &tft;

    tftLog("=== ESP32-S3 ===", YELLOW);
    tft.println();

    // 读取配置文件并连接 WiFi
    if (loadSettings()) {
        connectWiFi();
    }
}

// 提供后端 URL 给外部使用
const String& getBackendUrl() { return backendUrl; }

}  // namespace init
}  // namespace esp32
