"use strict";
/**
 * WatchdogHeartbeat — periodic liveness signal for external supervisors.
 *
 * Story 6.6 — OpenLife v1.2 Royal Stack.
 *
 * The daemon emits a heartbeat file every `intervalMs` so an external
 * supervisor (systemd `WatchdogSec=`, supervisord `eventlistener`, k8s
 * livenessProbe via a file mtime check) can detect hangs even when the
 * HTTP `/health` endpoint becomes unresponsive (e.g. event-loop block).
 *
 * Format: `.openlife/heartbeat.json` with `{ pid, host, ts, uptime_s,
 * startedAt }`. ts is updated atomically each tick so a torn read is
 * impossible.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.WatchdogHeartbeat = void 0;
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./AtomicWriter");
class WatchdogHeartbeat {
    filePath;
    intervalMs;
    startedAt;
    version;
    onTick;
    timer = null;
    constructor(opts = {}) {
        const stateDir = process.env.OPENLIFE_STATE_DIR || path.join(process.cwd(), '.openlife');
        this.filePath = opts.filePath || path.join(stateDir, 'heartbeat.json');
        this.intervalMs = opts.intervalMs ?? 30_000;
        this.startedAt = Date.now();
        this.version = opts.version;
        this.onTick = opts.onTick;
    }
    /**
     * Emit one heartbeat immediately and schedule periodic re-emission.
     * Idempotent: calling start() while already running is a no-op.
     */
    start() {
        if (this.timer)
            return;
        this.fireTick(); // immediate tick so external supervisor sees freshness on boot
        this.timer = setInterval(() => {
            this.fireTick();
        }, this.intervalMs);
        if (typeof this.timer.unref === 'function')
            this.timer.unref();
    }
    fireTick() {
        let rec;
        try {
            rec = this.emit();
        }
        catch {
            return; // swallow — best-effort writes
        }
        if (this.onTick) {
            try {
                this.onTick(rec);
            }
            catch (err) {
                console.error('[WATCHDOG] onTick callback threw:', err);
            }
        }
    }
    /**
     * Stop emitting heartbeats. Idempotent. Does not delete the heartbeat
     * file (so post-shutdown the supervisor still sees the last known
     * good ts; staleness is the supervisor's signal that we are down).
     */
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }
    /**
     * Force-emit one heartbeat now (used by tests and graceful shutdown).
     */
    emit() {
        const now = Date.now();
        const rec = {
            pid: process.pid,
            host: os.hostname(),
            ts: now,
            uptime_s: Math.floor((now - this.startedAt) / 1000),
            startedAt: this.startedAt,
            version: this.version,
        };
        (0, AtomicWriter_1.writeJsonAtomic)(this.filePath, rec);
        return rec;
    }
    /** Exposed for tests. */
    _filePath() {
        return this.filePath;
    }
}
exports.WatchdogHeartbeat = WatchdogHeartbeat;
