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

export async function getTraceData(tracePrefix: string) {
  "use cache"
  cacheLife("frequent")

  const [rawLlmCalls, errors, optimizationFeatures, optimizationEvent] = await Promise.all([
    prisma.llm_calls.findMany({
      where: { trace_id: { startsWith: tracePrefix } },
      orderBy: { created_at: "asc" },
      select: {
        id: true,
        trace_id: true,
        call_type: true,
        model_name: true,
        status: true,
        latency_ms: true,
        llm_cost: true,
        total_tokens: true,
        created_at: true,
        context: true,
      },
    }),
    prisma.optimization_errors.findMany({
      where: { trace_id: { startsWith: tracePrefix } },
      orderBy: { created_at: "asc" },
      select: {
        id: true,
        error_type: true,
        severity: true,
        error_message: true,
        context: true,
        created_at: true,
      },
    }),
    prisma.optimization_features.findFirst({
      where: { trace_id: { startsWith: tracePrefix } },
      select: {
        original_code: true,
        optimizations_post: true,
        explanations_post: true,
        optimizations_origin: true,
        ranking: true,
        pull_request: true,
        metadata: true,
        test_framework: true,
        generated_test: true,
        instrumented_generated_test: true,
        instrumented_perf_test: true,
        dependency_code: true,
      },
    }),
    prisma.optimization_events.findFirst({
      where: { trace_id: { startsWith: tracePrefix } },
      select: { event_type: true, function_name: true, file_path: true },
    }),
  ])
  return { rawLlmCalls, errors, optimizationFeatures, optimizationEvent }
}

export type TraceData = Awaited<ReturnType<typeof getTraceData>>
