#pragma once

// Include nlohmann/json BEFORE grove headers to avoid macro conflicts
#include <nlohmann/json.hpp>

#include "IService.hpp"
#include "ISTTService.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 celuna {

/**
 * @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 (legacy API)
    void configureSTT(bool enabled = true, const std::string& language = "fr",
                     const std::string& apiKey = "");

    /// Configure STT with full config (Phase 7)
    void configureSTT(const nlohmann::json& sttConfig);

    /// Load configuration from JSON file
    bool loadConfig(const std::string& configPath);

    /**
     * @brief Transcribe audio file synchronously (for MCP Server mode)
     *
     * @param filePath Path to audio file
     * @param language Language code (e.g., "fr", "en")
     * @return Transcribed text
     */
    std::string transcribeFileSync(
        const std::string& filePath,
        const std::string& language = "fr"
    );

    /**
     * @brief Convert text to speech synchronously (for MCP Server mode)
     *
     * @param text Text to synthesize
     * @param outputFile Output audio file path
     * @param voice Voice identifier (e.g., "fr-fr")
     * @return true if successful
     */
    bool textToSpeechSync(
        const std::string& text,
        const std::string& outputFile,
        const std::string& voice = "fr-fr"
    );

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;  // Legacy direct engine (deprecated)
    std::unique_ptr<ISTTService> m_sttService;  // Phase 7: New STT service layer
    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);

    // STT handlers (Phase 7)
    void handleTranscription(const std::string& text, STTMode mode);
    void handleKeyword(const std::string& keyword);
};

} // namespace celuna
