/*
 * time.h — system clock access via ESTEX $21 / $22.
 *
 *   getdatetime() — read current date/time into a datetime_t.
 *   setdatetime() — set system clock from a datetime_t.
 *                   Returns 0 on success, -1 with errno set on failure.
 *
 * Date/time is the raw Sprinter clock — no epoch conversion, no time_t.
 */

#ifndef TIME_H
#define TIME_H

#include <stdint.h>

typedef struct {
    uint8_t  day;       /* 1..31 */
    uint8_t  month;     /* 1..12 */
    uint16_t year;      /* full year, e.g. 2026 */
    uint8_t  hour;      /* 0..23 */
    uint8_t  minute;    /* 0..59 */
    uint8_t  second;    /* 0..59 */
    uint8_t  dow;       /* day of week, 1-based: 1=Sun..7=Sat — see DOW_* */
} datetime_t;

/* Sprinter ESTEX SYSTIME dow encoding (verified empirically):
 *   1-based, week starts on Sunday — matches DOS INT 21h AH=2A+1. */
#define DOW_SUN 1
#define DOW_MON 2
#define DOW_TUE 3
#define DOW_WED 4
#define DOW_THU 5
#define DOW_FRI 6
#define DOW_SAT 7

void getdatetime(datetime_t *dt);
int  setdatetime(const datetime_t *dt);

/* ------------------------------------------------------------------
 * POSIX <time.h> API — implemented by SDCC's z80.lib (time.rel etc.).
 * We provide RtcRead() in libc/io/time.c which bridges to getdatetime().
 *
 * Layout of struct tm matches SDCC's z80 ABI exactly (__TIME_UNSIGNED=1
 * variant): tm_sec/min/hour/mday/mon/wday/isdst/hundredth are 1 byte,
 * tm_year/tm_yday are 16-bit ints. Total 12 bytes.
 * ------------------------------------------------------------------ */

struct tm {
    unsigned char tm_sec;       /* 0..60 */
    unsigned char tm_min;       /* 0..59 */
    unsigned char tm_hour;      /* 0..23 */
    unsigned char tm_mday;      /* 1..31 */
    unsigned char tm_mon;       /* 0..11  (POSIX, not Sprinter native!) */
    int           tm_year;      /* years since 1900 */
    unsigned char tm_wday;      /* 0..6   (Sunday=0, POSIX) */
    int           tm_yday;      /* 0..365 */
    unsigned char tm_isdst;
    unsigned char tm_hundredth; /* SDCC extension; we leave 0 */
};

typedef unsigned long time_t;

time_t       time     (time_t *t);
struct tm   *gmtime   (time_t *timep);
struct tm   *localtime(time_t *timep);
time_t       mktime   (struct tm *timeptr);
char        *asctime  (struct tm *timeptr);
char        *ctime    (time_t *timep);

#endif
