import { parseHTML } from "linkedom";
const MIN_CODE_LENGTH = 30;
async function extractCodeSnippet(html, url) {
  if (!html) return null;
  let document;
  try {
    ({ document } = parseHTML(html));
  } catch {
    return null;
  }
  const blocks = Array.from(document.querySelectorAll("pre > code, pre code"));
  if (blocks.length === 0) return null;
  let largest = null;
  let largestLen = 0;
  for (const block of blocks) {
    const text = block.textContent ?? "";
    if (text.length > largestLen) {
      largestLen = text.length;
      largest = block;
    }
  }
  if (!largest || largestLen < MIN_CODE_LENGTH) return null;
  const code = (largest.textContent ?? "").trim();
  if (!code) return null;
  const data = { code, url };
  const language = detectLanguage(largest);
  if (language) data.language = language;
  const pre = closestPre(largest);
  const filename = detectFilename(pre);
  if (filename) data.filename = filename;
  const description = detectDescription(pre);
  if (description) data.description = description;
  return data;
}
function detectLanguage(codeEl) {
  const fromCode = languageFromClass(codeEl.getAttribute("class"));
  if (fromCode) return fromCode;
  const pre = closestPre(codeEl);
  if (pre) {
    const fromPre = languageFromClass(pre.getAttribute("class"));
    if (fromPre) return fromPre;
  }
  return void 0;
}
function languageFromClass(cls) {
  if (!cls) return void 0;
  for (const token of cls.split(/\s+/)) {
    const m = /^(?:language|lang|hljs|highlight)-(.+)$/.exec(token);
    if (m) return m[1];
  }
  return void 0;
}
function closestPre(el) {
  let current = el;
  while (current) {
    if (current.tagName === "PRE") return current;
    current = current.parentElement;
  }
  return null;
}
function detectFilename(pre) {
  if (!pre) return void 0;
  const figcaption = pre.parentElement?.querySelector("figcaption") ?? pre.previousElementSibling;
  if (figcaption && figcaption.tagName === "FIGCAPTION") {
    const text = (figcaption.textContent ?? "").trim();
    if (text) return text;
  }
  const header = pre.parentElement?.querySelector("header, .filename, div.filename");
  if (header) {
    const text = (header.textContent ?? "").trim();
    if (text) return text;
  }
  return void 0;
}
function detectDescription(pre) {
  if (!pre) return void 0;
  let sib = pre.previousElementSibling;
  while (sib && (sib.tagName === "FIGCAPTION" || sib.tagName === "HEADER")) {
    sib = sib.previousElementSibling;
  }
  if (sib && sib.tagName === "P") {
    const text = (sib.textContent ?? "").trim();
    if (text) return text.slice(0, 300);
  }
  return void 0;
}
export {
  extractCodeSnippet
};
//# sourceMappingURL=CodeSnippet.js.map