#pragma once

#include <grove/IModule.h>
#include <grove/JsonDataNode.h>

#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <memory>
#include <string>
#include <set>
#include <map>

namespace celuna {

/**
 * @brief Monitoring Module - App classification logic only
 *
 * Handles app classification without platform-specific tracking.
 * Receives window info from PlatformService via IIO.
 *
 * Publie sur:
 * - "monitoring:app_changed"       : When tracked app changes (with classification)
 * - "monitoring:productivity_update": Periodic stats
 *
 * Souscrit a:
 * - "platform:window_info"     : Current window from PlatformService
 * - "platform:window_changed"  : Window change from PlatformService
 * - "platform:idle_detected"   : User idle
 * - "platform:activity_resumed": User active
 */
class MonitoringModule : public grove::IModule {
public:
    MonitoringModule();
    ~MonitoringModule() override = default;

    // IModule interface
    void process(const grove::IDataNode& input) override;
    void setConfiguration(const grove::IDataNode& configNode, grove::IIO* io,
                         grove::ITaskScheduler* scheduler) override;
    const grove::IDataNode& getConfiguration() override;
    std::unique_ptr<grove::IDataNode> getHealthStatus() override;
    void shutdown() override;
    std::unique_ptr<grove::IDataNode> getState() override;
    void setState(const grove::IDataNode& state) override;
    std::string getType() const override { return "MonitoringModule"; }
    bool isIdle() const override { return true; }
    int getVersion() const override { return 2; }

private:
    // Configuration
    std::set<std::string> m_productiveApps;
    std::set<std::string> m_distractingApps;
    bool m_enabled = true;

    // State
    std::string m_currentApp;
    bool m_isIdle = false;
    std::map<std::string, int> m_appDurations;  // seconds per app
    int m_totalProductiveSeconds = 0;
    int m_totalDistractingSeconds = 0;

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

    // Helpers
    void processMessages();
    void handleWindowChanged(const grove::IDataNode& data);
    void handleWindowInfo(const grove::IDataNode& data);
    void handleIdleDetected(const grove::IDataNode& data);
    void handleActivityResumed(const grove::IDataNode& data);
    bool isProductiveApp(const std::string& appName) const;
    bool isDistractingApp(const std::string& appName) const;

    // Tool handlers
    void handleToolQuery(const grove::IDataNode& request);
};

} // namespace celuna

extern "C" {
    grove::IModule* createModule();
    void destroyModule(grove::IModule* module);
}
