"use strict";
// Watchdog — Daemon health monitor + auto-restart
// Runs as separate process, minimal footprint (~15MB)
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const http = __importStar(require("http"));
const path_1 = __importDefault(require("path"));
const HEALTH_URL = 'http://localhost:9876/health';
const PING_INTERVAL = 5000;
const MAX_FAILURES = 3;
const MAX_RESTARTS = 5;
const RESTART_WINDOW_MS = 600000;
let daemonProcess = null;
let failureCount = 0;
let restartCount = 0;
let restartWindowStart = Date.now();
function checkHealth() {
    return new Promise(resolve => {
        const req = http.get(HEALTH_URL, res => { resolve(res.statusCode === 200); });
        req.on('error', () => resolve(false));
        req.setTimeout(3000, () => { req.destroy(); resolve(false); });
    });
}
function startDaemon() {
    const safeEnv = { NODE_OPTIONS: '--max-old-space-size=256', PATH: process.env.PATH || '', HOME: process.env.HOME || '', USERPROFILE: process.env.USERPROFILE || '' };
    daemonProcess = (0, child_process_1.spawn)('node', [path_1.default.resolve(__dirname, 'server.js')], { stdio: ['ignore', 'pipe', 'pipe'], env: safeEnv });
    daemonProcess.stdout?.on('data', (d) => process.stdout.write(`[daemon] ${d}`));
    daemonProcess.stderr?.on('data', (d) => process.stderr.write(`[daemon:err] ${d}`));
    daemonProcess.on('exit', (code) => { console.log(`Daemon exited with code ${code}`); daemonProcess = null; });
}
async function monitor() {
    const healthy = await checkHealth();
    if (healthy) {
        failureCount = 0;
        return;
    }
    failureCount++;
    if (failureCount >= MAX_FAILURES) {
        const now = Date.now();
        if (now - restartWindowStart > RESTART_WINDOW_MS) {
            restartCount = 0;
            restartWindowStart = now;
        }
        if (restartCount >= MAX_RESTARTS) {
            console.error('Max restarts reached. Alert user.');
            process.exit(1);
        }
        console.log('Daemon unhealthy. Restarting...');
        if (daemonProcess) {
            daemonProcess.kill('SIGTERM');
            await new Promise(r => setTimeout(r, 2000));
        }
        startDaemon();
        restartCount++;
        failureCount = 0;
        await new Promise(r => setTimeout(r, 3000));
    }
}
startDaemon();
setInterval(monitor, PING_INTERVAL);
console.log('Watchdog started. Monitoring daemon...');
//# sourceMappingURL=watchdog.js.map