import type { Client } from 'ssh2'
import { execCommand, kibToGiB, toFixedNum } from './common.js'

export async function collectMemoryMetrics(
  client: Client,
): Promise<{ percent: number | null; usedGiB: number | null; totalGiB: number | null }> {
  try {
    const { stdout } = await execCommand(client, 'cat /proc/meminfo')
    const totalKb = Number(stdout.match(/^MemTotal:\s+(\d+)/m)?.[1])
    const availKb = Number(stdout.match(/^MemAvailable:\s+(\d+)/m)?.[1])
    if (!Number.isFinite(totalKb) || !Number.isFinite(availKb) || totalKb <= 0) {
      return { percent: null, usedGiB: null, totalGiB: null }
    }
    const usedKb = totalKb - availKb
    return {
      percent: toFixedNum((usedKb / totalKb) * 100),
      usedGiB: toFixedNum(kibToGiB(usedKb)),
      totalGiB: toFixedNum(kibToGiB(totalKb)),
    }
  } catch {
    return { percent: null, usedGiB: null, totalGiB: null }
  }
}
