"use strict";
/**
 * test_watchdog_heartbeat — Story 6.6 regression suite.
 *
 * Three scenarios:
 *   1. start() emits immediately and writes a fresh heartbeat file
 *   2. periodic emission updates `ts` after intervalMs elapses
 *   3. stop() halts emission; subsequent file mtime stays frozen
 *
 * Prints TEST_WATCHDOG_HEARTBEAT_OK on full pass.
 */
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 });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const WatchdogHeartbeat_1 = require("./orchestrator/util/WatchdogHeartbeat");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'wd-test-'));
}
function rmTmp(dir) {
    try {
        fs.rmSync(dir, { recursive: true, force: true });
    }
    catch { /* ignore */ }
}
function read(filePath) {
    return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
// ─────────────────────────────────────────────────────────────
// Scenario 1 — start() emits immediately
// ─────────────────────────────────────────────────────────────
function scenarioStartImmediate() {
    const tmp = mkTmp();
    const filePath = path.join(tmp, 'heartbeat.json');
    try {
        const wd = new WatchdogHeartbeat_1.WatchdogHeartbeat({ filePath, intervalMs: 100_000, version: '1.2.0' });
        wd.start();
        assert(fs.existsSync(filePath), 'heartbeat file must exist immediately after start()');
        const rec = read(filePath);
        assert(rec.pid === process.pid, 'pid round-trip');
        assert(typeof rec.ts === 'number' && rec.ts > 0, 'ts must be a positive ms epoch');
        assert(rec.uptime_s >= 0, 'uptime_s must be non-negative');
        assert(rec.version === '1.2.0', 'version round-trip');
        wd.stop();
        console.log('✅ scenario 1: start() emits immediately');
    }
    finally {
        rmTmp(tmp);
    }
}
// ─────────────────────────────────────────────────────────────
// Scenario 2 — periodic emission updates ts
// ─────────────────────────────────────────────────────────────
async function scenarioPeriodicEmission() {
    const tmp = mkTmp();
    const filePath = path.join(tmp, 'heartbeat.json');
    try {
        const wd = new WatchdogHeartbeat_1.WatchdogHeartbeat({ filePath, intervalMs: 50 });
        wd.start();
        const firstTs = read(filePath).ts;
        await sleep(180); // wait ~3 intervals
        const laterTs = read(filePath).ts;
        assert(laterTs > firstTs, `ts must advance after interval: first=${firstTs}, later=${laterTs}`);
        wd.stop();
        console.log('✅ scenario 2: periodic emission updates ts');
    }
    finally {
        rmTmp(tmp);
    }
}
// ─────────────────────────────────────────────────────────────
// Scenario 3 — stop() halts emission
// ─────────────────────────────────────────────────────────────
async function scenarioStopHalts() {
    const tmp = mkTmp();
    const filePath = path.join(tmp, 'heartbeat.json');
    try {
        const wd = new WatchdogHeartbeat_1.WatchdogHeartbeat({ filePath, intervalMs: 50 });
        wd.start();
        await sleep(70);
        const beforeStop = read(filePath).ts;
        wd.stop();
        await sleep(150); // would be 3 more intervals if still running
        const afterStop = read(filePath).ts;
        assert(afterStop === beforeStop, `ts must not change after stop(): before=${beforeStop}, after=${afterStop}`);
        // Idempotent stop
        wd.stop();
        // Manual emit after stop still works (graceful-shutdown final beat use case)
        wd.emit();
        const manual = read(filePath).ts;
        assert(manual >= afterStop, 'manual emit() after stop must succeed');
        console.log('✅ scenario 3: stop() halts emission, emit() still callable');
    }
    finally {
        rmTmp(tmp);
    }
}
// ─────────────────────────────────────────────────────────────
// Driver
// ─────────────────────────────────────────────────────────────
async function main() {
    console.log('🧪 test_watchdog_heartbeat — Story 6.6 regression suite');
    scenarioStartImmediate();
    await scenarioPeriodicEmission();
    await scenarioStopHalts();
    console.log('');
    console.log('TEST_WATCHDOG_HEARTBEAT_OK');
}
main().catch((err) => {
    console.error('❌ test_watchdog_heartbeat FAILED:', err instanceof Error ? err.message : err);
    process.exit(1);
});
