const { test } = require('node:test');
const assert = require('node:assert/strict');

const { normalizeMcpSearchResponse, normalizeMcpMultimodalResponse } = require('../src/utils/clinicalRetrieval');

test('clinical retrieval replaces known internal PDF title with document title', () => {
  const results = normalizeMcpSearchResponse({
    results: [{
      id: 1586022,
      doc_type: 'file',
      title: 'FABK010-fm[i-xiv].qxd',
      excerpt: 'Respiratory disease text',
      page_number: 320
    }]
  });

  assert.equal(results[0].title, 'Respiratory Disease');
  assert.equal(results[0].page, 320);
});

test('clinical retrieval prefers file basename for internal PDF production titles', () => {
  const results = normalizeMcpMultimodalResponse({
    results: [{
      id: 99,
      doc_type: 'file',
      title: 'chapter-layout.qxd',
      file_path: 'Medical Library/Critical%20care%20%26%20Respiratory/Respiratory%20Disease.pdf',
      visual_caption: 'Airway diagram',
      page_number: 12
    }]
  });

  assert.equal(results[0].title, 'Respiratory Disease');
});

test('clinical retrieval leaves normal source titles unchanged', () => {
  const results = normalizeMcpSearchResponse({
    results: [{
      id: 123,
      doc_type: 'file',
      title: 'Nelson Textbook of Pediatrics.pdf',
      excerpt: 'Clinical text'
    }]
  });

  assert.equal(results[0].title, 'Nelson Textbook of Pediatrics');
});

test('clinical retrieval always prefers file basename over PDF metadata title', () => {
  const results = normalizeMcpSearchResponse({
    results: [{
      id: 321,
      doc_type: 'file',
      title: 'Dermatology, Second Edition: 2-Volume Set (Bolognia, Dermatology)',
      file_path: 'Medical Library/Dermatology/My%20Named%20Dermatology%20Source.pdf',
      excerpt: 'Dermatologic therapy text'
    }]
  });

  assert.equal(results[0].title, 'My Named Dermatology Source');
});

test('clinical retrieval prefers file basename for URL PDF metadata titles', () => {
  const results = normalizeMcpSearchResponse({
    results: [{
      id: 456,
      doc_type: 'file',
      title: 'https://bookbaz.ir',
      file_path: 'Medical Library/Dermatology/Bolognia%20Dermatology%20Second%20Edition.pdf',
      excerpt: 'Dermatologic therapy text'
    }]
  });

  assert.equal(results[0].title, 'Bolognia Dermatology Second Edition');
});

test('clinical retrieval strips image markdown while preserving OCR table text', () => {
  const results = normalizeMcpSearchResponse({
    results: [{
      id: 1585684,
      doc_type: 'file',
      title: 'Nelson Textbook of Pediatrics.pdf',
      excerpt: '~~Table 13.1~~\n\n![](/tmp/pdf-images/pdf-0132-02.png)\n\nAGE STREAMS OF DEVELOPMENT<br>2 mo row'
    }]
  });

  assert.match(results[0].excerpt, /Table 13\.1/);
  assert.match(results[0].excerpt, /AGE STREAMS OF DEVELOPMENT/);
  assert.doesNotMatch(results[0].excerpt, /pdf-images|!\[\]/);
});
