#ifndef TIMEKEEPER_HPP
#define TIMEKEEPER_HPP

#include <Arduino.h>
#include <vector>
#include <algorithm>
#include <ArduinoJson.h>
#include <RTClib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

// Structure to hold scheduled events
struct ScheduledEvent {
    String timeStr;           // Time in "HH:MM:SS" format
    JsonObject eventData;     // Complete event data from JSON
    bool triggered = false;   // Flag to prevent multiple triggers
};

class Timekeeper {
private:
    // RTC object
    RTC_DS1307 rtc;

    // Event storage
    std::vector<ScheduledEvent> todaysEvents;
    std::vector<ScheduledEvent> tomorrowsEvents;

    // Clock management (using PCF8574 relays)
    int clockRelay1 = -1, clockRelay2 = -1;  // -1 means not assigned
    unsigned long lastClockPulse = 0;
    bool currentClockRelay = false; // false = relay1, true = relay2
    bool clockEnabled = false;  // Only enable when outputs are set

    // Function pointer for relay control
    void (*relayWriteFunc)(int relay, int state) = nullptr;

    // Task handles
    TaskHandle_t rtcTaskHandle = NULL;
    TaskHandle_t clockTaskHandle = NULL;
    TaskHandle_t schedulerTaskHandle = NULL;

public:
    // Main initialization (no clock outputs initially)
    void begin();

    // Set the relay control function
    void setRelayWriteFunction(void (*func)(int, int));

    // Set/change clock relay outputs after initialization
    void setClockOutputs(int relay1, int relay2);

    // Time management functions
    void setTime(unsigned long timestamp);  // Set RTC time from Unix timestamp
    unsigned long getTime();                // Get current time as Unix timestamp

    // Event management
    void loadTodaysEvents();
    void loadNextDayEvents();

    // Static task functions (required by FreeRTOS)
    static void rtcTask(void* parameter);
    static void clockTask(void* parameter);
    static void schedulerTask(void* parameter);

private:
    // Helper functions
    bool isSameDate(String eventDateTime, int year, int month, int day);
    void addToTodaysSchedule(JsonObject event);
    void sortEventsByTime();
    String getCurrentTimeString();

    // Core functionality
    void updateClock();
    void checkScheduledEvents();
    void triggerEvent(ScheduledEvent& event);
};

#endif
