import { readFile } from 'fs/promises' import { extname, basename } from 'path' import mammoth from 'mammoth' import pdfParse from 'pdf-parse' // Garde le contenu dans une taille raisonnable pour le contexte de conversation (cout/latence). const MAX_CHARS = 12000 export interface ExtractedDocument { name: string text: string truncated: boolean } export async function extractText(filePath: string): Promise { const name = basename(filePath) const ext = extname(filePath).toLowerCase() let text: string switch (ext) { case '.txt': case '.md': case '.csv': text = await readFile(filePath, 'utf-8') break case '.docx': { const buffer = await readFile(filePath) const result = await mammoth.extractRawText({ buffer }) text = result.value break } case '.pdf': { const buffer = await readFile(filePath) const result = await pdfParse(buffer) text = result.text break } default: throw new Error(`Format de fichier non supporte : ${ext || '(sans extension)'}`) } const truncated = text.length > MAX_CHARS return { name, text: truncated ? text.slice(0, MAX_CHARS) : text, truncated } }