import { NextResponse } from "next/server";
import { logger } from "@/lib/logger";

/**
 * GET /api/metrics
 *
 * Proxies to llmhosts backend metrics endpoint.
 * Returns real-time proxy usage statistics for the Achievements page.
 */
export async function GET() {
  try {
    // Backend URL from environment or default to Docker service name
    const backendUrl = process.env.LLMHOSTS_BACKEND_URL || "http://llmhosts:4000";

    const res = await fetch(`${backendUrl}/api/metrics`, {
      headers: {
        "Accept": "application/json",
      },
    });

    if (!res.ok) {
      logger.error({ action: 'metrics_fetch', status: res.status, statusText: res.statusText }, 'Failed to fetch metrics from backend');
      return NextResponse.json(
        {
          uptime: 0,
          requests_total: 0,
          rpm: 0,
          cache_hit_rate: 0,
          avg_latency: 0,
          savings_total: 0,
          by_backend: {},
          by_model: [],
        },
        { status: 200 } // Return empty metrics instead of error
      );
    }

    const data = await res.json();
    return NextResponse.json(data);
  } catch (error) {
    logger.error({ err: error, action: 'metrics_fetch' }, 'Error fetching metrics from backend');
    // Return empty metrics on error instead of failing
    return NextResponse.json(
      {
        uptime: 0,
        requests_total: 0,
        rpm: 0,
        cache_hit_rate: 0,
        avg_latency: 0,
        savings_total: 0,
        by_backend: {},
        by_model: [],
      },
      { status: 200 }
    );
  }
}
