export const formatBytes = (bytes: number): string => {
  if (bytes === 0 || bytes === null || bytes === undefined || isNaN(bytes) || !isFinite(bytes)) {
    return '0 B';
  }
  
  // 处理负数
  if (bytes < 0) {
    bytes = 0;
  }
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  
  // 处理小于 1 的情况
  if (bytes < 1) {
    return bytes.toFixed(2) + ' ' + sizes[0];
  }
  
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  // 确保索引在有效范围内
  const sizeIndex = Math.max(0, Math.min(i, sizes.length - 1));
  const value = Math.round((bytes / Math.pow(k, sizeIndex)) * 100) / 100;
  
  // 确保 sizes[sizeIndex] 存在
  const unit = sizes[sizeIndex] || sizes[0];
  
  return value + ' ' + unit;
};

export const formatUptime = (seconds: number): string => {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  const parts: string[] = [];
  if (days > 0) parts.push(`${days}天`);
  if (hours > 0) parts.push(`${hours}小时`);
  if (minutes > 0) parts.push(`${minutes}分钟`);
  
  return parts.length > 0 ? parts.join(' ') : '刚刚启动';
};

export const formatPercent = (value: number): string => {
  return `${Math.round(value * 10) / 10}%`;
};

/** 采集端上报的毫秒延迟（与 Go 侧 TCP 探测展示一致） */
export const formatLatencyMs = (ms: number): string => {
  if (!Number.isFinite(ms) || ms < 0) return '超时';
  if (ms < 1) return `${ms.toFixed(1)} ms`;
  return `${Math.round(ms)} ms`;
};
