import * as _TurndownService from '@joplin/turndown';
import * as TurndownPluginGfm from '@joplin/turndown-plugin-gfm';
import { getBasename } from './basename';
import { getFileNameFromUrl } from '../../media-utils';
import { normalizeItemsByLabelAttributes } from '../../items-by-label';

// CJS/ESM interop: .default exists in Vite, not in NestJS
const TurndownService = (_TurndownService as any).default || _TurndownService;

// queried one at a time, as domino sorts all matches of a selector list
const NESTING_BLOCKS = ['details', 'ol.footnotes'];

function sanitizeMdLinkText(value: string): string {
  return value
    .replace(/\\/g, '\\\\')
    .replace(/([\[\]!])/g, '\\$1')
    .replace(/[\r\n]+/g, ' ');
}

function isItemsByLabel(node: HTMLElement): boolean {
  return (
    node.nodeName === 'DIV' &&
    node.getAttribute('data-type') === 'items-by-label'
  );
}

function itemsByLabelMarkdown(
  service: _TurndownService,
  node: HTMLElement,
): string {
  const paragraph = node.ownerDocument.createElement('p');
  let heading = '';
  try {
    const attrs = JSON.parse(node.getAttribute('data-config') ?? '{}');
    heading = normalizeItemsByLabelAttributes(attrs).heading.trim();
  } catch {
    // Older or incomplete HTML can contain only the marker.
  }
  paragraph.textContent = heading || 'Pages by label';
  // Rich tables emit outerHTML after converting their children.
  node.parentNode.replaceChild(paragraph, node);
  return '\n\n' + service.turndown(paragraph) + '\n\n';
}

export function htmlToMarkdown(html: string): string {
  const turndownService = new TurndownService({
    headingStyle: 'atx',
    codeBlockStyle: 'fenced',
    hr: '---',
    bulletListMarker: '-',
    // Turndown bypasses custom rules for nodes with no text.
    blankReplacement: (_content: string, node: HTMLElement & { isBlock: boolean }) => {
      if (isItemsByLabel(node)) return itemsByLabelMarkdown(turndownService, node);
      return node.isBlock ? '\n\n' : '';
    },
  });

  turndownService.use([
    TurndownPluginGfm.tables,
    TurndownPluginGfm.strikethrough,
    TurndownPluginGfm.highlightedCodeBlock,
    tabs,
    taskList,
    callout,
    preserveDetail,
    listParagraph,
    orderedListItem,
    mathInline,
    mathBlock,
    iframeEmbed,
    pdf,
    image,
    video,
    audio,
    footnoteRef,
    footnotesList,
  ]);
  turndownService.addRule('itemsByLabel', {
    filter: isItemsByLabel,
    replacement: (_content: string, node: HTMLElement) =>
      itemsByLabelMarkdown(turndownService, node),
  });
  const htmlWithoutColgroups = html.replace(
    /<colgroup\b[^>]*>[\s\S]*?<\/colgroup>/gi,
    '',
  );
  return turndownService.turndown(htmlWithoutColgroups).replaceAll('<br>', ' ');
}

// domino, the server's DOM, silently matches nothing for :scope selectors
function getChildDivs(node: Element, dataType: string): Element[] {
  return Array.from(node.children).filter(
    (child) =>
      child.nodeName === 'DIV' && child.getAttribute('data-type') === dataType,
  );
}

// Turndown converts children before their parent's rule runs, so parents read
// the result here: converting again doubles the work per nesting level.
// Blank divs skip this rule, so parents still convert those themselves.
function collectDivMarkdown(
  turndownService: _TurndownService,
  dataType: string,
): WeakMap<Node, string> {
  const markdownByDiv = new WeakMap<Node, string>();

  turndownService.addRule(dataType, {
    filter: (node: HTMLInputElement) =>
      node.nodeName === 'DIV' && node.getAttribute('data-type') === dataType,
    replacement: (content: string, node: HTMLInputElement) => {
      markdownByDiv.set(node, content.replace(/^[\t\r\n]+/, '').trimEnd());
      return `\n\n${content}\n\n`;
    },
  });

  return markdownByDiv;
}

// Summaries and footnotes hold inline content, so any of these blocks inside
// one keeps only its text rather than being converted at every level.
function convertAgain(
  turndownService: _TurndownService,
  node: Element,
  html: string,
): string {
  const nested = NESTING_BLOCKS.some((block) => node.querySelector(block));
  return turndownService.turndown(
    nested ? html.replace(/<[^>]*>/g, ' ') : html,
  );
}

function tabs(turndownService: _TurndownService) {
  const panels = collectDivMarkdown(turndownService, 'tabPanel');

  turndownService.addRule('tabs', {
    filter: (node: HTMLInputElement) =>
      node.nodeName === 'DIV' && node.getAttribute('data-type') === 'tabs',
    replacement: (_content: string, node: HTMLInputElement) => {
      const sections = getChildDivs(node, 'tab').map((tabNode) => {
        const label = getChildDivs(tabNode, 'tabLabel')[0]?.textContent ?? '';
        const panel = getChildDivs(tabNode, 'tabPanel')[0];
        const heading = `#### ${turndownService.escape(label.replace(/\s+/g, ' ').trim())}`;
        const body = panel
          ? (
              panels.get(panel) ?? turndownService.turndown(panel.innerHTML)
            ).trim()
          : '';
        return body ? `${heading}\n\n${body}` : heading;
      });

      return `\n\n${sections.join('\n\n')}\n\n`;
    },
  });
}

function listParagraph(turndownService: _TurndownService) {
  turndownService.addRule('paragraph', {
    filter: ['p'],
    replacement: (content: string, node: HTMLInputElement) => {
      if (node.parentElement?.nodeName === 'LI') {
        return content;
      }
      return `\n\n${content}\n\n`;
    },
  });
}

function orderedListItem(turndownService: _TurndownService) {
  turndownService.addRule('orderedListItem', {
    filter: function (node: HTMLInputElement) {
      return (
        node.nodeName === 'LI' && node.getAttribute('data-type') !== 'taskItem'
      );
    },
    replacement: (content: string, node: HTMLInputElement, options: any) => {
      const parent = node.parentNode as HTMLElement;
      if (parent.nodeName !== 'OL' && parent.nodeName !== 'UL') {
        return content;
      }

      content = content
        .replace(/^\n+/, '')
        .replace(/\n+$/, '\n')
        .replace(/\n/gm, '\n  ');

      let prefix: string;
      if (parent.nodeName === 'OL') {
        const start = parseInt(parent.getAttribute('start') || '1', 10);
        const index = Array.prototype.indexOf.call(parent.children, node);
        prefix = `${start + index}. `;
      } else {
        prefix = `${options.bulletListMarker} `;
      }

      return (
        prefix +
        content +
        (node.nextSibling && !/\n$/.test(content) ? '\n' : '')
      );
    },
  });
}

function callout(turndownService: _TurndownService) {
  turndownService.addRule('callout', {
    filter: function (node: HTMLInputElement) {
      return (
        node.nodeName === 'DIV' && node.getAttribute('data-type') === 'callout'
      );
    },
    replacement: function (content: string, node: HTMLInputElement) {
      const calloutType = node.getAttribute('data-callout-type');
      return `\n\n:::${calloutType}\n${content.trim()}\n:::\n\n`;
    },
  });
}

function taskList(turndownService: _TurndownService) {
  turndownService.addRule('taskListItem', {
    filter: function (node: HTMLInputElement) {
      return (
        node.getAttribute('data-type') === 'taskItem' &&
        node.parentNode.nodeName === 'UL'
      );
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const isChecked = node.getAttribute('data-checked') === 'true';
      const div = node.querySelector('div');
      const text = div ? div.textContent.trim() : node.textContent.trim();

      const prefix = `- ${isChecked ? '[x]' : '[ ]'} `;

      return (
        prefix + text + (node.nextSibling && !/\n$/.test(text) ? '\n' : '')
      );
    },
  });
}

function preserveDetail(turndownService: _TurndownService) {
  const contents = collectDivMarkdown(turndownService, 'detailsContent');

  turndownService.addRule('preserveDetail', {
    filter: function (node: HTMLInputElement) {
      return node.nodeName === 'DETAILS';
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const summary = Array.from(node.children).find(
        (child) => child.nodeName === 'SUMMARY',
      );
      let detailSummary = '';

      if (summary) {
        detailSummary = `<summary>${convertAgain(turndownService, summary, summary.innerHTML)}</summary>`;
      }

      const detailsContent = Array.from(node.childNodes)
        .filter((child) => child.nodeName !== 'SUMMARY')
        .map((child) =>
          child.nodeType === 1
            ? (contents.get(child) ??
              convertAgain(
                turndownService,
                child as HTMLElement,
                (child as HTMLElement).outerHTML,
              ))
            : child.textContent,
        )
        .join('');

      return `\n<details markdown="1">\n${detailSummary}\n\n${detailsContent}\n\n</details>\n`;
    },
  });
}

function mathInline(turndownService: _TurndownService) {
  turndownService.addRule('mathInline', {
    filter: function (node: HTMLInputElement) {
      return (
        node.nodeName === 'SPAN' &&
        node.getAttribute('data-type') === 'mathInline'
      );
    },
    replacement: function (content: string) {
      return `$${content}$`;
    },
  });
}

function mathBlock(turndownService: _TurndownService) {
  turndownService.addRule('mathBlock', {
    filter: function (node: HTMLInputElement) {
      return (
        node.nodeName === 'DIV' &&
        node.getAttribute('data-type') === 'mathBlock'
      );
    },
    replacement: function (content: string) {
      return `\n$$\n${content}\n$$\n`;
    },
  });
}

function iframeEmbed(turndownService: _TurndownService) {
  turndownService.addRule('iframeEmbed', {
    filter: function (node: HTMLInputElement) {
      return node.nodeName === 'IFRAME';
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const src = node.getAttribute('src');
      return '[' + src + '](' + src + ')';
    },
  });
}

function image(turndownService: _TurndownService) {
  turndownService.addRule('image', {
    filter: 'img',
    replacement: function (_content: string, node: HTMLInputElement) {
      const src = node.getAttribute('src') || '';
      if (!src) return '';
      const alt = sanitizeMdLinkText(node.getAttribute('alt') || '');
      const title = node.getAttribute('title') || '';
      const titlePart = title ? ' "' + title.replace(/"/g, '\\"') + '"' : '';
      return '![' + alt + '](' + src + titlePart + ')';
    },
  });
}

function getFootnoteAnchor(node: HTMLElement): HTMLElement | null {
  const child = node.firstElementChild as HTMLElement | null;
  return child?.nodeName === 'A' && child.classList.contains('footnote-ref')
    ? child
    : null;
}

function footnoteRef(turndownService: _TurndownService) {
  turndownService.addRule('footnoteRef', {
    filter: function (node: HTMLInputElement) {
      return node.nodeName === 'SUP' && !!getFootnoteAnchor(node);
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const anchor = getFootnoteAnchor(node);
      const number =
        anchor.getAttribute('data-reference-number') || anchor.textContent;
      return `[^${number}]`;
    },
  });
}

function footnotesList(turndownService: _TurndownService) {
  turndownService.addRule('footnotesList', {
    filter: function (node: HTMLInputElement) {
      return node.nodeName === 'OL' && node.classList.contains('footnotes');
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const items = Array.from(node.children).filter(
        (child) => child.nodeName === 'LI',
      );
      const definitions = items.map((li, index) => {
        const number =
          (li.getAttribute('id') || '').replace('fn:', '') ||
          String(index + 1);
        const markdown = convertAgain(
          turndownService,
          li,
          (li as HTMLElement).innerHTML,
        ).trim();
        // continuation lines need a 4-space indent to stay in the footnote
        const [first, ...rest] = markdown.split('\n');
        const body = [
          first,
          ...rest.map((line: string) => (line.trim() ? `    ${line}` : line)),
        ].join('\n');
        return `[^${number}]: ${body}`;
      });
      return `\n\n${definitions.join('\n')}\n\n`;
    },
  });
}

// a link to the file, named after it, instead of the generic iframe rule
function pdf(turndownService: _TurndownService) {
  turndownService.addRule('pdf', {
    filter: function (node: HTMLElement) {
      return (
        node.nodeName === 'DIV' && node.getAttribute('data-type') === 'pdf'
      );
    },
    replacement: function (_content: string, node: HTMLElement) {
      const src = node.getAttribute('src') || '';
      if (!src) return '';
      const name = sanitizeMdLinkText(
        node.getAttribute('data-name') || getFileNameFromUrl(src) || src,
      );
      return '\n\n[' + name + '](' + src + ')\n\n';
    },
  });
}

function video(turndownService: _TurndownService) {
  turndownService.addRule('video', {
    filter: function (node: HTMLInputElement) {
      return node.tagName === 'VIDEO';
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const src = node.getAttribute('src') || '';
      const ariaLabel = node.getAttribute('aria-label');
      const name = sanitizeMdLinkText(ariaLabel || getBasename(src) || src);
      return '[' + name + '](' + src + ')';
    },
  });
}

function audio(turndownService: _TurndownService) {
  turndownService.addRule('audio', {
    filter: function (node: HTMLInputElement) {
      return node.tagName === 'AUDIO';
    },
    replacement: function (_content: string, node: HTMLInputElement) {
      const src = node.getAttribute('src') || '';
      if (!src) return '';
      const name = sanitizeMdLinkText(
        node.getAttribute('data-name') || getFileNameFromUrl(src) || src,
      );
      return '\n\n[' + name + '](' + src + ')\n\n';
    },
  });
}
