import { request } from "./client";
import type { TraceDetailResponse, TraceListResponse } from "../types/trace";

export const traceApi = {
  fetchTraces(params?: { status?: string; mode?: string; limit?: number }) {
    const query = new URLSearchParams();
    if (params?.status) query.set("status", params.status);
    if (params?.mode) query.set("mode", params.mode);
    if (typeof params?.limit === "number") query.set("limit", String(params.limit));
    const suffix = query.toString() ? `?${query.toString()}` : "";
    return request<TraceListResponse>(`/api/traces${suffix}`);
  },
  fetchTraceDetail(traceId: string) {
    return request<TraceDetailResponse>(`/api/traces/${traceId}`);
  },
  createTrace(data: {
    messages: Array<{ role: "system" | "user" | "assistant" | "tool"; content: unknown }>;
    model?: string;
    temperature?: number;
    max_iterations?: number;
    tools?: string[] | null;
    name?: string;
    uid?: string;
  }) {
    return request<{ trace_id: string }>("/api/traces", {
      method: "POST",
      data,
    });
  },
  runTrace(
    traceId: string,
    data?: {
      messages?: Array<{ role: "system" | "user" | "assistant" | "tool"; content: unknown }>;
      after_message_id?: string | null;
    },
  ) {
    return request<void>(`/api/traces/${traceId}/run`, {
      method: "POST",
      data,
    });
  },
  stopTrace(traceId: string) {
    return request<void>(`/api/traces/${traceId}/stop`, {
      method: "POST",
    });
  },
  reflectTrace(traceId: string, data?: { focus?: string | null }) {
    return request<void>(`/api/traces/${traceId}/reflect`, {
      method: "POST",
      data,
    });
  },
  getExperiences() {
    return request<string>("/api/experiences");
  },
  fetchExamples() {
    return request<{ projects: Array<{ name: string; path: string; has_prompt: boolean }> }>("/api/examples");
  },
  fetchExamplePrompt(projectName: string) {
    return request<{
      system_prompt: string;
      user_prompt: string;
      model?: string;
      temperature?: number;
    }>(`/api/examples/${projectName}/prompt`);
  },
};
