#ifndef DIDACTYL_SIGNER_HEALTH_H
#define DIDACTYL_SIGNER_HEALTH_H

#include <time.h>

/* Signer runtime health tracking (Phase 4 item 18/19).
 *
 * Lightweight process-global state recording whether the active signer
 * provider (local or remote n_signer) is currently considered healthy,
 * along with the last error reason and timestamp. This is surfaced via
 * the HTTP /api/status endpoint so an operator can detect a signing
 * outage out-of-band (without requiring a signed admin DM to come back).
 *
 * The state is intentionally minimal and lock-protected; it is updated
 * from central signer call paths (nostr_handler self-encrypt/decrypt,
 * DM encrypt/decrypt, main.c startup connectivity check). It is NOT a
 * full health-check daemon: it reflects the outcome of the last signer
 * operation that was attempted.
 */

typedef enum {
    SIGNER_HEALTH_UNKNOWN = 0,   /* no signer operation attempted yet */
    SIGNER_HEALTH_HEALTHY = 1,
    SIGNER_HEALTH_UNHEALTHY = 2
} signer_health_state_t;

#define SIGNER_HEALTH_REASON_LEN 256

typedef struct {
    signer_health_state_t state;
    char mode[32];                                  /* snapshot of cfg.signer.mode */
    char last_reason[SIGNER_HEALTH_REASON_LEN];     /* human-readable last error */
    time_t last_error_ts;                           /* unix ts of last unhealthy transition */
    time_t last_ok_ts;                              /* unix ts of last healthy observation */
} signer_health_snapshot_t;

/* Record the configured signer mode at startup. Call once after the
 * signer is constructed. Safe to call multiple times. */
void signer_health_set_mode(const char* mode);

/* Mark the signer healthy and record a successful operation timestamp.
 * Emits a one-line warning if this is a transition from unhealthy -> healthy. */
void signer_health_record_ok(void);

/* Mark the signer unhealthy with a reason string and the nostr error code
 * (from nostr_common.h). The reason is formatted as "<classification>: <detail>".
 * Emits a one-line warning if this is a transition from healthy -> unhealthy.
 * Pass rc=0 only if you do not have a nostr error code (the detail string
 * should then fully describe the failure). */
void signer_health_record_failure(int nostr_rc, const char* detail);

/* Thread-safe snapshot copy for the HTTP status endpoint. Returns 0 on
 * success, -1 if out is NULL. */
int signer_health_snapshot(signer_health_snapshot_t* out);

/* Reset state (used by tests / reinit). */
void signer_health_reset(void);

#endif /* DIDACTYL_SIGNER_HEALTH_H */
