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

export interface ProcessEntry {
  pid: string
  user: string
  cpu: string
  mem: string
  command: string
}

export async function collectProcessesMetrics(
  client: Client,
): Promise<{ total: number | null; running: number | null; top: ProcessEntry[] }> {
  let total: number | null = null
  let running: number | null = null
  const top: ProcessEntry[] = []

  try {
    const [psOut, countOut, runningOut] = await Promise.all([
      execCommand(client, 'ps aux --sort=-%cpu | head -n 11'),
      execCommand(client, 'ps aux | wc -l'),
      execCommand(client, "ps aux | grep -c ' R '"),
    ])

    const lines = psOut.stdout.split('\n').map((l) => l.trim()).filter(Boolean)
    for (let i = 1; i < Math.min(lines.length, 11); i++) {
      const parts = lines[i].split(/\s+/)
      if (parts.length >= 11) {
        top.push({
          pid: parts[1],
          user: parts[0],
          cpu: parts[2],
          mem: parts[3],
          command: parts.slice(10).join(' ').substring(0, 50),
        })
      }
    }

    const totalCount = Number(countOut.stdout.trim()) - 1
    total = Number.isFinite(totalCount) ? totalCount : null

    const runningCount = Number(runningOut.stdout.trim())
    running = Number.isFinite(runningCount) ? runningCount : null
  } catch {
    // best-effort
  }

  return { total, running, top }
}
