/**
 * Health & dependency check routes for cowork-service.
 *
 * GET /api/health/dependencies — checks platform-service + Rust runtime reachability.
 */

import type { FastifyInstance } from 'fastify';
import { config } from '../../lib/config.js';
import { PRODUCT_ID } from '../../lib/product-config.js';
import { getIpcBridge } from '../../lib/ipc-bridge.js';

export async function healthRoutes(app: FastifyInstance) {
  app.get('/api/health/dependencies', async (_req, reply) => {
    const checks: Record<string, { status: string; latencyMs?: number; error?: string }> = {};

    // Check platform-service
    const psStart = Date.now();
    try {
      const res = await fetch(`${config.PLATFORM_SERVICE_URL}/health`, {
        signal: AbortSignal.timeout(5_000),
      });
      checks['platform-service'] = {
        status: res.ok ? 'ok' : 'degraded',
        latencyMs: Date.now() - psStart,
      };
    } catch (err) {
      checks['platform-service'] = {
        status: 'unreachable',
        latencyMs: Date.now() - psStart,
        error: err instanceof Error ? err.message : 'unknown',
      };
    }

    const ipcConnected = getIpcBridge().isRunning;
    const depsOk = Object.values(checks).every(c => c.status === 'ok');
    const allOk = depsOk && ipcConnected;
    reply.code(allOk ? 200 : 503);
    return {
      status: allOk ? 'ok' : 'degraded',
      service: config.SERVICE_NAME,
      productId: PRODUCT_ID,
      ipcBridge: ipcConnected ? 'connected' : 'disconnected',
      checks,
      timestamp: new Date().toISOString(),
    };
  });
}
