#include "device_status.h"
#include "rx8130_time.h"
#include <array>
#include <cassert>
#include <cstdio>
#include <limits>

using namespace wearable;
int main() {
    RtcFields leap{2028,2,29,2,23,59,58};
    uint64_t epoch=0;assert(rtc_fields_to_epoch_ms(leap,epoch));
    RtcFields decoded;assert(epoch_ms_to_rtc_fields(epoch,decoded));
    assert(decoded.year==2028 && decoded.month==2 && decoded.day==29 && decoded.weekday==2);
    std::array<uint8_t,7> registers{};assert(encode_rx8130(epoch,registers.data(),registers.size()));
    assert(decode_rx8130(registers.data(),registers.size(),decoded));
    assert(decoded.hour==23 && decoded.minute==59 && decoded.second==58);

    auto corrupt=registers;corrupt[0]=0x7a;assert(!decode_rx8130(corrupt.data(),corrupt.size(),decoded));
    for(auto& value:corrupt) value=0;
    assert(!decode_rx8130(corrupt.data(),corrupt.size(),decoded));
    corrupt[0]=0;corrupt[1]=0;corrupt[2]=0;corrupt[3]=3;corrupt[4]=1;corrupt[5]=1;corrupt[6]=0x28;
    assert(!decode_rx8130(corrupt.data(),corrupt.size(),decoded));
    RtcFields invalid_date{2025,2,29,6,0,0,0};assert(!rtc_fields_to_epoch_ms(invalid_date,epoch));

    // Cold boot can seed from RTC; monotonic time advances while offline.
    WallClock clock;assert(clock.sync(1791072000000.0,100,480));
    assert(clock.utc_ms(5100)==1791072005000ULL);
    assert(clock.local_ms(5100)==1791072005000LL+480*60000LL);
    // Reconnect replaces both UTC and offset. Invalid truth never destroys it.
    assert(clock.sync(1791075600000.0,6000,-300));
    assert(clock.local_ms(7000)==1791075601000LL-300*60000LL);
    assert(!clock.sync(1,8000,0));
    assert(!clock.sync(1791075600000.0,8000,900));
    assert(clock.timezone_offset_minutes==-300 && clock.utc_ms(8000)==1791075602000ULL);
    std::puts("RX8130 BCD/date validation, cold boot, offline advance, reconnect resync PASS");
}
