#pragma once
#include <cstdint>

// Owned by the WebSocket event task. Publish generation/readiness separately to
// senders; an authenticated target snapshot is required before controls resume.
struct CloudLinkState {
    uint32_t generation = 0, attempt = 0;
    uint64_t connected_ms = 0, outage_ms = 0;
    bool transport = false, hello = false, target = false, recovering = false;

    void connecting() { ++attempt; }
    uint64_t connected(uint64_t now) {
        const auto recovery = recovering ? now - outage_ms : 0;
        ++generation; connected_ms = now; transport = true; hello = target = false;
        return recovery;
    }
    bool disconnected(uint64_t now) {
        const bool first = !recovering;
        if (first) { outage_ms = now; recovering = true; attempt = 0; }
        transport = hello = target = false;
        return first;
    }
    bool ready() const { return transport && hello && target; }
    uint64_t synchronized(uint64_t now) {
        const auto recovery = recovering ? now - outage_ms : 0;
        recovering = false; attempt = 0;
        return recovery;
    }
};

inline bool cloud_operation_current(uint32_t expected, uint32_t current, bool ready) {
    return ready && expected != 0 && expected == current;
}
