import { NextResponse } from 'next/server';

/**
 * GET /api/health
 *
 * System health check — chain connectivity, API status, uptime.
 * Agents should call this before committing to using the platform.
 */

const RPC: Record<string, string> = {
  base:      'https://mainnet.base.org',
  avalanche: 'https://api.avax.network/ext/bc/C/rpc',
  arbitrum:  'https://arb1.arbitrum.io/rpc',
  polygon:   'https://rpc-mainnet.matic.quiknode.pro',
};

const START_TIME = Date.now();

async function checkChain(chain: string, rpc: string): Promise<{
  chain: string;
  status: 'ok' | 'degraded' | 'down';
  latencyMs: number;
  blockNumber: number | null;
}> {
  const start = Date.now();
  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 8000);
    const res = await fetch(rpc, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [] }),
      signal: controller.signal,
    });
    clearTimeout(timeout);
    const json = await res.json();
    const latency = Date.now() - start;
    const blockNumber = json.result ? parseInt(json.result, 16) : null;
    return {
      chain,
      status: latency > 5000 ? 'degraded' : 'ok',
      latencyMs: latency,
      blockNumber,
    };
  } catch {
    return { chain, status: 'down', latencyMs: Date.now() - start, blockNumber: null };
  }
}

export async function GET() {
  const chains = await Promise.all(
    Object.entries(RPC).map(([chain, rpc]) => checkChain(chain, rpc)),
  );

  const allOk = chains.every(c => c.status === 'ok');
  const anyDown = chains.some(c => c.status === 'down');
  const overallStatus = anyDown ? 'degraded' : allOk ? 'healthy' : 'degraded';

  const uptimeMs = Date.now() - START_TIME;
  const uptimeHours = Math.round(uptimeMs / 3600000 * 10) / 10;

  return NextResponse.json({
    status: overallStatus,
    version: '3.3',
    protocol: 'vaultfire',
    uptime: { ms: uptimeMs, hours: uptimeHours },
    chains,
    endpoints: {
      api: 17,
      mcp: true,
      xmtp: true,
    },
    supportedChains: ['base', 'avalanche', 'arbitrum', 'polygon'],
    timestamp: new Date().toISOString(),
  }, {
    headers: {
      'Cache-Control': 'public, max-age=30',
    },
  });
}
