File size: 6,487 Bytes
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/**
 * Hook for managing context documents with basic fetch operations
 */

import { useState, useCallback } from "react";
import {
  ContextDocument,
  CreateContextRequest,
  UpdateContextRequest,
  ContextDocumentResponse,
  ContextDocumentType,
} from "@/types/context";

interface UseContextDocumentsReturn {
  documents: ContextDocument[];
  loading: boolean;
  error: string | null;
  createDocument: (
    traceId: string,
    request: CreateContextRequest
  ) => Promise<ContextDocument | null>;
  updateDocument: (
    traceId: string,
    contextId: string,
    updates: UpdateContextRequest
  ) => Promise<ContextDocument | null>;
  deleteDocument: (traceId: string, contextId: string) => Promise<boolean>;
  uploadFile: (
    traceId: string,
    file: File,
    title: string,
    documentType: ContextDocumentType
  ) => Promise<ContextDocument | null>;
  loadDocuments: (traceId: string) => Promise<void>;
  refreshDocuments: (traceId: string) => Promise<void>;
}

const API_BASE = "/api";

async function fetchApi<T>(
  endpoint: string,
  options?: RequestInit
): Promise<T> {
  const url = `${API_BASE}${endpoint}`;

  const response = await fetch(url, {
    headers: {
      "Content-Type": "application/json",
      ...options?.headers,
    },
    ...options,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`API Error: ${response.statusText} - ${errorText}`);
  }

  const data = await response.json();
  return data;
}

export function useContextDocuments(): UseContextDocumentsReturn {
  const [documents, setDocuments] = useState<ContextDocument[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleError = useCallback((err: any, defaultMessage: string) => {
    const message = err?.message || defaultMessage;
    setError(message);
    console.error(defaultMessage, err);
    return null;
  }, []);

  const loadDocuments = useCallback(
    async (traceId: string) => {
      setLoading(true);
      setError(null);

      try {
        const documents = await fetchApi<ContextDocument[]>(
          `/traces/${traceId}/context`
        );
        setDocuments(documents || []);
      } catch (err) {
        handleError(err, "Failed to load context documents");
      } finally {
        setLoading(false);
      }
    },
    [handleError]
  );

  const refreshDocuments = useCallback(
    async (traceId: string) => {
      await loadDocuments(traceId);
    },
    [loadDocuments]
  );

  const createDocument = useCallback(
    async (
      traceId: string,
      request: CreateContextRequest
    ): Promise<ContextDocument | null> => {
      setLoading(true);
      setError(null);

      try {
        const response = await fetchApi<ContextDocumentResponse>(
          `/traces/${traceId}/context`,
          {
            method: "POST",
            body: JSON.stringify(request),
          }
        );

        if (response.success && response.data) {
          setDocuments((prev) => [...prev, response.data!]);
          return response.data;
        } else {
          throw new Error(response.message || "Failed to create document");
        }
      } catch (err) {
        return handleError(err, "Failed to create context document");
      } finally {
        setLoading(false);
      }
    },
    [handleError]
  );

  const updateDocument = useCallback(
    async (
      traceId: string,
      contextId: string,
      updates: UpdateContextRequest
    ): Promise<ContextDocument | null> => {
      setLoading(true);
      setError(null);

      try {
        const response = await fetchApi<ContextDocumentResponse>(
          `/traces/${traceId}/context/${contextId}`,
          {
            method: "PUT",
            body: JSON.stringify(updates),
          }
        );

        if (response.success && response.data) {
          setDocuments((prev) =>
            prev.map((doc) => (doc.id === contextId ? response.data! : doc))
          );
          return response.data;
        } else {
          throw new Error(response.message || "Failed to update document");
        }
      } catch (err) {
        return handleError(err, "Failed to update context document");
      } finally {
        setLoading(false);
      }
    },
    [handleError]
  );

  const deleteDocument = useCallback(
    async (traceId: string, contextId: string): Promise<boolean> => {
      setLoading(true);
      setError(null);

      try {
        const response = await fetchApi<ContextDocumentResponse>(
          `/traces/${traceId}/context/${contextId}`,
          {
            method: "DELETE",
          }
        );

        if (response.success) {
          setDocuments((prev) => prev.filter((doc) => doc.id !== contextId));
          return true;
        } else {
          throw new Error(response.message || "Failed to delete document");
        }
      } catch (err) {
        handleError(err, "Failed to delete context document");
        return false;
      } finally {
        setLoading(false);
      }
    },
    [handleError]
  );

  const uploadFile = useCallback(
    async (
      traceId: string,
      file: File,
      title: string,
      documentType: ContextDocumentType
    ): Promise<ContextDocument | null> => {
      setLoading(true);
      setError(null);

      try {
        const formData = new FormData();
        formData.append("file", file);
        formData.append("title", title);
        formData.append("document_type", documentType);

        const response = await fetch(
          `${API_BASE}/traces/${traceId}/context/upload`,
          {
            method: "POST",
            body: formData,
          }
        );

        if (!response.ok) {
          throw new Error(`Upload failed: ${response.statusText}`);
        }

        const result = (await response.json()) as ContextDocumentResponse;

        if (result.success && result.data) {
          setDocuments((prev) => [...prev, result.data!]);
          return result.data;
        } else {
          throw new Error(result.message || "Failed to upload file");
        }
      } catch (err) {
        return handleError(err, "Failed to upload context file");
      } finally {
        setLoading(false);
      }
    },
    [handleError]
  );

  return {
    documents,
    loading,
    error,
    createDocument,
    updateDocument,
    deleteDocument,
    uploadFile,
    loadDocuments,
    refreshDocuments,
  };
}