import { formatShanghaiDateTime, formatZhNumber } from './formatters';

export function formatTelemetryValue(value: unknown, displayValue?: string) {
  if (displayValue) return displayValue;
  if (typeof value === 'number' && Number.isFinite(value)) {
    return formatZhNumber(value, 2);
  }
  if (typeof value === 'boolean') return value ? '是' : '否';
  if (typeof value === 'string') return value || '—';
  return value == null ? '—' : String(value);
}

export function telemetryQualityLabel(quality: string) {
  if (quality === 'good') return '正常';
  if (quality === 'stale') return '陈旧';
  return '异常';
}

export function telemetryQualityColor(quality: string) {
  return quality === 'good' ? 'green' : quality === 'stale' ? 'orange' : 'red';
}

export function telemetryValueTypeLabel(value?: string) {
  const normalized = value?.trim().toLowerCase();
  if (!normalized) return '—';
  const labels: Record<string, string> = {
    array: '列表',
    boolean: '布尔值',
    dynamic: '动态值',
    number: '数值',
    numeric: '数值',
    object: '对象',
    string: '文本'
  };
  return labels[normalized] ?? value!;
}

export function formatTelemetryTime(value?: string) {
  if (!value) return '—';
  const local = formatShanghaiDateTime(value);
  return local.match(/[T ](\d{2}:\d{2}:\d{2})/)?.[1] ?? local;
}
