import { parseHTML } from "linkedom";
import { htmlToMarkdown } from "../markdown.js";
const STRIP_SELECTORS = [
  "nav",
  ".docs-sidebar",
  ".sidebar",
  ".toc-wrapper",
  ".table-of-contents",
  ".version-picker",
  ".pagination-nav",
  "header",
  "footer"
];
function detectFramework(html) {
  if (html.includes("docs-sidebar") || html.includes("data-docusaurus-page")) {
    return "docusaurus";
  }
  if (html.includes("md-content")) {
    return "mkdocs";
  }
  if (html.includes('class="document"') || html.includes("class='document'") || html.includes('class="body"') && html.includes("highlight")) {
    return "sphinx";
  }
  if (html.includes("page-body")) {
    return "gitbook";
  }
  return null;
}
function extractWithSelectors(document, contentSelectors) {
  for (const selector of contentSelectors) {
    const el = document.querySelector(selector);
    if (el) return el;
  }
  return null;
}
function stripElements(root, selectors) {
  for (const selector of selectors) {
    for (const el of Array.from(root.querySelectorAll(selector))) {
      el.parentNode?.removeChild(el);
    }
  }
}
function buildResult(document, contentEl) {
  stripElements(contentEl, STRIP_SELECTORS);
  const titleEl = contentEl.querySelector("h1") ?? document.querySelector("h1") ?? document.querySelector("title");
  const rawTitle = titleEl?.textContent?.trim() ?? "";
  const title = rawTitle.includes("|") ? rawTitle.split("|")[0].trim() : rawTitle;
  if (!title) return null;
  const markdown = htmlToMarkdown(contentEl.innerHTML).trim();
  if (!markdown) return null;
  return {
    title,
    markdown,
    metadata: {},
    links: [],
    images: [],
    extractor: "site-specific"
  };
}
const docsGenericExtractor = {
  name: "docs-generic",
  canHandle(_url, html) {
    if (!html) return false;
    return detectFramework(html) !== null;
  },
  extract(html, _url) {
    if (!html) return null;
    const framework = detectFramework(html);
    if (!framework) return null;
    const { document } = parseHTML(html);
    let contentSelectors;
    switch (framework) {
      case "docusaurus":
        contentSelectors = [".markdown", "article", "main"];
        break;
      case "mkdocs":
        contentSelectors = [".md-content"];
        break;
      case "sphinx":
        contentSelectors = [".document", ".body"];
        break;
      case "gitbook":
        contentSelectors = [".page-body"];
        break;
    }
    const contentEl = extractWithSelectors(document, contentSelectors);
    if (!contentEl) return null;
    return buildResult(document, contentEl);
  }
};
export {
  docsGenericExtractor
};
//# sourceMappingURL=docs-generic.js.map