import { cacheLife } from "next/cache"
import { prisma } from "@/lib/prisma"

export interface RecentTrace {
  traceId: string
  lastSeenAt: Date
  functionName: string | null
  filePath: string | null
}

export async function getRecentTraces(): Promise<RecentTrace[]> {
  "use cache"
  cacheLife("frequent")

  const distinctTraces = await prisma.llm_calls.groupBy({
    by: ["trace_id"],
    where: { trace_id: { not: "" } },
    orderBy: { _max: { created_at: "desc" } },
    take: 10,
    _max: { created_at: true },
  })

  type DistinctTrace = { trace_id: string | null; _max: { created_at: Date | null } }
  const traceIds = (distinctTraces as DistinctTrace[])
    .map((t: DistinctTrace) => t.trace_id)
    .filter((id: string | null): id is string => id != null && id.trim().length > 0)

  if (traceIds.length === 0) return []

  const events = await prisma.optimization_events.findMany({
    where: { trace_id: { in: traceIds } },
    select: { trace_id: true, function_name: true, file_path: true },
  })

  type EventRow = {
    trace_id: string | null
    function_name: string | null
    file_path: string | null
  }
  const eventMap = new Map(
    (events as EventRow[]).map((e: EventRow) => [
      e.trace_id,
      { functionName: e.function_name, filePath: e.file_path },
    ]),
  )

  const traceMap = new Map(
    (distinctTraces as DistinctTrace[]).map((t: DistinctTrace) => [t.trace_id, t]),
  )

  return traceIds.map((id: string) => {
    const trace = traceMap.get(id)!
    return {
      traceId: id,
      lastSeenAt: trace._max.created_at ?? new Date(),
      functionName: eventMap.get(id)?.functionName ?? null,
      filePath: eventMap.get(id)?.filePath ?? null,
    }
  })
}
