import fs from 'node:fs';
import os from 'node:os';
let previousSample = null;
function takeCpuSample() {
    let idle = 0;
    let total = 0;
    for (const cpu of os.cpus()) {
        const t = cpu.times;
        idle += t.idle;
        total += t.user + t.nice + t.sys + t.idle + t.irq;
    }
    return { idle, total };
}
export function collectSystemStats(diskPath = process.cwd()) {
    const sample = takeCpuSample();
    let cpuPercent = null;
    if (previousSample !== null) {
        const totalDelta = sample.total - previousSample.total;
        const idleDelta = sample.idle - previousSample.idle;
        if (totalDelta > 0) {
            const busy = Math.max(0, 1 - idleDelta / totalDelta);
            cpuPercent = Math.round(busy * 1000) / 10;
        }
    }
    previousSample = sample;
    const totalBytes = os.totalmem();
    const freeBytes = os.freemem();
    const usedBytes = Math.max(0, totalBytes - freeBytes);
    const memoryPercent = totalBytes > 0 ? Math.round((usedBytes / totalBytes) * 1000) / 10 : 0;
    const disk = readDiskUsage(diskPath);
    const swap = readSwapUsage();
    return {
        cpuPercent,
        memoryPercent,
        memoryUsedBytes: usedBytes,
        memoryTotalBytes: totalBytes,
        diskPercent: disk?.percent ?? null,
        diskUsedBytes: disk?.usedBytes ?? null,
        diskTotalBytes: disk?.totalBytes ?? null,
        swapPercent: swap?.percent ?? null,
        swapUsedBytes: swap?.usedBytes ?? null,
        swapTotalBytes: swap?.totalBytes ?? null,
        cores: os.cpus().length
    };
}
function readDiskUsage(diskPath) {
    try {
        const stats = fs.statfsSync(diskPath);
        const totalBytes = stats.blocks * stats.bsize;
        const availableBytes = stats.bavail * stats.bsize;
        const usedBytes = Math.max(0, totalBytes - availableBytes);
        return byteUsage(usedBytes, totalBytes);
    }
    catch {
        return null;
    }
}
function readSwapUsage() {
    let raw;
    try {
        raw = fs.readFileSync('/proc/meminfo', 'utf8');
    }
    catch {
        return null;
    }
    const totalKb = readMeminfoKb(raw, 'SwapTotal');
    const freeKb = readMeminfoKb(raw, 'SwapFree');
    if (totalKb === null || freeKb === null) {
        return null;
    }
    const totalBytes = totalKb * 1024;
    const usedBytes = Math.max(0, totalBytes - freeKb * 1024);
    return byteUsage(usedBytes, totalBytes);
}
function readMeminfoKb(raw, key) {
    const match = raw.match(new RegExp(`^${key}:\\s+(\\d+)\\s+kB$`, 'm'));
    if (!match) {
        return null;
    }
    const value = Number(match[1]);
    return Number.isFinite(value) && value >= 0 ? value : null;
}
function byteUsage(usedBytes, totalBytes) {
    return {
        usedBytes,
        totalBytes,
        percent: totalBytes > 0 ? Math.round((usedBytes / totalBytes) * 1000) / 10 : 0
    };
}
//# sourceMappingURL=stats.js.map