import { parseHTML } from "linkedom";
import { htmlToMarkdown } from "../markdown.js";
function isIssueOrPR(url) {
  return /\/issues\/\d+|\/pull\/\d+/.test(url);
}
function isBlob(url) {
  return /\/blob\//.test(url);
}
function extractIssue(document, _url) {
  const titleEl = document.querySelector(".js-issue-title") ?? document.querySelector(".gh-header-title");
  if (!titleEl) return null;
  const title = titleEl.textContent?.trim() ?? "";
  const labelEls = document.querySelectorAll(".IssueLabel");
  const labels = Array.from(labelEls).map((el) => el.textContent?.trim() ?? "").filter(Boolean);
  const commentBodies = document.querySelectorAll(".d-block.comment-body");
  if (commentBodies.length === 0) return null;
  const sections = [];
  if (labels.length > 0) {
    sections.push(`**Labels:** ${labels.join(", ")}
`);
  }
  Array.from(commentBodies).forEach((body, i) => {
    const html = body.innerHTML;
    const md = htmlToMarkdown(html).trim();
    if (md) {
      sections.push(i === 0 ? md : `---

${md}`);
    }
  });
  const markdown = sections.join("\n\n");
  return {
    title,
    markdown,
    metadata: {},
    links: [],
    images: [],
    extractor: "site-specific"
  };
}
function extractReadme(document) {
  const titleEl = document.querySelector("title");
  const rawTitle = titleEl?.textContent?.trim() ?? "";
  const title = rawTitle.split(":")[0]?.trim() ?? rawTitle;
  const readmeBody = document.querySelector("#readme .markdown-body") ?? document.querySelector(".markdown-body");
  if (!readmeBody) return null;
  const markdown = htmlToMarkdown(readmeBody.innerHTML).trim();
  if (!markdown) return null;
  return {
    title,
    markdown,
    metadata: {},
    links: [],
    images: [],
    extractor: "site-specific"
  };
}
function extractBlob(document) {
  const titleEl = document.querySelector("title");
  const title = titleEl?.textContent?.trim() ?? "";
  const codeBlock = document.querySelector(".blob-code-content") ?? document.querySelector(".highlight") ?? document.querySelector(".markdown-body");
  if (!codeBlock) return null;
  const markdown = htmlToMarkdown(codeBlock.innerHTML).trim();
  if (!markdown) return null;
  return {
    title,
    markdown,
    metadata: {},
    links: [],
    images: [],
    extractor: "site-specific"
  };
}
const githubExtractor = {
  name: "github",
  canHandle(url) {
    try {
      const hostname = new URL(url).hostname;
      return hostname === "github.com" || hostname.endsWith(".github.com");
    } catch {
      return false;
    }
  },
  extract(html, url) {
    if (!html) return null;
    const { document } = parseHTML(html);
    if (isIssueOrPR(url)) {
      return extractIssue(document, url);
    }
    if (isBlob(url)) {
      return extractBlob(document);
    }
    return extractReadme(document);
  }
};
export {
  githubExtractor
};
//# sourceMappingURL=github.js.map