// Tiny driver for the DS3231 clock module (no library needed).
// The module keeps UTC; the ESP32 adds the time zone itself, as before.
#pragma once
#include <Wire.h>
#include <time.h>

class Ds3231 {
 public:
  // Checks the module answers at 0x68 (its memory chip at 0x57 is not used).
  bool present() {
    Wire.beginTransmission(ADDR);
    found_ = Wire.endTransmission() == 0;
    return found_;
  }
  // Seconds since 1970 (UTC), or 0 if the module is missing, has never been set,
  // or its coin cell ran out (the chip's "oscillator stopped" flag is then set).
  time_t read() {
    uint8_t r[7], status;
    if (!found_ || !regs(0x0F, &status, 1) || (status & 0x80) || !regs(0x00, r, 7)) return 0;
    if (r[2] & 0x40) return 0;                     // 12-hour mode: set by some other program
    int sec = bcd(r[0] & 0x7F), min = bcd(r[1] & 0x7F), hour = bcd(r[2] & 0x3F);
    int day = bcd(r[4] & 0x3F), mon = bcd(r[5] & 0x1F), year = 2000 + bcd(r[6]);
    if (sec > 59 || min > 59 || hour > 23 || day < 1 || day > 31 || mon < 1 || mon > 12) return 0;
    return (time_t)daysSince1970(year, mon, day) * 86400 + hour * 3600L + min * 60L + sec;  // 64-bit: past 2038
  }
  // Stores t (UTC) and clears the "oscillator stopped" flag.
  void write(time_t t) {
    if (!found_) return;
    struct tm u;
    gmtime_r(&t, &u);
    Wire.beginTransmission(ADDR);
    Wire.write(0x00);
    Wire.write(dec(u.tm_sec));
    Wire.write(dec(u.tm_min));
    Wire.write(dec(u.tm_hour));                    // bit 6 = 0: 24-hour mode
    Wire.write(u.tm_wday + 1);
    Wire.write(dec(u.tm_mday));
    Wire.write(dec(u.tm_mon + 1));
    Wire.write(dec(u.tm_year - 100));              // 2000-2099
    Wire.endTransmission();
    uint8_t status;
    if (regs(0x0F, &status, 1)) {
      Wire.beginTransmission(ADDR);
      Wire.write(0x0F);
      Wire.write(status & 0x7F);
      Wire.endTransmission();
    }
  }

  // Days from 1970-01-01 to the given date (works for any year from 2000 on).
  static long daysSince1970(int y, int m, int d) {
    y -= m <= 2;
    long era = y / 400;
    int yoe = y - era * 400;
    int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
    long doe = yoe * 365L + yoe / 4 - yoe / 100 + doy;
    return era * 146097L + doe - 719468L;
  }

 private:
  static const uint8_t ADDR = 0x68;
  bool found_ = false;
  static int bcd(uint8_t v) { return (v >> 4) * 10 + (v & 0x0F); }
  static uint8_t dec(int v) { return ((v / 10) << 4) | (v % 10); }
  bool regs(uint8_t reg, uint8_t *buf, uint8_t n) {
    Wire.beginTransmission(ADDR);
    Wire.write(reg);
    if (Wire.endTransmission(false) != 0 || Wire.requestFrom(ADDR, n) != n) return false;
    for (uint8_t i = 0; i < n; i++) buf[i] = Wire.read();
    return true;
  }
};
