/**
 * Markdown节点渲染器
 * 为Mind Elixir节点提供markdown内容渲染能力
 * 支持表格、数学公式、代码块等
 */

import { marked } from 'marked';
import Prism from 'prismjs';
import katex from 'katex';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-json';
import 'prismjs/components/prism-python';
import 'prismjs/components/prism-sql';
import 'katex/dist/katex.min.css';

// 自定义渲染器（移除图片处理，使用MindElixir原生image属性）
const renderer = new marked.Renderer();

// 配置marked选项
marked.setOptions({
  breaks: false, // 禁用breaks，避免在表格中产生<br>标签导致HTML不匹配
  gfm: true, // GitHub Flavored Markdown
  tables: true, // 支持表格
  sanitize: false, // 允许HTML（用于数学公式等）
  renderer: renderer // 使用自定义渲染器
});

/**
 * 渲染markdown内容为HTML
 * @param {string} markdown - markdown文本
 * @returns {string} 渲染后的HTML
 */
export const renderMarkdownToHTML = (markdown) => {
  if (!markdown || typeof markdown !== 'string') {
    return '';
  }
  
  try {
    // 预处理markdown
    const processedMarkdown = preprocessMarkdown(markdown);
    
    // 使用marked渲染
    const html = marked.parse(processedMarkdown);
    
    // 后处理HTML
    const finalHTML = postprocessHTML(html);
    
    return finalHTML;
  } catch (error) {
    console.error('Markdown渲染失败:', error);
    return `<div class="markdown-error">渲染失败: ${error.message}</div>`;
  }
};

/**
 * 预处理markdown内容
 * @param {string} markdown - 原始markdown
 * @returns {string} 处理后的markdown
 */
const preprocessMarkdown = (markdown) => {
  return markdown
    // 处理块级数学公式（$$...$$）
    .replace(/\$\$([\s\S]*?)\$\$/g, (match, formula) => {
      try {
        const rendered = katex.renderToString(formula.trim(), {
          displayMode: true,
          throwOnError: false
        });
        return `<div class="math-block">${rendered}</div>`;
      } catch (error) {
        console.warn('数学公式渲染失败:', error);
        return `<div class="math-error">数学公式错误: ${formula}</div>`;
      }
    })
    // 处理行内数学公式（$...$），但避免匹配单个$符号
    .replace(/\$([^$\n]+?)\$/g, (match, formula) => {
      // 检查是否包含LaTeX命令或数学符号
      if (formula.includes('\\') || formula.includes('{') || formula.includes('}') || 
          formula.includes('^') || formula.includes('_') || formula.includes('=') ||
          formula.includes('+') || formula.includes('-') || formula.includes('*') ||
          formula.includes('/') || formula.includes('(') || formula.includes(')')) {
        try {
          const rendered = katex.renderToString(formula.trim(), {
            displayMode: false,
            throwOnError: false
          });
          return `<span class="math-inline">${rendered}</span>`;
        } catch (error) {
          console.warn('数学公式渲染失败:', error);
          return `<span class="math-error">数学公式错误: ${formula}</span>`;
        }
      }
      return match; // 如果不包含数学符号，保持原样
    });
};

/**
 * 后处理HTML内容
 * @param {string} html - 渲染后的HTML
 * @returns {string} 处理后的HTML
 */
const postprocessHTML = (html) => {
  let processedHTML = html
    // 为表格添加样式类
    .replace(/<table>/g, '<table class="markdown-table">')
    // 为代码块添加样式类
    .replace(/<pre><code/g, '<pre class="markdown-code"><code');

  // 创建临时DOM元素来处理语法高亮
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = processedHTML;
  
  // 为代码块添加语法高亮
  const codeBlocks = tempDiv.querySelectorAll('pre code');
  codeBlocks.forEach(block => {
    const language = block.className.match(/language-(\w+)/);
    if (language) {
      try {
        block.innerHTML = Prism.highlight(block.textContent, Prism.languages[language[1]], language[1]);
      } catch (e) {
        console.warn('语法高亮失败:', e);
      }
    }
  });
  
  return tempDiv.innerHTML;
};

/**
 * 为Mind Elixir节点设置markdown内容
 * @param {HTMLElement} nodeElement - 节点DOM元素
 * @param {string} markdownContent - markdown内容
 */
export const setNodeMarkdownContent = (nodeElement, markdownContent) => {
  if (!nodeElement || !markdownContent) return;
  
  // 查找或创建内容容器
  let contentContainer = nodeElement.querySelector('.markdown-content');
  if (!contentContainer) {
    contentContainer = document.createElement('div');
    contentContainer.className = 'markdown-content';
    
    // 将内容容器添加到节点中
    const topicText = nodeElement.querySelector('.topic-text');
    if (topicText) {
      topicText.appendChild(contentContainer);
    } else {
      nodeElement.appendChild(contentContainer);
    }
  }
  
  // 渲染markdown内容
  const html = renderMarkdownToHTML(markdownContent);
  contentContainer.innerHTML = html;
  
  // 添加样式
  addMarkdownStyles(contentContainer);
};

/**
 * 添加markdown样式
 * @param {HTMLElement} container - 容器元素
 */
const addMarkdownStyles = (container) => {
  // 检查是否已经添加过样式
  if (document.getElementById('markdown-node-styles')) return;
  
  const style = document.createElement('style');
  style.id = 'markdown-node-styles';
  style.textContent = `
    .markdown-content {
      max-width: 100%;
      overflow: hidden;
      word-wrap: break-word;
      word-break: break-word;
      line-height: 1.4;
      text-align: left;
      display: block;
    }
    
    .markdown-content h1,
    .markdown-content h2,
    .markdown-content h3,
    .markdown-content h4,
    .markdown-content h5,
    .markdown-content h6 {
      margin: 4px 0 2px 0;
      font-weight: 600;
      color: #333;
    }
    
    .markdown-content h1 { font-size: 16px; }
    .markdown-content h2 { font-size: 15px; }
    .markdown-content h3 { font-size: 14px; }
    .markdown-content h4 { font-size: 13px; }
    .markdown-content h5 { font-size: 12px; }
    .markdown-content h6 { font-size: 11px; }
    
    .markdown-content p {
      margin: 2px 0;
      line-height: 1.3;
      color: #666;
    }
    
    .markdown-content ul,
    .markdown-content ol {
      margin: 2px 0;
      padding-left: 16px;
      list-style-position: inside;
    }
    
    .markdown-content li {
      margin: 1px 0;
      line-height: 1.3;
      color: #666;
      display: list-item;
      text-align: left;
    }
    
    .markdown-content strong,
    .markdown-content b {
      font-weight: 600;
      color: #333;
    }
    
    .markdown-content em,
    .markdown-content i {
      font-style: italic;
      color: #555;
    }
    
    .markdown-content code {
      background: #f5f5f5;
      padding: 1px 4px;
      border-radius: 3px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 11px;
      color: #d63384;
      border: 1px solid #e9ecef;
    }
    
    .markdown-content pre {
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 4px;
      padding: 8px;
      margin: 4px 0;
      overflow-x: auto;
      position: relative;
    }
    
    .markdown-content pre code {
      background: none;
      padding: 0;
      color: #333;
      font-size: 11px;
      border: none;
      display: block;
      white-space: pre;
    }
    
    /* 语法高亮样式 */
    .markdown-content pre code .token.comment,
    .markdown-content pre code .token.prolog,
    .markdown-content pre code .token.doctype,
    .markdown-content pre code .token.cdata {
      color: #6a737d;
    }
    
    .markdown-content pre code .token.punctuation {
      color: #586069;
    }
    
    .markdown-content pre code .token.property,
    .markdown-content pre code .token.tag,
    .markdown-content pre code .token.boolean,
    .markdown-content pre code .token.number,
    .markdown-content pre code .token.constant,
    .markdown-content pre code .token.symbol,
    .markdown-content pre code .token.deleted {
      color: #005cc5;
    }
    
    .markdown-content pre code .token.selector,
    .markdown-content pre code .token.attr-name,
    .markdown-content pre code .token.string,
    .markdown-content pre code .token.char,
    .markdown-content pre code .token.builtin,
    .markdown-content pre code .token.inserted {
      color: #032f62;
    }
    
    .markdown-content pre code .token.operator,
    .markdown-content pre code .token.entity,
    .markdown-content pre code .token.url,
    .markdown-content pre code .language-css .token.string,
    .markdown-content pre code .style .token.string {
      color: #d73a49;
    }
    
    .markdown-content pre code .token.atrule,
    .markdown-content pre code .token.attr-value,
    .markdown-content pre code .token.keyword {
      color: #d73a49;
    }
    
    .markdown-content pre code .token.function,
    .markdown-content pre code .token.class-name {
      color: #6f42c1;
    }
    
    .markdown-content pre code .token.regex,
    .markdown-content pre code .token.important,
    .markdown-content pre code .token.variable {
      color: #e36209;
    }
    
    .markdown-table {
      border-collapse: collapse;
      width: 100%;
      margin: 4px 0;
      font-size: 11px;
      border: 1px solid #e0e0e0;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      background-color: #fafafa;
      overflow: hidden;
      white-space: normal; /* 覆盖MindElixir的pre-wrap */
    }
    
    .markdown-table th,
    .markdown-table td {
      border: 1px solid #e0e0e0;
      padding: 8px 12px;
      text-align: left;
      vertical-align: top;
      position: relative;
      white-space: normal; /* 覆盖MindElixir的pre-wrap */
    }
    
    .markdown-table th {
      background-color: #f5f5f5;
      font-weight: 600;
      color: #333;
      text-align: center;
      border-bottom: 1px solid #d0d0d0;
    }
    
    .markdown-table td {
      background-color: #fff;
    }
    
    .markdown-table tr:nth-child(even) td {
      background-color: #f8f8f8;
    }
    
    .markdown-table tr:hover td {
      background-color: #f0f8ff;
    }
    
    /* 移除多余的边框，保持简洁 */
    .markdown-table th:not(:last-child),
    .markdown-table td:not(:last-child) {
      border-right: 1px solid #e0e0e0;
    }
    
    .markdown-table tr:not(:last-child) td {
      border-bottom: 1px solid #e0e0e0;
    }
    
    .markdown-content a {
      color: #007bff;
      text-decoration: none;
    }
    
    .markdown-content a:hover {
      text-decoration: underline;
    }
    
    .markdown-content blockquote {
      border-left: 3px solid #ddd;
      margin: 4px 0;
      padding-left: 8px;
      color: #666;
      font-style: italic;
    }
    
    .math-block {
      text-align: center;
      margin: 4px 0;
      padding: 4px;
      background: #f8f9fa;
      border-radius: 4px;
    }
    
    .math-inline {
      display: inline;
      margin: 0 2px;
    }
    
    .math-error {
      color: #dc3545;
      background: #f8d7da;
      border: 1px solid #f5c6cb;
      padding: 2px 4px;
      border-radius: 3px;
      font-size: 10px;
      font-family: monospace;
    }
    
    .markdown-error {
      color: #dc3545;
      background: #f8d7da;
      border: 1px solid #f5c6cb;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 11px;
    }
  `;
  
  document.head.appendChild(style);
};

/**
 * 检查内容是否包含表格
 * @param {string} content - 内容文本
 * @returns {boolean} 是否包含表格
 */
export const hasTable = (content) => {
  if (!content || typeof content !== 'string') {
    return false;
  }
  
  // 检查是否包含表格语法
  const lines = content.split('\n');
  let hasTableRow = false;
  let hasSeparator = false;
  
  for (const line of lines) {
    const trimmedLine = line.trim();
    
    // 检查表格行（包含|字符且至少有3个部分）
    if (trimmedLine.includes('|') && trimmedLine.split('|').length >= 3) {
      hasTableRow = true;
    }
    // 检查分隔符行（包含-和|，且主要由这些字符组成）
    if (trimmedLine.includes('|') && trimmedLine.includes('-') && /^[\s\|\-\:]+$/.test(trimmedLine)) {
      hasSeparator = true;
    }
  }
  
  // 如果只有表格行但没有分隔符，也可能是表格
  // 或者如果内容包含多个|字符，也可能是表格
  const pipeCount = (content.match(/\|/g) || []).length;
  const hasMultiplePipes = pipeCount >= 6; // 至少3行，每行2个|
  
  // 更宽松的表格检测逻辑
  return (hasTableRow && hasSeparator) || (hasTableRow && hasMultiplePipes) || (hasTableRow && pipeCount >= 4);
};

/**
 * 检查内容是否包含markdown语法
 * @param {string} content - 内容文本
 * @returns {boolean} 是否包含markdown语法
 */
export const hasMarkdownSyntax = (content) => {
  if (!content || typeof content !== 'string') {
    return false;
  }
  
  // 首先检查表格
  if (hasTable(content)) {
    return true;
  }
  
  // 检查其他常见的markdown语法
  const markdownPatterns = [
    /#{1,6}\s+/, // 标题
    /\*\*.*?\*\*/, // 粗体
    /\*.*?\*/, // 斜体
    /`.*?`/, // 行内代码
    /```[\s\S]*?```/, // 代码块
    /^\s*[-*+]\s+/m, // 列表
    /^\s*\d+\.\s+/m, // 有序列表
    /\[.*?\]\(.*?\)/, // 链接
    /!\[.*?\]\(.*?\)/, // 图片
    /\$\$.*?\$\$/, // 块级数学公式
    /\$.*?\$/, // 行内数学公式
  ];
  
  return markdownPatterns.some(pattern => pattern.test(content));
};

/**
 * 智能渲染节点内容
 * 根据内容类型选择渲染方式
 * @param {string} content - 节点内容
 * @returns {string} 渲染后的HTML内容
 */
export const smartRenderNodeContent = (content) => {
  if (!content || typeof content !== 'string') return content || '';
  
  // 检查是否包含markdown语法
  if (hasMarkdownSyntax(content)) {
    // 使用markdown渲染
    return renderMarkdownToHTML(content);
  } else if (content.includes('|')) {
    // 如果包含|字符但没有检测到markdown语法，强制尝试渲染
    return renderMarkdownToHTML(content);
  } else {
    // 返回原始内容
    return content;
  }
};


export default {
  renderMarkdownToHTML,
  setNodeMarkdownContent,
  hasMarkdownSyntax,
  hasTable,
  smartRenderNodeContent
};
