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

export interface KnowledgeFeedbackListItem {
  knowledge_id: string;
  action: FeedbackAction;
  eval_status?: string;
  feedback_text?: string;
  source: {
    trace_id: string;
    goal_id?: string;
    sequence?: number;
    feedback_by: string;
    feedback_at: string;
  };
}

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;
    project_name?: 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",
    });
  },
  compactTrace(traceId: string) {
    return request<{ previous_count: number; new_count: number; message: string }>(`/api/traces/${traceId}/compact`, {
      method: "POST",
    });
  },
  reflectTrace(traceId: string, data: { focus?: string | null } = {}) {
    return request<{ trace_id: string; reflection: string }>(`/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`);
  },
  uploadTraces(file: File) {
    const formData = new FormData();
    formData.append("file", file);
    return request<{
      success: boolean;
      message: string;
      imported_traces: string[];
      failed_traces: Array<{ trace_id: string; reason: string }>;
    }>("/api/traces/upload", {
      method: "POST",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },
  fetchKnowledgeLog(traceId: string) {
    return request<{ trace_id: string; entries: KnowledgeLogEntry[] }>(
      `/api/traces/${traceId}/knowledge_log`
    );
  },
  submitKnowledgeFeedback(
    traceId: string,
    data: { feedback_list: KnowledgeFeedbackListItem[] }
  ) {
    return request<{ status: string; updated: number }>(
      `/api/traces/${traceId}/knowledge_feedback`,
      { method: "POST", data }
    );
  },
};
