import { api } from './http';

export interface RetrievedSnippet {
  fileName: string;
  chunkIndex: number;
  score: number;
  preview: string;
}

export interface ToolCallTrace {
  name: string;
  args: any;
  result: any;
}

export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  reasoning?: string | null;
  parentId?: string | null;
  createdAt: number;
  meta?: {
    retrieved?: RetrievedSnippet[];
    toolCalls?: ToolCallTrace[];
    aborted?: boolean;
    reasoning?: string;
    error?: string;
  } | null;
}

export interface BranchInfo {
  total: number;
  activeIndex: number;
  ids: string[];
}

export interface ChatHistoryResp {
  messages: ChatMessage[];
  branches: Record<string, BranchInfo>;
}

export const ChatAPI = {
  history: (agentId: string, sessionId?: string) =>
    api.get<ChatHistoryResp>(`/chat/${agentId}/messages`, { params: sessionId ? { sessionId } : {} }).then((r) => r.data),
  send: (agentId: string, content: string, sessionId?: string, model?: string, imageUrls?: string[]) =>
    api
      .post<{ user: ChatMessage; assistant: ChatMessage }>(`/chat/${agentId}/messages`, {
        content,
        sessionId,
        model,
        imageUrls
      })
      .then((r) => r.data),
  clear: (agentId: string, sessionId?: string) =>
    api.delete(`/chat/${agentId}/messages`, { params: sessionId ? { sessionId } : {} }).then((r) => r.data),
  switchBranch: (agentId: string, userMsgId: string, branchId: string) =>
    api.post(`/chat/${agentId}/messages/${userMsgId}/switch-branch`, { branchId }).then((r) => r.data)
};

export interface ChatAttachment {
  name: string;
  size: number;
  mime: string;
  text: string;
  truncated: boolean;
}

export const ChatAttachmentsAPI = {
  upload: (files: File[]) => {
    const fd = new FormData();
    files.forEach((f) => fd.append('files', f));
    return api.post<{ files: ChatAttachment[] }>('/chat/attachments', fd).then((r) => r.data);
  }
};

