import { AnalysisOptions, AnalysisResult, ApiError, ColumnDetectionResult } from '../types'; const API_BASE = '/api'; async function handleResponse(response: Response): Promise { if (!response.ok) { let errorData: { detail?: { code: string; message: string; hints: string[] } | string }; try { errorData = await response.json(); } catch { throw { code: 'NETWORK_ERROR', message: `HTTP ${response.status}: ${response.statusText}`, hints: [] } as ApiError; } const detail = errorData?.detail; if (typeof detail === 'object' && detail !== null) { throw detail as ApiError; } throw { code: 'API_ERROR', message: typeof detail === 'string' ? detail : `Request failed with status ${response.status}`, hints: [], } as ApiError; } return response.json() as Promise; } export async function analyzeFiles( csvFile: File, harFile: File, options: AnalysisOptions, nameCol?: string, valueCol?: string ): Promise { const formData = new FormData(); formData.append('csv_file', csvFile); formData.append('har_file', harFile); formData.append('options_json', JSON.stringify(options)); if (nameCol) formData.append('name_col', nameCol); if (valueCol) formData.append('value_col', valueCol); const response = await fetch(`${API_BASE}/analyze`, { method: 'POST', body: formData, }); return handleResponse(response); } export async function loadDemo(): Promise { const response = await fetch(`${API_BASE}/demo`); return handleResponse(response); } export async function detectColumns(csvFile: File): Promise { const formData = new FormData(); formData.append('csv_file', csvFile); const response = await fetch(`${API_BASE}/columns`, { method: 'POST', body: formData, }); return handleResponse(response); } export async function exportReport( result: AnalysisResult, format: 'html' | 'json' | 'csv' ): Promise { const response = await fetch(`${API_BASE}/export/${format}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(result), }); if (!response.ok) { throw { code: 'EXPORT_ERROR', message: 'Export failed', hints: [] } as ApiError; } // Trigger download const blob = await response.blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; const ext = format === 'html' ? 'html' : format === 'json' ? 'json' : 'csv'; const contentDisp = response.headers.get('Content-Disposition'); const filename = contentDisp?.match(/filename="?([^"]+)"?/)?.[1] ?? `analysis-report.${ext}`; a.download = filename; a.click(); URL.revokeObjectURL(url); }