import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";

const turndownService = new TurndownService({
    headingStyle: "atx",
    codeBlockStyle: "fenced",
    bulletListMarker: "-",
});

turndownService.use(gfm);

turndownService.addRule("strikethrough", {
    filter: ["del", "s"],
    replacement(content: string) {
        return `~~${content}~~`;
    },
});

turndownService.addRule("taskListItems", {
    filter(node: HTMLElement) {
        return node.nodeName === "LI" && node.className.includes("task-list-item");
    },
    replacement(content: string, node: HTMLElement) {
        const isChecked = node.getAttribute("data-checked") === "true";
        return `${isChecked ? "- [x] " : "- [ ] "}${content.replace(/^- /, "")}\n`;
    },
});

export function htmlToMarkdown(html: string): string {
    if (!html) return "";
    return turndownService.turndown(html);
}
