import { NextResponse } from 'next/server';

/**
 * GET /api/ai/node-health
 *
 * Calls the AI_001 node agent at /health using AI_NODE_API_KEY.
 * Returns the full JSON response from the node, or an error object if unreachable.
 */
export async function GET() {
  const endpoint = process.env.OLLAMA_ENDPOINT;
  const apiKey = process.env.AI_NODE_API_KEY;

  if (!endpoint) {
    return NextResponse.json(
      { ok: false, error: 'OLLAMA_ENDPOINT is not configured' },
      { status: 503 }
    );
  }

  const healthUrl = `${endpoint}/health`;

  try {
    const res = await fetch(healthUrl, {
      method: 'GET',
      headers: {
        ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
      },
      signal: AbortSignal.timeout(10_000),
    });

    const body = await res.json().catch(() => null);

    if (!res.ok) {
      return NextResponse.json(
        {
          ok: false,
          status: res.status,
          error: `AI_001 /health returned HTTP ${res.status}`,
          body,
        },
        { status: 503 }
      );
    }

    return NextResponse.json({ ok: true, status: res.status, body }, { status: 200 });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json(
      { ok: false, error: `AI_001 node unreachable: ${message}` },
      { status: 503 }
    );
  }
}
