import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { sql } from "@/db";

// AI observability feed over ai_usage: headline totals, per-intent latency &
// cost breakdown (incl. p95), daily trend, and the slowest recent calls.
export async function GET(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const days = Math.min(Math.max(parseInt(searchParams.get("days") || "30", 10) || 30, 1), 365);

  try {
    const summaryRows = await sql`
      SELECT
        COUNT(*)::int AS total_calls,
        COALESCE(SUM(total_tokens), 0)::int AS total_tokens,
        COALESCE(SUM(cost_estimate_paise), 0)::numeric AS total_cost_paise,
        COUNT(DISTINCT family_id)::int AS families_using_ai,
        COALESCE(AVG(duration_ms), 0)::int AS avg_ms,
        COALESCE(percentile_cont(0.95) WITHIN GROUP (ORDER BY duration_ms), 0)::int AS p95_ms,
        COUNT(*) FILTER (WHERE intent = 'medical_redirect')::int AS redirects
      FROM ai_usage
      WHERE created_at > NOW() - make_interval(days => ${days})
    `;

    const byIntent = await sql`
      SELECT
        COALESCE(intent, 'unknown') AS intent,
        COUNT(*)::int AS count,
        COALESCE(AVG(duration_ms), 0)::int AS avg_ms,
        COALESCE(percentile_cont(0.95) WITHIN GROUP (ORDER BY duration_ms), 0)::int AS p95_ms,
        COALESCE(SUM(total_tokens), 0)::int AS tokens,
        COALESCE(SUM(cost_estimate_paise), 0)::numeric AS cost_paise
      FROM ai_usage
      WHERE created_at > NOW() - make_interval(days => ${days})
      GROUP BY intent
      ORDER BY count DESC
    `;

    const byDay = await sql`
      SELECT DATE(created_at) AS date, COUNT(*)::int AS count,
             COALESCE(SUM(cost_estimate_paise), 0)::numeric AS cost_paise
      FROM ai_usage
      WHERE created_at > NOW() - make_interval(days => ${days})
      GROUP BY DATE(created_at)
      ORDER BY date
    `;

    const slowest = await sql`
      SELECT id, COALESCE(intent, 'unknown') AS intent, duration_ms, model_used, created_at, family_id
      FROM ai_usage
      WHERE created_at > NOW() - make_interval(days => ${days}) AND duration_ms IS NOT NULL
      ORDER BY duration_ms DESC
      LIMIT 10
    `;

    const s = summaryRows[0] || {};
    return NextResponse.json({
      days,
      summary: {
        totalCalls: Number(s.total_calls) || 0,
        totalTokens: Number(s.total_tokens) || 0,
        totalCostPaise: Number(s.total_cost_paise) || 0,
        familiesUsingAI: Number(s.families_using_ai) || 0,
        avgMs: Number(s.avg_ms) || 0,
        p95Ms: Number(s.p95_ms) || 0,
        redirects: Number(s.redirects) || 0,
      },
      byIntent: byIntent.map((r: Record<string, unknown>) => ({
        intent: r.intent,
        count: Number(r.count) || 0,
        avgMs: Number(r.avg_ms) || 0,
        p95Ms: Number(r.p95_ms) || 0,
        tokens: Number(r.tokens) || 0,
        costPaise: Number(r.cost_paise) || 0,
      })),
      byDay: byDay.map((r: Record<string, unknown>) => ({
        date: r.date instanceof Date ? r.date.toISOString().split("T")[0] : String(r.date).split("T")[0],
        count: Number(r.count) || 0,
        costPaise: Number(r.cost_paise) || 0,
      })),
      slowest: slowest.map((r: Record<string, unknown>) => ({
        id: r.id,
        intent: r.intent,
        durationMs: Number(r.duration_ms) || 0,
        model: r.model_used || "—",
        createdAt: r.created_at instanceof Date ? (r.created_at as Date).toISOString() : String(r.created_at),
        familyId: r.family_id,
      })),
    });
  } catch (error) {
    console.error("Admin AI feed error:", error);
    return NextResponse.json({
      days,
      summary: { totalCalls: 0, totalTokens: 0, totalCostPaise: 0, familiesUsingAI: 0, avgMs: 0, p95Ms: 0, redirects: 0 },
      byIntent: [], byDay: [], slowest: [], error: String(error),
    });
  }
}
