import fs from 'node:fs/promises';
import type { DocumentFormat } from '../types.js';

// Lazy import — pdf-parse has side effects on module load
async function getPdfParse() {
  const mod = await import('pdf-parse');
  return mod.default ?? mod;
}

export async function extract(filePath: string, format: DocumentFormat): Promise<string> {
  let fileBuffer: Buffer;
  try {
    fileBuffer = await fs.readFile(filePath);
  } catch {
    throw new Error('file_not_found');
  }

  if (format === 'txt' || format === 'md') {
    return fileBuffer.toString('utf-8');
  }

  // PDF — collect one text string per page via pagerender callback
  const pdfParse = await getPdfParse();
  const pageTexts: string[] = [];

  await pdfParse(fileBuffer, {
    pagerender: (pageData: { getTextContent: () => Promise<{ items: Array<{ str: string }> }> }) =>
      pageData.getTextContent().then(tc => {
        const text = tc.items.map(i => i.str).join(' ').trim();
        if (text) pageTexts.push(text);
        return text;
      }),
  });

  if (pageTexts.length === 0) {
    throw new Error('pdf_extraction_empty');
  }

  return pageTexts.join('\n\n---PAGE---\n\n');
}
