"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.remoteMetricsPoller = void 0;
const remote_connection_1 = require("./remote-connection");
const remote_metrics_db_1 = require("./remote-metrics-db");
// @group Configuration : Polling interval in milliseconds
const POLL_INTERVAL_MS = 30000; // 30 seconds
// @group RemoteMetricsPoller : Background service that samples PM2 metrics for every connected remote server
class RemoteMetricsPoller {
    constructor() {
        this.timer = null;
    }
    // @group RemoteMetricsPoller : Start the periodic polling loop
    start() {
        if (this.timer)
            return; // already running
        console.log('[RemoteMetricsPoller] Starting — polling every', POLL_INTERVAL_MS / 1000, 's');
        this.timer = setInterval(() => this.poll(), POLL_INTERVAL_MS);
    }
    // @group RemoteMetricsPoller : Stop the polling loop
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }
    // @group RemoteMetricsPoller : Poll all currently-connected remote servers and persist metrics
    async poll() {
        var _a;
        const connectionsMap = remote_connection_1.remoteConnectionManager.getAllConnections();
        const connected = Array.from(connectionsMap.entries()).filter(([, c]) => c.isConnected());
        if (connected.length === 0)
            return;
        const now = Date.now();
        for (const [connectionId, conn] of connected) {
            try {
                const processes = await conn.getPM2Processes();
                if (!Array.isArray(processes) || processes.length === 0)
                    continue;
                const rows = processes
                    .filter(p => p && p.name)
                    .map(p => {
                    var _a, _b, _c, _d, _e, _f, _g, _h;
                    return ({
                        connection_id: connectionId,
                        connection_name: (_a = conn.name) !== null && _a !== void 0 ? _a : conn.host,
                        process_name: p.name,
                        pm_id: (_b = p.pm_id) !== null && _b !== void 0 ? _b : -1,
                        timestamp: now,
                        cpu: parseFloat(((_d = (_c = p.monit) === null || _c === void 0 ? void 0 : _c.cpu) !== null && _d !== void 0 ? _d : 0).toFixed(2)),
                        memory_bytes: ((_f = (_e = p.monit) === null || _e === void 0 ? void 0 : _e.memory) !== null && _f !== void 0 ? _f : 0),
                        memory_mb: parseFloat((((_h = (_g = p.monit) === null || _g === void 0 ? void 0 : _g.memory) !== null && _h !== void 0 ? _h : 0) / 1048576).toFixed(2)),
                    });
                });
                if (rows.length > 0) {
                    remote_metrics_db_1.remoteMetricsDB.insertBatch(rows);
                }
            }
            catch (err) {
                // Non-fatal — log and continue with other servers
                console.warn(`[RemoteMetricsPoller] Failed to poll ${conn.host}:`, (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err);
            }
        }
    }
}
// @group Exports : Singleton poller started once when the server boots
exports.remoteMetricsPoller = new RemoteMetricsPoller();
