// Inventory nodegroups: composition + nominal machine specs + allocatable
// totals. Specs come from the pricing cache via the coverage artifact;
// older runs (or uncached types) fall back to an em dash, as do missing
// allocatable totals.

import type { InventoryNodegroup } from "@/engine/inventory";
import { num } from "@/lib/fmt";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";

function specText(instanceTypes: string[], specByType?: Record<string, string>): string {
  const specs = instanceTypes.map((t) => specByType?.[t]).filter((s): s is string => !!s);
  return specs.length > 0 ? specs.join(", ") : "—";
}

export function NodegroupTable({
  nodegroups,
  specByType,
}: {
  nodegroups: InventoryNodegroup[];
  specByType?: Record<string, string>;
}) {
  if (nodegroups.length === 0) {
    return <Empty>No nodegroups in the cluster inventory.</Empty>;
  }
  return (
    <DataTable>
      <thead>
        <tr>
          <Th>Nodegroup</Th>
          <Th numeric>Nodes</Th>
          <Th>Instance types</Th>
          <Th title="Nominal machine spec per instance type (vCPU c / GiB g), from the pricing cache">Spec</Th>
          <Th>Zone</Th>
          <Th numeric>Alloc CPU</Th>
          <Th numeric>Alloc mem</Th>
        </tr>
      </thead>
      <tbody>
        {nodegroups.map((ng) => (
          <tr key={`${ng.name}/${ng.zone}`} className="hover:bg-surface-1">
            <Td className="font-medium">{ng.name || <span className="text-text-muted">(unlabeled)</span>}</Td>
            <Td numeric>{num(ng.count)}</Td>
            <Td><span className="text-text-muted">{ng.instanceTypes.join(", ") || "—"}</span></Td>
            <Td><span className="tabular-nums">{specText(ng.instanceTypes, specByType)}</span></Td>
            <Td><span className="text-text-muted">{ng.zone || "—"}</span></Td>
            <Td numeric>{typeof ng.allocatableCpuTotal === "number" ? `${ng.allocatableCpuTotal.toFixed(1)} cores` : "—"}</Td>
            <Td numeric>{typeof ng.allocatableMemGibTotal === "number" ? `${ng.allocatableMemGibTotal.toFixed(1)} GiB` : "—"}</Td>
          </tr>
        ))}
      </tbody>
    </DataTable>
  );
}
