import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { extractAttachmentText } from './mindspace-attachment-text.mjs';

test('extractAttachmentText returns text for plain text', () => {
  const result = extractAttachmentText(Buffer.from('hello\nworld\n'), 'text/plain', 'note.txt');
  assert.equal(result.format, 'text');
  assert.equal(result.text, 'hello\nworld\n');
  assert.deepEqual(result.warnings, []);
});

test('extractAttachmentText extracts docx text', async () => {
  const docPath = path.join(process.cwd(), 'MindSpace/john/oa/端午感怀.docx');
  let buffer;
  try {
    buffer = await fs.readFile(docPath);
  } catch {
    return;
  }
  const result = extractAttachmentText(
    buffer,
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    '端午感怀.docx',
  );
  assert.equal(result.format, 'docx');
  assert.match(result.text, /端午/);
});

test('extractAttachmentText extracts simple pdf text streams', () => {
  const pdf = Buffer.from(
    '%PDF-1.4\n1 0 obj\n<<>>\nstream\nBT (Hello PDF) Tj ET\nendstream\nendobj\n%%EOF',
    'latin1',
  );
  const result = extractAttachmentText(pdf, 'application/pdf', 'demo.pdf');
  assert.equal(result.format, 'pdf');
  assert.match(result.text, /Hello PDF/);
});
