#pragma once

#include "IService.hpp"
#include "../shared/audio/ITTSEngine.hpp"
#include "../shared/audio/ISTTEngine.hpp"

#include <grove/IIO.h>
#include <grove/JsonDataNode.h>
#include <spdlog/spdlog.h>

#include <memory>
#include <string>
#include <queue>

namespace aissia {

/**
 * @brief Voice Service - TTS and STT engines
 *
 * Handles platform-specific audio engines (SAPI on Windows, espeak on Linux).
 * Manages speak queue and processes TTS/STT requests.
 *
 * Subscribes to:
 * - "voice:speak"  : { text, priority? }
 * - "voice:stop"   : Stop current speech
 * - "voice:listen" : Start STT recording
 *
 * Publishes:
 * - "voice:speaking_started" : { text }
 * - "voice:speaking_ended"   : {}
 * - "voice:transcription"    : { text, confidence }
 */
class VoiceService : public IService {
public:
    VoiceService();
    ~VoiceService() override = default;

    bool initialize(grove::IIO* io) override;
    void process() override;
    void shutdown() override;
    std::string getName() const override { return "VoiceService"; }
    bool isHealthy() const override { return m_ttsEngine != nullptr; }

    /// Configure TTS settings
    void configureTTS(bool enabled = true, int rate = 0, int volume = 80);

    /// Configure STT settings
    void configureSTT(bool enabled = true, const std::string& language = "fr",
                     const std::string& apiKey = "");

private:
    // Configuration
    bool m_ttsEnabled = true;
    bool m_sttEnabled = true;
    int m_ttsRate = 0;
    int m_ttsVolume = 80;
    std::string m_language = "fr";

    // State
    std::unique_ptr<ITTSEngine> m_ttsEngine;
    std::unique_ptr<ISTTEngine> m_sttEngine;
    std::queue<std::string> m_speakQueue;
    int m_totalSpoken = 0;

    // Services
    grove::IIO* m_io = nullptr;
    std::shared_ptr<spdlog::logger> m_logger;

    // Helpers
    void processMessages();
    void processSpeakQueue();
    void speak(const std::string& text);
    void handleSpeakRequest(const grove::IDataNode& data);
};

} // namespace aissia
