import { escapeAttr, escapeHtml } from './citations.js';

export function createAssistantExporter(options) {
  options = options || {};
  var exportCacheKey = '';
  var exportCacheItems = null;

  function invalidate() {
    exportCacheKey = '';
    exportCacheItems = null;
  }

  function exportAnswerPdf(state) {
    state = state || {};
    if (!state.lastAnswer) {
      if (typeof options.showToast === 'function') options.showToast('No answer to export', 'error');
      return;
    }
    var exportItems = collectExportItems(state.messages || [], state.lastAnswer, state.lastSources || []);
    var cacheKey = buildExportCacheKey(exportItems, state.lastGeneratedImageSrc || '');
    var doc = openExportWindow();
    if (!doc) {
      if (typeof options.showToast === 'function') options.showToast('Allow popups to export PDF', 'error');
      return;
    }
    if (exportCacheKey === cacheKey && exportCacheItems) {
      writePrintableChatExport(doc, exportCacheItems, state.lastGeneratedImageSrc || '');
      return;
    }
    exportCacheKey = cacheKey;
    exportCacheItems = exportItems;
    writePrintableChatExport(doc, exportItems, state.lastGeneratedImageSrc || '');
  }

  function openExportWindow() {
    var doc = window.open('', '_blank', 'width=900,height=1100');
    if (!doc) return null;
    doc.document.open();
    doc.document.write('<!doctype html><html><head><title>Preparing Clinical Assistant Export</title><style>body{font-family:Arial,sans-serif;color:#111827;margin:36px;line-height:1.5}.spinner{width:18px;height:18px;border:3px solid #e5e7eb;border-top-color:#7c3aed;border-radius:50%;display:inline-block;vertical-align:middle;margin-right:8px;animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><p><span class="spinner"></span>Preparing PDF export...</p></body></html>');
    doc.document.close();
    return doc;
  }

  function writePrintableChatExport(doc, items, imageSrc) {
    if (!doc || doc.closed) return;
    items = Array.isArray(items) && items.length ? items : [];
    var imageHtml = imageSrc ? '<h2>Generated Image</h2><div class="export-image"><img src="' + escapeAttr(imageSrc) + '" alt="Generated clinical visual"></div>' : '';
    var sections = items.map(function (item, idx) {
      var sources = Array.isArray(item.sources) ? item.sources : [];
      var heading = item.heading || deriveExportHeading(item.question, idx);
      var summary = item.summary || '';
      var answer = item.answer || '';
      var citedNumbers = extractCitedSourceNumbers([summary, answer].filter(Boolean).join('\n\n'));
      var refs = renderExportRefs(sources, idx + 1, citedNumbers);
      return '<section class="export-section">' +
        '<h2>' + escapeHtml(heading) + '</h2>' +
        '<div class="question"><strong>Question:</strong> ' + escapeHtml(item.question || '') + '</div>' +
        (summary ? '<h3>Summary</h3><div class="answer">' + renderMarkdown(summary, sources, { citationLabel: 'number' }) + '</div>' : '') +
        '<h3>Full Generated Answer</h3><div class="answer full-answer">' + renderMarkdown(answer, sources, { citationLabel: 'number' }) + '</div>' +
        (refs ? '<h3>References</h3><ol class="refs">' + refs + '</ol>' : '') +
        '</section>';
    }).join('');
    var html = '<!doctype html><html><head><title>Clinical Assistant Export</title>' +
      '<style>body{font-family:Arial,sans-serif;color:#111827;line-height:1.55;margin:36px;max-width:820px}h1{font-size:22px;margin:0 0 4px}h2{font-size:17px;margin-top:26px;border-bottom:1px solid #e5e7eb;padding-bottom:4px;break-after:avoid}h3{font-size:14px;margin:18px 0 8px;break-after:avoid}.meta,.question{font-size:12px;color:#6b7280;margin-bottom:12px}.answer{font-size:13px}.export-section{margin-top:20px;break-before:auto}.full-answer{page-break-before:auto}.export-image img{max-width:100%;border:1px solid #e5e7eb;border-radius:10px}.refs{font-size:12px;padding-left:20px;margin-top:8px;break-inside:auto}.refs li{margin:6px 0;break-inside:avoid}.assistant-cite{display:inline-flex;align-items:center;justify-content:center;min-width:16px;height:16px;padding:0 5px;margin:0 1px;border-radius:999px;background:#f3e8ff;color:#7c3aed;border:1px solid rgba(124,58,237,.22);font-size:9px;font-weight:800;line-height:16px;text-decoration:none;text-transform:uppercase;letter-spacing:.03em;vertical-align:baseline;white-space:nowrap;-webkit-print-color-adjust:exact;print-color-adjust:exact}.answer table{width:100%;border-collapse:collapse;table-layout:auto;margin:12px 0 18px;border:1px solid #e5e7eb;page-break-inside:auto}.answer th,.answer td{padding:7px 8px;border:1px solid #e5e7eb;text-align:left;vertical-align:top;word-break:normal;overflow-wrap:break-word}.answer th{background:#f9fafb;font-weight:700;-webkit-print-color-adjust:exact;print-color-adjust:exact}.answer th:last-child,.answer td:last-child{width:1%;white-space:nowrap}.answer tr{break-inside:avoid;page-break-inside:avoid}.answer thead{display:table-header-group}.answer tbody{display:table-row-group}.answer p{margin:8px 0}.answer ul,.answer ol{padding-left:20px}.answer li{margin:4px 0}@media print{button{display:none}body{margin:24mm}.export-section{break-inside:auto}.refs{break-before:avoid}}</style>' +
      '</head><body><button id="assistant-export-print" type="button" style="float:right;padding:8px 12px">Print / Save PDF</button><h1>Clinical Assistant Export</h1>' +
      '<div class="meta">Export generated ' + escapeHtml(new Date().toLocaleString()) + '</div>' +
      imageHtml +
      sections + '</body></html>';
    doc.document.open();
    doc.document.write(html);
    doc.document.close();
    try {
      var printBtn = doc.document.getElementById('assistant-export-print');
      if (printBtn) printBtn.addEventListener('click', function () { doc.focus(); doc.print(); });
    } catch (e) {}
    setTimeout(function () { try { doc.focus(); doc.print(); } catch (e) {} }, 500);
  }

  function renderMarkdown(md, sources, renderOptions) {
    if (typeof options.renderMarkdown === 'function') return options.renderMarkdown(md, sources, renderOptions);
    return escapeHtml(md);
  }

  return {
    exportAnswerPdf: exportAnswerPdf,
    invalidate: invalidate
  };
}

function collectExportItems(messages, lastAnswer, lastSources) {
  var items = [];
  var pendingQuestion = '';
  (messages || []).forEach(function (m) {
    if (m.role === 'user') {
      pendingQuestion = m.content || pendingQuestion;
      return;
    }
    if (m.role !== 'assistant' || !m.content) return;
    if (isUtilityAssistantMessage(m.content)) return;
    items.push({
      question: pendingQuestion || 'Clinical question',
      heading: deriveExportHeading(pendingQuestion, items.length),
      summary: '',
      answer: m.content,
      sources: Array.isArray(m.sources) && m.sources.length ? m.sources : lastSources
    });
    pendingQuestion = '';
  });
  if (!items.length && lastAnswer) {
    items.push({ question: 'Clinical question', heading: 'Clinical Answer', summary: '', answer: lastAnswer, sources: lastSources });
  }
  return items;
}

function renderExportRefs(sources, sectionNumber, citedNumbers) {
  var cited = citedNumbers && citedNumbers.length ? new Set(citedNumbers.map(String)) : null;
  return (sources || []).filter(function (s, idx) {
    var n = s.number || idx + 1;
    return !cited || cited.has(String(n));
  }).map(function (s, idx) {
    var n = s.number || idx + 1;
    var title = s.title || s.resource || 'Untitled source';
    var page = s.page || s.page_number || s.pageNumber;
    return '<li id="ref-' + sectionNumber + '-' + n + '"><strong>[' + n + ']</strong> ' + escapeHtml(title) + (page ? ', page ' + escapeHtml(page) : '') + '.</li>';
  }).join('');
}

function extractCitedSourceNumbers(text) {
  var found = new Set();
  String(text || '').replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g, function (_, nums) {
    nums.split(',').forEach(function (n) {
      n = String(n || '').trim();
      if (n) found.add(n);
    });
    return _;
  });
  return Array.from(found).sort(function (a, b) { return Number(a) - Number(b); });
}

function deriveExportHeading(question, idx) {
  var text = String(question || '').replace(/\s+/g, ' ').trim();
  if (!text || /^(what|which|when|why|how|and|also|what dose\??|dose\??)$/i.test(text)) return 'Clinical Question ' + (idx + 1);
  return text.replace(/[?!.]+$/, '').slice(0, 90);
}

function isUtilityAssistantMessage(content) {
  return /^I prepared the image prompt in the \*\*Image \/ Graph\*\* box/i.test(String(content || ''));
}

export function buildExportCacheKey(items, imageSrc) {
  return JSON.stringify({ items: (items || []).map(function (item) {
    return { q: item.question, a: item.answer, s: (item.sources || []).map(function (s) { return [s.number, s.title, s.page]; }) };
  }), image: imageSrc ? '1' : '' });
}
