/**
 * Report Generator for Radiology Analysis
 * Generates HTML reports that can be saved or uploaded
 */

function escapeHtml(text) {
  if (!text) return '';
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

/**
 * Generate HTML report from analysis results
 * @param {Object} result - Analysis result object
 * @returns {string} HTML content
 */
export function generateHtmlReport(result) {
  const { analysis, study, usage, timestamp } = result;

  let html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Radiology Analysis Report</title>
  <style>
    @page {
      size: letter;
      margin: 0.75in;
    }
    @media print {
      body { margin: 0; }
      .no-print { display: none; }
    }
    body {
      font-family: 'Segoe UI', Arial, sans-serif;
      font-size: 11pt;
      line-height: 1.6;
      color: #000;
      max-width: 100%;
    }
    .header {
      text-align: center;
      margin-bottom: 20pt;
      padding: 15pt;
      border: 2px solid #333;
    }
    h1 {
      font-size: 18pt;
      margin: 0 0 10pt 0;
    }
    h2 {
      font-size: 14pt;
      margin: 20pt 0 10pt 0;
      border-bottom: 2px solid #333;
      padding-bottom: 5pt;
    }
    h3 {
      font-size: 12pt;
      margin: 15pt 0 8pt 0;
    }
    .field {
      margin: 5pt 0;
    }
    .field-label {
      font-weight: bold;
    }
    .warning-box {
      background: #fff3cd;
      border-left: 4px solid #ffc107;
      padding: 10pt;
      margin: 10pt 0;
      page-break-inside: avoid;
    }
    .critical-box {
      background: #f8d7da;
      border-left: 4px solid #dc3545;
      padding: 10pt;
      margin: 10pt 0;
      page-break-inside: avoid;
    }
    ul {
      margin: 8pt 0;
      padding-left: 25pt;
    }
    li {
      margin: 4pt 0;
    }
    .disclaimer {
      margin-top: 20pt;
      padding: 10pt;
      background: #f8f9fa;
      border: 1px solid #dee2e6;
      font-size: 9pt;
    }
    .footer {
      margin-top: 20pt;
      padding-top: 10pt;
      border-top: 1px solid #ccc;
      font-size: 9pt;
      color: #666;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>🤖 AI RADIOLOGY ANALYSIS REPORT</h1>
    <p style="margin: 5pt 0;"><strong>Generated:</strong> ${new Date(timestamp).toLocaleString()}</p>
  </div>
`;

  // Study Summary
  if (analysis.study_summary) {
    html += `
      <h2>STUDY SUMMARY</h2>
      <div class="field"><span class="field-label">Body Part:</span> ${escapeHtml(analysis.study_summary.body_part)}</div>
      <div class="field"><span class="field-label">Modality:</span> ${escapeHtml(analysis.study_summary.modality)}</div>
      <div class="field"><span class="field-label">Study Type:</span> ${escapeHtml(analysis.study_summary.study_type)}</div>
      <div class="field"><span class="field-label">Image Quality:</span> ${escapeHtml(analysis.study_summary.image_quality)}</div>
    `;
    if (analysis.study_summary.quality_notes) {
      html += `<div class="field"><span class="field-label">Quality Notes:</span> ${escapeHtml(analysis.study_summary.quality_notes)}</div>`;
    }
    html += `<div class="field"><span class="field-label">Images Analyzed:</span> ${analysis.study_summary.total_images_analyzed} images across ${analysis.study_summary.series_count} series</div>`;
  }

  // Critical Findings
  if (analysis.critical_findings) {
    html += '<h2>CRITICAL FINDINGS</h2>';

    if (analysis.critical_findings.structures_not_clearly_visualized?.length) {
      html += '<h3>⚠️ Structures Not Clearly Visualized</h3>';
      for (const item of analysis.critical_findings.structures_not_clearly_visualized) {
        html += `
          <div class="critical-box">
            <div style="font-weight: bold; margin-bottom: 5pt;">${escapeHtml(item.structure)}</div>
            <div><strong>Clinical Significance:</strong> ${escapeHtml(item.clinical_significance)}</div>
            <div><strong>Expected Visibility:</strong> ${escapeHtml(item.expected_visibility)}</div>
        `;
        if (item.possible_explanations?.length) {
          html += '<div><strong>Possible Explanations:</strong> ' + item.possible_explanations.map(e => escapeHtml(e)).join('; ') + '</div>';
        }
        html += '</div>';
      }
    }

    if (analysis.critical_findings.secondary_signs_identified?.length) {
      html += '<h3>🔍 Secondary Signs Identified</h3>';
      for (const sign of analysis.critical_findings.secondary_signs_identified) {
        html += `
          <div class="warning-box">
            <div><strong>${escapeHtml(sign.finding)}</strong> at ${escapeHtml(sign.location)}</div>
            <div>Suggests: ${escapeHtml(sign.suggests)}</div>
          </div>
        `;
      }
    }
  }

  // Overall Impression
  if (analysis.overall_impression) {
    html += '<h2>OVERALL IMPRESSION</h2>';
    if (analysis.overall_impression.summary) {
      html += `<p>${escapeHtml(analysis.overall_impression.summary)}</p>`;
    }
    if (analysis.overall_impression.key_findings?.length) {
      html += '<h3>Key Findings</h3><ul>';
      for (const finding of analysis.overall_impression.key_findings) {
        html += `<li>${escapeHtml(finding)}</li>`;
      }
      html += '</ul>';
    }
  }

  // Detailed Findings
  if (analysis.findings) {
    html += '<h2>DETAILED FINDINGS</h2>';

    if (analysis.findings.primary_observations?.length) {
      html += '<h3>Primary Observations</h3><ul>';
      for (const obs of analysis.findings.primary_observations) {
        html += `<li>${escapeHtml(obs)}</li>`;
      }
      html += '</ul>';
    }

    if (analysis.findings.secondary_observations?.length) {
      html += '<h3>Secondary Observations</h3><ul>';
      for (const obs of analysis.findings.secondary_observations) {
        html += `<li>${escapeHtml(obs)}</li>`;
      }
      html += '</ul>';
    }

    if (analysis.findings.normal_findings?.length) {
      html += '<h3>Normal Findings</h3><ul>';
      for (const obs of analysis.findings.normal_findings) {
        html += `<li>${escapeHtml(obs)}</li>`;
      }
      html += '</ul>';
    }
  }

  // Litigation Relevance
  if (analysis.litigation_relevance) {
    html += '<h2>LITIGATION RELEVANCE</h2>';
    if (analysis.litigation_relevance.objective_findings_summary) {
      html += `<p>${escapeHtml(analysis.litigation_relevance.objective_findings_summary)}</p>`;
    }
    if (analysis.litigation_relevance.questions_for_radiologist?.length) {
      html += '<h3>Questions for Radiologist</h3><ul>';
      for (const q of analysis.litigation_relevance.questions_for_radiologist) {
        html += `<li>${escapeHtml(q)}</li>`;
      }
      html += '</ul>';
    }
  }

  // Footer
  html += `
    <div class="footer">
      <div><strong>Analysis Date:</strong> ${new Date(timestamp).toLocaleString()}</div>
  `;
  if (usage) {
    html += `
      <div><strong>Estimated Cost:</strong> $${usage.estimatedCost}</div>
      <div><strong>Tokens:</strong> ${usage.inputTokens?.toLocaleString() || 'N/A'} input / ${usage.outputTokens?.toLocaleString() || 'N/A'} output</div>
    `;
  }
  html += `
    </div>
    <div class="disclaimer">
      <strong>IMPORTANT DISCLAIMER:</strong><br>
      🤖 This analysis was generated by Claude Sonnet 4.5 via Filevine DICOM Viewer for legal review purposes only.<br>
      <strong>THIS IS NOT A MEDICAL DIAGNOSIS.</strong> This AI-assisted analysis is intended to help legal professionals understand radiology studies.
      Always consult with a qualified radiologist for definitive medical interpretation.
    </div>
  </body>
</html>
`;

  return html;
}

/**
 * Generate filename for report
 * @param {Object} study - Study metadata
 * @returns {string} Filename
 */
export function generateReportFilename(study) {
  const date = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
  const bodyPart = study?.metadata?.BodyPart || 'Unknown';
  const sanitized = bodyPart.replace(/[^a-zA-Z0-9]/g, '_');
  return `Radiology_Analysis_${sanitized}_${date}.html`;
}
