#pragma once

#include "IService.hpp"
#include "../shared/platform/IWindowTracker.hpp"

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

#include <memory>
#include <string>

namespace celuna {

/**
 * @brief Platform Service - OS-specific APIs (window tracking, etc.)
 *
 * Handles platform-specific operations that can't be in hot-reload modules.
 * Polls foreground window at configurable interval.
 *
 * Subscribes to:
 * - "platform:query_window" : Request current window info
 *
 * Publishes:
 * - "platform:window_info"    : { appName, windowTitle, isIdle, idleSeconds }
 * - "platform:window_changed" : { oldApp, newApp, duration }
 * - "platform:idle_detected"  : { idleSeconds }
 * - "platform:activity_resumed" : {}
 */
class PlatformService : public IService {
public:
    PlatformService();
    ~PlatformService() override = default;

    bool initialize(grove::IIO* io) override;
    void process() override;
    void shutdown() override;
    std::string getName() const override { return "PlatformService"; }
    bool isHealthy() const override { return m_tracker != nullptr && m_tracker->isAvailable(); }

    /// Configure polling interval and idle threshold
    void configure(int pollIntervalMs = 1000, int idleThresholdSeconds = 300);

private:
    // Configuration
    int m_pollIntervalMs = 1000;
    int m_idleThresholdSeconds = 300;

    // State
    std::unique_ptr<IWindowTracker> m_tracker;
    std::string m_currentApp;
    std::string m_currentWindowTitle;
    float m_appStartTime = 0.0f;
    float m_lastPollTime = 0.0f;
    bool m_wasIdle = false;

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

    // Helpers
    void pollWindowInfo(float currentTime);
    void publishWindowInfo();
    void publishWindowChanged(const std::string& oldApp, const std::string& newApp, int duration);
};

} // namespace celuna
