/** * Chart Suggestion Service * Frontend service for calling the AI chart suggestions API */ export interface ChartSuggestion { type: 'bar' | 'horizontal-bar' | 'line' | 'area' | 'pie' | 'radar' | 'funnel' | 'gauge' title: string data: { label: string; value: number }[] description: string rationale?: string } export interface SuggestChartsResponse { suggestions: ChartSuggestion[] analyzedText: string detectedData: string hasData: boolean error?: string quotaExceeded?: boolean } export interface SuggestChartsRequest { content: string selection?: string | null noteId?: string } /** * Call the AI chart suggestions API * @param request - The request parameters * @returns Promise with the chart suggestions */ export async function suggestCharts(request: SuggestChartsRequest): Promise { try { const response = await fetch('/api/ai/suggest-charts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) if (!response.ok) { const errorData = await response.json().catch(() => ({ error: 'Unknown error' })) const isQuotaError = response.status === 402 || errorData.error === 'QUOTA_EXCEEDED' return { suggestions: [], analyzedText: '', detectedData: '', hasData: false, error: isQuotaError ? 'AI quota exceeded. Please upgrade your plan to continue using AI features.' : (errorData.error || `HTTP ${response.status}`), quotaExceeded: isQuotaError, } } const data = await response.json() return data as SuggestChartsResponse } catch (error) { console.error('[suggestCharts] Network error:', error) return { suggestions: [], analyzedText: '', detectedData: '', hasData: false, error: error instanceof Error ? error.message : 'Network error', } } } /** * Convert a chart suggestion to raw chart format (no markdown ticks) * This is the content that goes inside * @param suggestion - The chart suggestion to convert * @returns Raw chart content string */ export function chartSuggestionToMarkdown(suggestion: ChartSuggestion): string { const lines = [ suggestion.type, suggestion.title, ...suggestion.data.map(d => `${d.label}: ${d.value}`), ] return lines.join('\n') }