import type { ServerMetrics } from '../types';

export const fetchServerMetrics = async (serverUrl: string): Promise<ServerMetrics> => {
  // 测量客户端到服务器的延迟（使用健康检查端点）
  const clientToServerLatency = await measureLatency(`${serverUrl}/api/health`);
  
  // 并行请求各个端点
  const endpoints = [
    '/api/metrics/cpu',
    '/api/metrics/memory',
    '/api/metrics/storage',
    '/api/metrics/gpu',
    '/api/metrics/network',
    '/api/metrics/system',
    '/api/metrics/docker',
    '/api/metrics/latency',
  ];

  const results = await Promise.all(
    endpoints.map(endpoint =>
      fetch(`${serverUrl}${endpoint}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then(res => {
          if (!res.ok) throw new Error(`Failed to fetch ${endpoint}`);
          return res.json();
        })
        .catch(err => {
          console.error(`Error fetching ${endpoint}:`, err);
          return null;
        })
    )
  );

  // 合并所有结果
  const [cpuRes, memRes, storageRes, gpuRes, networkRes, systemRes, dockerRes, latencyRes] = results;

  const system = systemRes?.data || {};
  const docker = dockerRes?.data || {};
  const latency = latencyRes?.data || {};
  
  // 将 docker 数据合并到 system.dockerStats
  return {
    hostname: system.hostname || 'Unknown',
    timestamp: new Date().toISOString(),
    cpu: cpuRes?.data || {},
    memory: memRes?.data || {},
    storage: storageRes?.data || [],
    gpu: gpuRes?.data || [],
    network: networkRes?.data || [],
    system: {
      ...system,
      dockerStats: docker
    },
    os: system.os || { kernel: '', distro: '', architecture: '' },
    uptimeSeconds: system.uptimeSeconds || 0,
    latency: {
      clientToServer: clientToServerLatency,
      external: latency.external || {},
    },
  };
};

// 测量延迟
async function measureLatency(url: string): Promise<number> {
  try {
    const startTime = performance.now();
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    const endTime = performance.now();
    
    if (response.ok) {
      return Math.round(endTime - startTime);
    }
    return -1; // 表示失败
  } catch {
    return -1; // 表示超时或失败
  }
}

export const checkServerHealth = async (serverUrl: string): Promise<boolean> => {
  try {
    const url = `${serverUrl}/api/health`;
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.ok;
  } catch {
    return false;
  }
};
