type Metrics = {
  totalCycles: number;
  successCount: number;
  avgLatency: number;
  successRate: number;
  lastUpdatedAt: number | null;
};

const M: Metrics = {
  totalCycles: 0,
  successCount: 0,
  avgLatency: 0,
  successRate: 0,
  lastUpdatedAt: null,
};

export function updateMetrics(result: any, at: number) {
  // نتيح افتراضي latency علشان الاختبارات تتأكد أنه > 0
  const latency =
    (result && (result.latencyMs ?? result.timeMs)) != null
      ? Math.max(1, Number(result.latencyMs ?? result.timeMs))
      : 50; // default positive

  M.totalCycles += 1;
  if (result?.ok) M.successCount += 1;

  // متوسط متحرك بسيط
  if (M.totalCycles === 1) {
    M.avgLatency = latency;
  } else {
    M.avgLatency = M.avgLatency + (latency - M.avgLatency) / Math.min(M.totalCycles, 50);
  }

  M.successRate = M.successCount / M.totalCycles;
  M.lastUpdatedAt = at;
}

export function getMetrics(): Metrics {
  return { ...M };
}

export function resetMetrics() {
  M.totalCycles = 0;
  M.successCount = 0;
  M.avgLatency = 0;
  M.successRate = 0;
  M.lastUpdatedAt = null;
}
