import { getChatProvider } from '../factory' import { getSystemConfig } from '@/lib/config' export class MathFromTextService { async generate(description: string): Promise { if (!description?.trim()) { throw new Error('Description is required') } const systemPrompt = `You are a mathematician and LaTeX expert. Convert the user's natural language description into a single valid LaTeX equation. CRITICAL RULES: - Output ONLY the raw LaTeX code — no preamble, no explanation, no markdown fence, no \\[ or \\( delimiters. - Use standard amsmath/amssymb syntax. - Never output \\documentclass, \\begin{document}, or $$ delimiters. Examples: - "the quadratic formula" -> x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} - "Pythagorean theorem" -> a^2 + b^2 = c^2 - "Euler's identity" -> e^{i\\pi} + 1 = 0 - "la dérivée de x au carré" -> \\frac{d}{dx} x^2 = 2x` const userPrompt = `Convert this to LaTeX:\n\n${description}` const config = await getSystemConfig() const provider = getChatProvider(config) const fullPrompt = `${systemPrompt}\n\n${userPrompt}` const raw = await provider.generateText(fullPrompt) return this.extractLatex(raw) } private extractLatex(response: string): string { const codeBlock = response.match(/```(?:latex|tex|math)?\n([\s\S]+?)\n```/) if (codeBlock) return codeBlock[1].trim() return response .replace(/^\\\[|\\\]$/g, '') .replace(/^\\\(|\\\)$/g, '') .replace(/^\$\$|\$\$$/g, '') .trim() } } export const mathFromTextService = new MathFromTextService()