#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 <vector>
#include <chrono>
#include <ctime>

namespace celuna {

/**
 * @brief Storage Module - Pure business logic for data persistence
 *
 * Handles data persistence logic without direct database access.
 * Communicates with StorageService via IIO pub/sub.
 *
 * Publie sur:
 * - "storage:save_session"      : Save work session
 * - "storage:save_app_usage"    : Save app usage record
 * - "storage:save_conversation" : Save conversation
 * - "storage:update_metrics"    : Update daily metrics
 *
 * Souscrit a:
 * - "scheduler:task_completed"  : Log task completion
 * - "monitoring:app_changed"    : Log app change
 * - "storage:session_saved"     : Session saved confirmation
 * - "storage:error"             : Storage error
 */
class StorageModule : public grove::IModule {
public:
    StorageModule();
    ~StorageModule() 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 "StorageModule"; }
    bool isIdle() const override { return true; }
    int getVersion() const override { return 2; }

private:
    // Note structure for in-memory storage
    struct Note {
        std::string id;
        std::string content;
        std::string timestamp;
        std::vector<std::string> tags;
    };

    // State
    int m_lastSessionId = 0;
    int m_pendingSaves = 0;
    int m_totalSaved = 0;
    std::vector<Note> m_notes;

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

    // Helpers
    void processMessages();
    void handleTaskCompleted(const grove::IDataNode& data);
    void handleAppChanged(const grove::IDataNode& data);
    void handleSessionSaved(const grove::IDataNode& data);
    void handleStorageError(const grove::IDataNode& data);

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

} // namespace celuna

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