"use strict";
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.WatchdogService = void 0;
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const logger_1 = require("../logger");
class WatchdogService {
    constructor(config, logger) {
        this.timer = null;
        this.lagTimer = null;
        this.sdNotifyInterval = null;
        this.lastEventLoopCheck = Date.now();
        this.eventLoopLagMs = 0;
        this.config = {
            checkIntervalMs: 30000,
            maxMemoryMB: 512,
            maxEventLoopLagMs: 5000,
            enableOsWatchdog: true,
            ...config,
        };
        this.logger = logger || logger_1.logger;
    }
    start() {
        this.logger.info('[Watchdog] Starting watchdog service');
        this.timer = setInterval(() => this.check(), this.config.checkIntervalMs);
        this.measureEventLoopLag();
        if (this.config.enableOsWatchdog) {
            this.setupOsWatchdog();
        }
    }
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
        if (this.lagTimer) {
            clearTimeout(this.lagTimer);
            this.lagTimer = null;
        }
        if (this.sdNotifyInterval) {
            clearInterval(this.sdNotifyInterval);
            this.sdNotifyInterval = null;
        }
    }
    measureEventLoopLag() {
        const check = () => {
            const now = Date.now();
            const expected = this.lastEventLoopCheck + 1000;
            this.eventLoopLagMs = Math.max(0, now - expected);
            this.lastEventLoopCheck = now;
            this.lagTimer = setTimeout(check, 1000);
        };
        this.lagTimer = setTimeout(check, 1000);
    }
    check() {
        const memUsage = process.memoryUsage();
        const heapMB = Math.round(memUsage.heapUsed / 1024 / 1024);
        const rssMB = Math.round(memUsage.rss / 1024 / 1024);
        if (rssMB > this.config.maxMemoryMB) {
            this.logger.warn('[Watchdog] High memory usage', { rssMB, heapMB, maxMB: this.config.maxMemoryMB });
            if (global.gc) {
                this.logger.info('[Watchdog] Forcing garbage collection');
                global.gc();
            }
        }
        if (this.eventLoopLagMs > this.config.maxEventLoopLagMs) {
            this.logger.warn('[Watchdog] High event loop lag', { lagMs: this.eventLoopLagMs, maxMs: this.config.maxEventLoopLagMs });
        }
        this.checkDiskSpace();
    }
    checkDiskSpace() {
        if (process.platform === 'win32') {
            (0, child_process_1.exec)('wmic logicaldisk where "DeviceID=\'C:\'" get FreeSpace /value', { timeout: 5000, windowsHide: true }, (err, stdout) => {
                if (err)
                    return;
                const match = String(stdout).match(/FreeSpace=(\d+)/);
                if (match) {
                    const freeGB = parseInt(match[1], 10) / (1024 * 1024 * 1024);
                    if (freeGB < 1) {
                        this.logger.warn('[Watchdog] Low disk space', { freeGB: freeGB.toFixed(2) });
                    }
                }
            });
        }
        else {
            (0, child_process_1.exec)("df -BG / | tail -1 | awk '{print $4}'", { timeout: 5000 }, (err, stdout) => {
                if (err)
                    return;
                const freeGB = parseInt(String(stdout).replace('G', ''), 10);
                if (freeGB < 1) {
                    this.logger.warn('[Watchdog] Low disk space', { freeGB });
                }
            });
        }
    }
    setupOsWatchdog() {
        if (process.platform === 'win32') {
            this.setupWindowsWatchdog();
        }
        else {
            this.setupLinuxWatchdog();
        }
    }
    setupWindowsWatchdog() {
        const taskName = 'EmtelleAnalyticsWatchdog';
        const serviceName = process.env.APPSTATS_AGENT_SERVICE_NAME || 'AppStatsAgent';
        // installPath: dist/services/watchdog.js is two levels below install root
        const installPath = path.resolve(__dirname, '../..');
        // Step 1: write the watchdog action script — no quoting issues since it's a .ps1 file
        const watchdogCheckScript = path.join(installPath, 'watchdog-check.ps1');
        const checkPs = [
            `$svcName = '${serviceName}'`,
            `try {`,
            `  $svc = Get-Service -Name $svcName -ErrorAction SilentlyContinue`,
            `  if ($svc -and $svc.Status -ne 'Running') {`,
            `    Start-Service -Name $svcName -ErrorAction SilentlyContinue`,
            `  }`,
            `} catch {}`,
        ].join('\r\n');
        try {
            fs.writeFileSync(watchdogCheckScript, checkPs, 'utf8');
        }
        catch (e) {
            this.logger.warn('[Watchdog] Failed to write watchdog-check.ps1', { error: String(e) });
            return;
        }
        // Step 2: write the task-registration script to a temp file
        const escaped = watchdogCheckScript.replace(/'/g, "''");
        const setupPs = [
            `$taskName = '${taskName}'`,
            `$scriptPath = '${escaped}'`,
            `$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ('-NoProfile -WindowStyle Hidden -File "' + $scriptPath + '"')`,
            // RepetitionDuration MaxValue = repeat forever
            `$trigger = New-ScheduledTaskTrigger -RepetitionInterval (New-TimeSpan -Minutes 5) -Once -At (Get-Date).AddSeconds(10) -RepetitionDuration ([TimeSpan]::MaxValue)`,
            `$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 1)`,
            `$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest`,
            `Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null`,
            // Configure Windows Service failure recovery: restart on crash
            `try { sc.exe failure '${serviceName}' reset= 3600 actions= restart/5000/restart/10000/restart/30000 | Out-Null } catch {}`,
        ].join('\r\n');
        const tmpSetup = path.join(os.tmpdir(), `emtelle-watchdog-${process.pid}.ps1`);
        try {
            fs.writeFileSync(tmpSetup, setupPs, 'utf8');
        }
        catch (e) {
            this.logger.warn('[Watchdog] Failed to write watchdog setup script', { error: String(e) });
            return;
        }
        (0, child_process_1.exec)(`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "${tmpSetup}"`, { timeout: 30000, windowsHide: true }, (err) => {
            try {
                fs.unlinkSync(tmpSetup);
            }
            catch { }
            if (err) {
                this.logger.warn('[Watchdog] Failed to configure Windows scheduled task', { error: String(err.message || err) });
            }
            else {
                this.logger.info('[Watchdog] Windows watchdog scheduled task configured');
            }
        });
    }
    setupLinuxWatchdog() {
        // For systemd services, send sd_notify watchdog keepalive.
        // This works if the service unit has WatchdogSec= configured.
        try {
            const notifySocket = process.env.NOTIFY_SOCKET;
            if (notifySocket) {
                const dgram = require('dgram');
                this.sdNotifyInterval = setInterval(() => {
                    try {
                        const client = dgram.createSocket('unix_dgram');
                        client.send('WATCHDOG=1', notifySocket, () => client.close());
                    }
                    catch { /* best-effort */ }
                }, 15000);
                this.logger.info('[Watchdog] Systemd watchdog notify enabled');
            }
            else {
                this.logger.info('[Watchdog] No NOTIFY_SOCKET; systemd watchdog notify skipped');
            }
        }
        catch (e) {
            this.logger.warn('[Watchdog] Linux watchdog setup error', { error: String(e) });
        }
    }
    getStatus() {
        const mem = process.memoryUsage();
        return {
            heapMB: Math.round(mem.heapUsed / 1024 / 1024),
            rssMB: Math.round(mem.rss / 1024 / 1024),
            eventLoopLagMs: this.eventLoopLagMs,
            uptime: process.uptime(),
        };
    }
}
exports.WatchdogService = WatchdogService;
//# sourceMappingURL=watchdog.js.map