package tech.easyflow.ai.node.filegeneration;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;
import org.springframework.stereotype.Component;

/**
 * HTML 清洗组件。
 *
 * @author Codex
 * @since 2026-04-18
 */
@Component
public class HtmlSanitizer {
    private final Safelist safelist;

    public HtmlSanitizer() {
        this.safelist = Safelist.relaxed()
                .addTags("table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "colgroup", "col")
                .addAttributes("table", "border", "cellpadding", "cellspacing")
                .addAttributes("th", "colspan", "rowspan", "scope", "align")
                .addAttributes("td", "colspan", "rowspan", "align")
                .addAttributes("col", "span", "width")
                .addAttributes("colgroup", "span", "width")
                .addProtocols("a", "href", "http", "https", "mailto");
        this.safelist.removeTags("img", "style", "script", "iframe", "object", "embed", "form");
        this.safelist.preserveRelativeLinks(true);
    }

    /**
     * 清洗 HTML 片段。
     *
     * @param html 原始 HTML
     * @return 清洗后的 HTML 片段
     */
    public String sanitize(String html) {
        Document.OutputSettings outputSettings = new Document.OutputSettings();
        outputSettings.prettyPrint(false);
        return Jsoup.clean(html == null ? "" : html, "", safelist, outputSettings);
    }
}
