/** Format watch probe byte rates for display. */

export interface WatchMetricsLike {
  probe_status?: string | null
}

/** 监测已开启但尚未收到任何探针回传（含失败态） */
export function isWatchMetricsPending(metrics: WatchMetricsLike | null | undefined): boolean {
  const status = metrics?.probe_status
  return status == null || status === ''
}

export function formatBytesPerSec(bps: number | null | undefined): string {
  if (bps == null || bps < 0) return '—'
  if (bps < 1024) return `${bps} B/s`
  if (bps < 1024 * 1024) return `${(bps / 1024).toFixed(1)} KB/s`
  return `${(bps / 1024 / 1024).toFixed(1)} MB/s`
}

/** Linux 1 分钟平均负载（宝塔「负载」同源） */
export function formatLoadAvg(load: number | null | undefined): string {
  if (load == null || Number.isNaN(load)) return '—'
  return load.toFixed(2)
}

export function loadAvgColor(load: number | null | undefined): string {
  if (load == null || Number.isNaN(load)) return 'grey'
  if (load >= 2) return 'error'
  if (load >= 1) return 'warning'
  return 'success'
}

export function formatRemaining(sec: number | null | undefined): string {
  if (sec == null || sec <= 0) return '已到期'
  const h = Math.floor(sec / 3600)
  const m = Math.floor((sec % 3600) / 60)
  if (h > 0) return `${h}h ${m}m`
  return `${m}m ${sec % 60}s`
}

const PROBE_STATUS_LABELS: Record<string, string> = {
  ok: '正常',
  parse_error: '探针解析失败',
  ssh_timeout: 'SSH 超时',
  ssh_auth: 'SSH 认证失败',
  no_cred: '无凭据',
  redis_stale: 'Agent 心跳过期',
  offline: '离线',
}

const PROBE_ERROR_EXACT: Record<string, string> = {
  parse_error: '探针返回数据无法解析',
  'psutil missing': '子机未安装 psutil',
  ssh_probe_failed: 'SSH 探针脚本执行失败',
  'SSH watch probe failed': 'SSH 监测探针失败',
  'SSH probe failed': 'SSH 探针失败',
  timeout: '连接超时',
  '探针失败': '探针失败',
  '无 Agent 且 SSH 探针失败': '无 Agent 且 SSH 探针失败',
  '服务器不存在': '服务器不存在',
}

/** Probe status code → Chinese label. */
export function probeStatusLabel(status: string | null | undefined): string {
  if (!status || status === 'ok') return PROBE_STATUS_LABELS.ok
  if (PROBE_STATUS_LABELS[status]) return PROBE_STATUS_LABELS[status]
  if (status.startsWith('parse_error')) return PROBE_STATUS_LABELS.parse_error
  return status
}

/** Probe source code → Chinese label. */
export function probeSourceLabel(source: string | null | undefined): string {
  if (!source) return '—'
  const map: Record<string, string> = {
    redis: 'Agent',
    ssh: 'SSH',
    mixed: 'Agent+SSH',
  }
  return map[source] ?? source
}

/** Error detail → Chinese (covers legacy English rows in DB). */
export function formatProbeError(
  error: string | null | undefined,
  status?: string | null,
): string {
  if (!error?.trim()) {
    if (status && status !== 'ok') return probeStatusLabel(status)
    return '—'
  }

  const text = error.trim()
  if (PROBE_ERROR_EXACT[text]) return PROBE_ERROR_EXACT[text]

  const lower = text.toLowerCase()
  if (lower.startsWith('parse_error')) {
    const detail = text.includes(':') ? text.split(':').slice(1).join(':').trim() : ''
    if (detail && PROBE_ERROR_EXACT[detail]) {
      return `探针返回数据无法解析：${PROBE_ERROR_EXACT[detail]}`
    }
    if (detail) return `探针返回数据无法解析：${detail}`
    return PROBE_ERROR_EXACT.parse_error
  }
  if (lower.includes('timed out') || lower.endsWith('timeout')) {
    return `SSH 连接超时：${text}`
  }
  if (lower.includes('permission denied') || lower.includes('authentication failed')) {
    return `SSH 认证失败：${text}`
  }
  if (lower.includes('psutil missing')) {
    return PROBE_ERROR_EXACT['psutil missing']
  }
  if (lower.includes('ssh_probe_failed') || lower.includes('ssh watch probe failed')) {
    return PROBE_ERROR_EXACT.ssh_probe_failed
  }
  if (/[\u4e00-\u9fff]/.test(text)) return text
  return `探针异常：${text}`
}

/** True when probe error indicates missing psutil on the remote host. */
export function isPsutilMissingError(
  error: string | null | undefined,
  status?: string | null,
): boolean {
  const text = (error || '').toLowerCase()
  if (text.includes('psutil missing')) return true
  if (status?.toLowerCase().includes('parse_error') && text.includes('psutil')) return true
  return false
}

export function probeStatusColor(status: string | null | undefined): string {
  if (!status || status === 'ok') return 'success'
  if (status.includes('timeout') || status.includes('auth')) return 'warning'
  return 'error'
}

/** Status filter options for probe records table. */
export const PROBE_STATUS_FILTER_ITEMS = [
  { title: '全部状态', value: null as string | null },
  { title: '正常', value: 'ok' },
  { title: 'SSH 超时', value: 'ssh_timeout' },
  { title: '探针解析失败', value: 'parse_error' },
  { title: '无凭据', value: 'no_cred' },
  { title: '离线', value: 'offline' },
]
