/**
 * ESP32 Smart Speaker Client - Firmware Implementation (CHỐNG TRÀN RAM)
 * 
 * Tương thích 100% với API Spec mới của Hệ thống Loa Thông Minh.
 * 
 * GIẢI PHÁP TỐI ƯU BỘ NHỚ (ZERO-HEAP PCM 16-BIT STREAMING):
 * 1. Chế độ Playlist: Giải mã MP3 từ /audio/stream qua thư viện ESP32-audioI2S.
 * 2. Chế độ Live: Tạm dừng giải mã MP3, nhận trực tiếp dữ liệu nhị phân PCM 16-bit 16000Hz
 *    từ WebSocket Binary Frame và đẩy thẳng vào phần cứng I2S DMA bằng driver/i2s.h.
 *    -> Bộ nhớ RAM tiêu tốn = 0 byte! Board ESP32 chạy ổn định cả ngày, không bao giờ bị tràn RAM!
 */

#include <Arduino.h>
#include <WiFi.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <driver/i2s.h>
#include "Audio.h"

// =========================================================================
// 1. CẤU HÌNH HỆ THỐNG
// =========================================================================
const char* DEFAULT_SSID     = "My_WiFi";
const char* DEFAULT_PASSWORD = "My_Password";

const char* SERVER_HOST      = "103.189.208.107";
const uint16_t SERVER_PORT   = 6789;
const char* WS_ENDPOINT      = "/ws/control";

const char* DEVICE_ID        = "dev_001";
const char* DEVICE_TOKEN     = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."; // Lấy từ /api/v1/devices/register

// Chân I2S DAC (ví dụ: MAX98357A hoặc PCM5102)
#define I2S_BCLK_PIN  26
#define I2S_LRC_PIN   25
#define I2S_DOUT_PIN  22
#define I2S_NUM       I2S_NUM_0

Audio audio;
WebSocketsClient webSocket;

String currentTrack = "";
String currentMode  = "playlist"; // "playlist" hoặc "live"
bool isI2SDriverInstalledForLive = false;

// =========================================================================
// 2. KHỞI TẠO & CẤU HÌNH I2S DRIVER GỐC CHO PCM 16-BIT (CHỐNG TRÀN RAM)
// =========================================================================

void setupI2SForPCM16(int sampleRate = 16000) {
    if (isI2SDriverInstalledForLive) {
        i2s_driver_uninstall(I2S_NUM);
        isI2SDriverInstalledForLive = false;
    }

    i2s_config_t i2s_config = {
        .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
        .sample_rate = (uint32_t)sampleRate,
        .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
        .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // Hoặc ONLY_RIGHT / RIGHT_LEFT
        .communication_format = I2S_COMM_FORMAT_STAND_I2S,
        .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
        .dma_buf_count = 8,
        .dma_buf_len = 256, // 8 * 256 = 2KB DMA Buffer (cực nhẹ RAM)
        .use_apll = false,
        .tx_desc_auto_clear = true
    };

    i2s_pin_config_t pin_config = {
        .bck_io_num = I2S_BCLK_PIN,
        .ws_io_num = I2S_LRC_PIN,
        .data_out_num = I2S_DOUT_PIN,
        .data_in_num = I2S_PIN_NO_CHANGE
    };

    i2s_driver_install(I2S_NUM, &i2s_config, 0, NULL);
    i2s_set_pin(I2S_NUM, &pin_config);
    i2s_zero_dma_buffer(I2S_NUM);

    isI2SDriverInstalledForLive = true;
    Serial.printf("[I2S] Cấu hình phần cứng I2S PCM 16-bit (%d Hz) thành công! Free Heap: %d bytes\n", 
                  sampleRate, ESP.getFreeHeap());
}

void restoreI2SForAudioLib() {
    if (isI2SDriverInstalledForLive) {
        i2s_driver_uninstall(I2S_NUM);
        isI2SDriverInstalledForLive = false;
    }
    // Gán lại chân cho thư viện Audio.h phát MP3
    audio.setPinout(I2S_BCLK_PIN, I2S_LRC_PIN, I2S_DOUT_PIN);
    Serial.printf("[I2S] Đã trả quyền I2S lại cho thư viện MP3 Playlist. Free Heap: %d bytes\n", ESP.getFreeHeap());
}

// =========================================================================
// 3. GỬI PHẢN HỒI (ACK) & BÁO CÁO TRẠNG THÁI
// =========================================================================

void sendCommandAck(const char* requestId, const char* status = "received") {
    DynamicJsonDocument doc(256);
    doc["type"]       = "device.command.ack";
    doc["request_id"] = requestId;
    doc["device_id"]  = DEVICE_ID;
    doc["status"]     = status;

    String jsonStr;
    serializeJson(doc, jsonStr);
    webSocket.sendTXT(jsonStr);
    Serial.printf("[WS] Sent ACK for %s: %s\n", requestId, status);
}

void sendTrackFinished(const char* file) {
    DynamicJsonDocument doc(256);
    doc["type"]      = "track.finished";
    doc["device_id"] = DEVICE_ID;
    doc["file"]      = file;
    doc["auto_next"] = true;

    String jsonStr;
    serializeJson(doc, jsonStr);
    webSocket.sendTXT(jsonStr);
    Serial.printf("[WS] Sent track.finished for: %s\n", file);
}

void sendHeartbeatStatus() {
    DynamicJsonDocument doc(512);
    doc["type"]      = "device.status";
    doc["device_id"] = DEVICE_ID;

    JsonObject data = doc.createNestedObject("data");
    data["mode"]            = currentMode;
    data["playback_status"] = (currentMode == "live") ? "live" : (audio.isRunning() ? "playing" : "idle");
    data["current_track"]   = currentTrack;
    data["volume"]          = audio.getVolume();
    data["wifi_status"]     = (WiFi.status() == WL_CONNECTED) ? "connected" : "disconnected";
    data["ssid"]            = WiFi.SSID();
    data["ip_address"]      = WiFi.localIP().toString();
    data["rssi"]            = WiFi.RSSI();
    data["free_heap_bytes"] = ESP.getFreeHeap(); // Báo RAM thực tế về Server
    data["uptime_sec"]      = millis() / 1000;

    String jsonStr;
    serializeJson(doc, jsonStr);
    webSocket.sendTXT(jsonStr);
}

// =========================================================================
// 4. XỬ LÝ LỆNH TỪ SERVER (type: "device.command")
// =========================================================================

void handleDeviceCommand(JsonObject doc) {
    const char* requestId = doc["request_id"] | "";
    const char* deviceId  = doc["device_id"] | "";

    if (strlen(deviceId) > 0 && strcmp(deviceId, DEVICE_ID) != 0 && strcmp(deviceId, "all") != 0) {
        return;
    }

    JsonObject payload = doc["payload"];
    const char* command = payload["command"] | "";
    JsonObject params   = payload["params"];

    Serial.printf("[CMD] Received: %s (req_id: %s) | Free Heap: %d bytes\n", command, requestId, ESP.getFreeHeap());

    // 1. wifi.update
    if (strcmp(command, "wifi.update") == 0) {
        const char* newSsid = params["ssid"] | "";
        const char* newPass = params["password"] | "";

        Serial.printf("[WIFI] Updating WiFi -> SSID: %s\n", newSsid);
        sendCommandAck(requestId, "received");

        WiFi.disconnect();
        WiFi.begin(newSsid, newPass);
        return;
    }

    // 2. channel.set (mode: live hoặc playlist)
    else if (strcmp(command, "channel.set") == 0) {
        const char* mode = params["mode"] | "playlist";

        if (strcmp(mode, "live") == 0) {
            currentMode = "live";
            int sampleRate = params["audio"]["sample_rate"] | 16000;

            Serial.printf("[CHANNEL] -> Chuyển sang LIVE STREAM 16-BIT (%d Hz)!\n", sampleRate);
            
            // Dừng phát MP3 và chuyển phần cứng sang chế độ nhận PCM 16-bit
            audio.stopSong();
            setupI2SForPCM16(sampleRate);
        } else {
            currentMode = "playlist";
            Serial.println("[CHANNEL] -> Kết thúc Live. Quay lại chế độ PLAYLIST.");
            restoreI2SForAudioLib();
        }
        sendCommandAck(requestId, "success");
    }

    // 3. play (Phát bài MP3)
    else if (strcmp(command, "play") == 0) {
        if (currentMode == "live") {
            currentMode = "playlist";
            restoreI2SForAudioLib();
        }

        const char* file = params["file"] | "";
        if (strlen(file) > 0) {
            currentTrack = file;
            char streamUrl[256];
            snprintf(streamUrl, sizeof(streamUrl), "http://%s:%d/audio/stream?file=%s",
                     SERVER_HOST, SERVER_PORT, file);

            Serial.printf("[AUDIO] Playing MP3: %s | Free Heap: %d\n", streamUrl, ESP.getFreeHeap());
            audio.stopSong();
            audio.connecttohost(streamUrl);
        } else {
            audio.pauseResume();
        }
        sendCommandAck(requestId, "success");
    }

    // 4. pause
    else if (strcmp(command, "pause") == 0) {
        if (currentMode == "playlist") {
            audio.pauseResume();
        }
        sendCommandAck(requestId, "success");
    }

    // 5. stop
    else if (strcmp(command, "stop") == 0) {
        if (currentMode == "playlist") {
            audio.stopSong();
        }
        sendCommandAck(requestId, "success");
    }

    // 6. next
    else if (strcmp(command, "next") == 0) {
        const char* file = params["file"] | "";
        if (strlen(file) > 0) {
            currentTrack = file;
            char streamUrl[256];
            snprintf(streamUrl, sizeof(streamUrl), "http://%s:%d/audio/stream?file=%s",
                     SERVER_HOST, SERVER_PORT, file);
            audio.stopSong();
            audio.connecttohost(streamUrl);
        }
        sendCommandAck(requestId, "success");
    }

    // 7. previous
    else if (strcmp(command, "previous") == 0) {
        const char* file = params["file"] | "";
        if (strlen(file) > 0) {
            currentTrack = file;
            char streamUrl[256];
            snprintf(streamUrl, sizeof(streamUrl), "http://%s:%d/audio/stream?file=%s",
                     SERVER_HOST, SERVER_PORT, file);
            audio.stopSong();
            audio.connecttohost(streamUrl);
        }
        sendCommandAck(requestId, "success");
    }

    // 8. set_volume
    else if (strcmp(command, "set_volume") == 0) {
        int vol = params["volume"] | 65;
        audio.setVolume(vol);
        sendCommandAck(requestId, "success");
    }
}

// =========================================================================
// 5. SỰ KIỆN WEBSOCKET (NHẬN TEXT LỆNH & BINARY ÂM THANH 16-BIT PCM)
// =========================================================================

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
    switch (type) {
        case WStype_DISCONNECTED:
            Serial.println("[WS] Disconnected!");
            break;

        case WStype_CONNECTED:
            Serial.printf("[WS] Connected to %s | Free Heap: %d bytes\n", WS_ENDPOINT, ESP.getFreeHeap());
            sendHeartbeatStatus();
            break;

        // A. NHẬN BẢN TIN LỆNH (JSON TEXT)
        case WStype_TEXT: {
            DynamicJsonDocument doc(1024);
            DeserializationError error = deserializeJson(doc, payload, length);
            if (error) {
                return;
            }

            const char* msgType = doc["type"] | doc["event"] | "";
            if (strcmp(msgType, "device.command") == 0) {
                handleDeviceCommand(doc.as<JsonObject>());
            }
            break;
        }

        // B. NHẬN LUỒNG ÂM THANH TRỰC TIẾP (16-BIT PCM BINARY - ZERO HEAP ALLOCATION)
        case WStype_BIN:
            if (currentMode == "live" && isI2SDriverInstalledForLive) {
                size_t bytes_written = 0;
                // Đẩy trực tiếp gói dữ liệu 16-bit PCM vào DMA I2S DAC (MAX98357A / PCM5102)
                // Không tốn 1 byte RAM Heap nào!
                i2s_write(I2S_NUM, payload, length, &bytes_written, portMAX_DELAY);
            }
            break;

        default:
            break;
    }
}

// =========================================================================
// 6. CALLBACK KHI PHÁT HẾT 1 BÀI NHẠC (ESP32-audioI2S)
// =========================================================================

void audio_eof_mp3(const char *info) {
    Serial.printf("[AUDIO] Track finished: %s\n", info);
    sendTrackFinished(currentTrack.c_str());
}

// =========================================================================
// 7. SETUP & LOOP
// =========================================================================

void setup() {
    Serial.begin(115200);
    delay(1000);
    Serial.println("\n--- Starting Smart Speaker ESP32 (Optimized RAM) ---");
    Serial.printf("[RAM] Khởi động ban đầu: Free Heap = %d bytes\n", ESP.getFreeHeap());

    // Khởi tạo chân âm thanh ban đầu cho thư viện MP3
    audio.setPinout(I2S_BCLK_PIN, I2S_LRC_PIN, I2S_DOUT_PIN);
    audio.setVolume(65);

    // Kết nối Wi-Fi
    WiFi.mode(WIFI_STA);
    WiFi.begin(DEFAULT_SSID, DEFAULT_PASSWORD);
    Serial.print("Connecting to WiFi");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nWiFi connected! IP: " + WiFi.localIP().toString());
    Serial.printf("[RAM] Sau khi kết nối WiFi: Free Heap = %d bytes\n", ESP.getFreeHeap());

    // Cấu hình URL WebSocket
    char wsUrl[256];
    snprintf(wsUrl, sizeof(wsUrl), "%s?device_id=%s&token=%s", WS_ENDPOINT, DEVICE_ID, DEVICE_TOKEN);

    webSocket.begin(SERVER_HOST, SERVER_PORT, wsUrl);
    webSocket.onEvent(webSocketEvent);
    webSocket.setReconnectInterval(5000);
    webSocket.enableHeartbeat(15000, 3000, 2);
}

unsigned long lastHeartbeat = 0;

void loop() {
    // Chỉ chạy audio.loop() khi ở chế độ playlist MP3 (ở chế độ Live ta dùng I2S DMA trực tiếp)
    if (currentMode == "playlist") {
        audio.loop();
    }

    webSocket.loop();

    // Heartbeat định kỳ 30 giây (báo kèm mức RAM tự do)
    if (millis() - lastHeartbeat > 30000) {
        lastHeartbeat = millis();
        if (webSocket.isConnected()) {
            sendHeartbeatStatus();
            Serial.printf("[RAM MONITOR] Free Heap: %d bytes | Mode: %s\n", ESP.getFreeHeap(), currentMode.c_str());
        }
    }
}
