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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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import type {
  Episode,
  Observation,
  Action,
  Reward,
  Agent,
  MemoryState,
  MCPTool,
  SystemSettings,
  APIResponse,
  StepRequest,
  ResetRequest,
  EpisodeStats,
} from '@/types';

const API_BASE = '/api';

class APIError extends Error {
  constructor(
    message: string,
    public status: number,
    public data?: unknown
  ) {
    super(message);
    this.name = 'APIError';
  }
}

async function request<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE}${endpoint}`;
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    ...options.headers,
  };

  const response = await fetch(url, {
    ...options,
    headers,
  });

  const data = await response.json() as APIResponse<T>;

  if (!response.ok) {
    throw new APIError(
      data.error ?? 'An error occurred',
      response.status,
      data
    );
  }

  if (!data.success) {
    throw new APIError(data.error ?? 'Request failed', response.status, data);
  }

  return data.data as T;
}

// Scraping types
export interface ScrapeRequest {
  assets: string[];
  instructions: string;
  output_instructions: string;
  output_format: 'json' | 'csv' | 'markdown' | 'text';
  complexity: 'low' | 'medium' | 'high';
  model: string;
  provider: string;
  enable_memory: boolean;
  enable_plugins: string[];
  selected_agents: string[];
  max_steps: number;
  python_code?: string;
}

export interface ScrapeStep {
  step_number: number;
  action: string;
  url: string | null;
  status: string;
  message: string;
  reward: number;
  extracted_data: Record<string, unknown> | null;
  duration_ms: number | null;
  timestamp: string;
}

export interface ScrapeResponse {
  session_id: string;
  status: string;
  total_steps: number;
  total_reward: number;
  extracted_data: Record<string, unknown>;
  output: string;
  output_format: string;
  duration_seconds: number;
  urls_processed: number;
  errors: string[];
  selected_agents?: string[];
  sandbox_artifacts?: string[];
}

export interface StreamEvent {
  type: 'init' | 'url_start' | 'step' | 'url_complete' | 'complete' | 'error';
  session_id?: string;
  url?: string;
  index?: number;
  total?: number;
  data?: ScrapeStep | ScrapeResponse | { url: string; error: string };
}

export const apiClient = {
  // Episode Management
  async resetEpisode(params: ResetRequest): Promise<Episode> {
    return request<Episode>('/episode/reset', {
      method: 'POST',
      body: JSON.stringify(params),
    });
  },

  async getEpisode(episodeId: string): Promise<Episode> {
    return request<Episode>(`/episode/${episodeId}`);
  },

  async getCurrentEpisode(): Promise<Episode | null> {
    try {
      return await request<Episode>('/episode/current');
    } catch (error) {
      if (error instanceof APIError && error.status === 404) {
        return null;
      }
      throw error;
    }
  },

  async stepEpisode(episodeId: string, step: StepRequest): Promise<{
    observation: Observation;
    reward: Reward;
    done: boolean;
    info: Record<string, unknown>;
  }> {
    return request(`/episode/${episodeId}/step`, {
      method: 'POST',
      body: JSON.stringify(step),
    });
  },

  async terminateEpisode(episodeId: string): Promise<Episode> {
    return request<Episode>(`/episode/${episodeId}/terminate`, {
      method: 'POST',
    });
  },

  // State Queries
  async getState(episodeId: string): Promise<{
    observation: Observation;
    agents: Agent[];
    memory: MemoryState;
  }> {
    return request(`/episode/${episodeId}/state`);
  },

  async getObservation(episodeId: string, step?: number): Promise<Observation> {
    const query = step !== undefined ? `?step=${step}` : '';
    return request<Observation>(`/episode/${episodeId}/observation${query}`);
  },

  async getActions(episodeId: string): Promise<Action[]> {
    return request<Action[]>(`/episode/${episodeId}/actions`);
  },

  async getRewards(episodeId: string): Promise<Reward[]> {
    return request<Reward[]>(`/episode/${episodeId}/rewards`);
  },

  // Agent Management
  async getAgents(episodeId: string): Promise<Agent[]> {
    return request<Agent[]>(`/episode/${episodeId}/agents`);
  },

  async getAgent(episodeId: string, agentId: string): Promise<Agent> {
    return request<Agent>(`/episode/${episodeId}/agents/${agentId}`);
  },

  async updateAgent(
    episodeId: string,
    agentId: string,
    updates: Partial<Agent>
  ): Promise<Agent> {
    return request<Agent>(`/episode/${episodeId}/agents/${agentId}`, {
      method: 'PATCH',
      body: JSON.stringify(updates),
    });
  },

  // Memory Operations
  async getMemory(episodeId: string): Promise<MemoryState> {
    return request<MemoryState>(`/episode/${episodeId}/memory`);
  },

  async queryMemory(
    episodeId: string,
    query: string,
    layer?: string,
    limit?: number
  ): Promise<import('@/types').MemoryEntry[]> {
    const params = new URLSearchParams({ query });
    if (layer) params.set('layer', layer);
    if (limit) params.set('limit', limit.toString());
    return request(`/episode/${episodeId}/memory/query?${params}`);
  },

  async addMemory(
    episodeId: string,
    entry: Omit<import('@/types').MemoryEntry, 'id' | 'timestamp'>
  ): Promise<import('@/types').MemoryEntry> {
    return request(`/episode/${episodeId}/memory`, {
      method: 'POST',
      body: JSON.stringify(entry),
    });
  },

  async clearMemory(episodeId: string, layer?: string): Promise<void> {
    const query = layer ? `?layer=${layer}` : '';
    return request(`/episode/${episodeId}/memory${query}`, {
      method: 'DELETE',
    });
  },

  // Tools
  async getTools(): Promise<MCPTool[]> {
    return request<MCPTool[]>('/tools');
  },

  async getTool(name: string): Promise<MCPTool> {
    return request<MCPTool>(`/tools/${name}`);
  },

  async executeTool(
    name: string,
    parameters: Record<string, unknown>
  ): Promise<unknown> {
    return request(`/tools/${name}/execute`, {
      method: 'POST',
      body: JSON.stringify(parameters),
    });
  },

  async toggleTool(name: string, enabled: boolean): Promise<MCPTool> {
    return request<MCPTool>(`/tools/${name}`, {
      method: 'PATCH',
      body: JSON.stringify({ enabled }),
    });
  },

  // Settings
  async getSettings(): Promise<SystemSettings> {
    return request<SystemSettings>('/settings');
  },

  async updateSettings(settings: Partial<SystemSettings>): Promise<SystemSettings> {
    return request<SystemSettings>('/settings', {
      method: 'PATCH',
      body: JSON.stringify(settings),
    });
  },

  // Stats
  async getStats(): Promise<EpisodeStats> {
    return request<EpisodeStats>('/stats');
  },

  // Health Check
  async healthCheck(): Promise<{ status: string; version: string }> {
    const response = await fetch(`${API_BASE}/health`, { cache: 'no-store' });
    if (!response.ok) {
      throw new APIError('Health check failed', response.status);
    }
    const contentType = response.headers.get('content-type') || '';
    if (contentType.includes('application/json')) {
      return response.json();
    }

    const text = await response.text();
    try {
      return JSON.parse(text) as { status: string; version: string };
    } catch {
      return { status: 'healthy', version: 'unknown' };
    }
  },

  // Scraping with streaming
  streamScrape(
    scrapeRequest: ScrapeRequest,
    onInit?: (sessionId: string) => void,
    onUrlStart?: (url: string, index: number, total: number) => void,
    onStep?: (step: ScrapeStep) => void,
    onUrlComplete?: (url: string, index: number) => void,
    onComplete?: (response: ScrapeResponse) => void,
    onError?: (error: string, url?: string) => void
  ): { abort: () => void } {
    const abortController = new AbortController();

    fetch(`${API_BASE}/scrape/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(scrapeRequest),
      signal: abortController.signal,
    })
      .then(async (response) => {
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          onError?.(errorData.detail || 'Stream failed');
          return;
        }

        const reader = response.body?.getReader();
        if (!reader) {
          onError?.('No response body');
          return;
        }

        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const event: StreamEvent = JSON.parse(line.slice(6));
                
                switch (event.type) {
                  case 'init':
                    onInit?.(event.session_id!);
                    break;
                  case 'url_start':
                    onUrlStart?.(event.url!, event.index!, event.total!);
                    break;
                  case 'step':
                    onStep?.(event.data as ScrapeStep);
                    break;
                  case 'url_complete':
                    onUrlComplete?.(event.url!, event.index!);
                    break;
                  case 'complete':
                    onComplete?.(event.data as ScrapeResponse);
                    break;
                  case 'error':
                    const errData = event.data as { url: string; error: string };
                    onError?.(errData.error, errData.url);
                    break;
                }
              } catch {
                // Ignore parse errors
              }
            }
          }
        }
      })
      .catch((err) => {
        if (err.name !== 'AbortError') {
          onError?.(err.message || 'Stream failed');
        }
      });

    return { abort: () => abortController.abort() };
  },

  // Get scrape session status
  async getScrapeStatus(sessionId: string): Promise<{
    session_id: string;
    status: string;
    current_url_index: number;
    total_urls: number;
    total_reward: number;
    extracted_count: number;
    errors: string[];
    duration: number;
  }> {
    const response = await fetch(`${API_BASE}/scrape/${sessionId}/status`);
    if (!response.ok) {
      throw new APIError('Failed to get scrape status', response.status);
    }
    return response.json();
  },

  // Get scrape result
  async getScrapeResult(sessionId: string): Promise<ScrapeResponse> {
    const response = await fetch(`${API_BASE}/scrape/${sessionId}/result`);
    if (!response.ok) {
      throw new APIError('Failed to get scrape result', response.status);
    }
    return response.json();
  },
};

export { APIError };
export default apiClient;