package tech.easyflow.ai.node.filegeneration;

import org.jsoup.nodes.Entities;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * HTML 文档构建器。
 *
 * @author Codex
 * @since 2026-04-18
 */
@Component
public class HtmlDocumentBuilder {
    private static final Pattern BLANK_LINE_PATTERN = Pattern.compile("\\n\\s*\\n");

    private final MarkdownSupport markdownSupport;
    private final HtmlSanitizer htmlSanitizer;

    public HtmlDocumentBuilder(MarkdownSupport markdownSupport, HtmlSanitizer htmlSanitizer) {
        this.markdownSupport = markdownSupport;
        this.htmlSanitizer = htmlSanitizer;
    }

    /**
     * 构建完整 HTML 文档。
     *
     * @param request 已归一化请求
     * @return 完整 HTML 文档字符串
     */
    public String buildDocument(FileGenerationRequest request) {
        String title = Entities.escape(request.getFileName());
        String body = buildBody(request);
        return """
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                  <meta charset="UTF-8" />
                  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                  <title>__TITLE__</title>
                  <style>
                    * { box-sizing: border-box; }
                    body {
                      margin: 0;
                      background: #f5f7fb;
                      color: #1f2937;
                      font-family: "EasyFlowPdfCjk", "Noto Sans CJK SC", "Microsoft YaHei", "PingFang SC", sans-serif;
                    }
                    .document-shell {
                      max-width: 960px;
                      margin: 0 auto;
                      padding: 40px 32px 56px;
                    }
                    .document-paper {
                      background: #ffffff;
                      border: 1px solid #dbe3ef;
                      border-radius: 20px;
                      padding: 40px 44px;
                    }
                    h1, h2, h3, h4, h5, h6 {
                      color: #0f172a;
                      margin-top: 1.4em;
                      margin-bottom: 0.6em;
                      line-height: 1.3;
                    }
                    h1 { font-size: 30px; }
                    h2 { font-size: 24px; }
                    h3 { font-size: 20px; }
                    p, li, blockquote, td, th {
                      font-size: 15px;
                      line-height: 1.75;
                    }
                    p { margin: 0 0 1em; white-space: normal; }
                    ul, ol { padding-left: 1.5em; margin: 0.4em 0 1em; }
                    blockquote {
                      margin: 1em 0;
                      padding: 12px 16px;
                      border-left: 4px solid #93c5fd;
                      background: #eff6ff;
                      color: #334155;
                    }
                    hr {
                      border: none;
                      border-top: 1px solid #dbe3ef;
                      margin: 1.5em 0;
                    }
                    table {
                      width: 100%;
                      border-collapse: collapse;
                      margin: 1em 0 1.4em;
                    }
                    th, td {
                      border: 1px solid #dbe3ef;
                      padding: 10px 12px;
                      vertical-align: top;
                    }
                    th {
                      background: #eff6ff;
                      color: #0f172a;
                      font-weight: 600;
                    }
                    a { color: #2563eb; text-decoration: underline; }
                    code, pre {
                      font-family: "SFMono-Regular", "Consolas", "EasyFlowPdfCjk", "Noto Sans CJK SC", "Microsoft YaHei", monospace;
                    }
                    pre {
                      background: #f8fafc;
                      border: 1px solid #e2e8f0;
                      border-radius: 12px;
                      padding: 14px 16px;
                    }
                  </style>
                </head>
                <body>
                  <main class="document-shell">
                    <article class="document-paper">__BODY__</article>
                  </main>
                </body>
                </html>
                """
                .replace("__TITLE__", title)
                .replace("__BODY__", body);
    }

    private String buildBody(FileGenerationRequest request) {
        SourceFormat sourceFormat = SourceFormat.fromValue(request.getSourceFormat());
        return switch (sourceFormat) {
            case PLAIN_TEXT -> plainTextToHtml(request.getContent());
            case MARKDOWN -> htmlSanitizer.sanitize(markdownSupport.renderHtml(request.getContent()));
            case HTML -> htmlSanitizer.sanitize(request.getContent());
        };
    }

    private String plainTextToHtml(String content) {
        String normalized = content == null ? "" : content.replace("\r\n", "\n").replace('\r', '\n');
        String[] paragraphs = BLANK_LINE_PATTERN.split(normalized, -1);
        StringBuilder builder = new StringBuilder();
        for (String paragraph : paragraphs) {
            if (builder.length() > 0) {
                builder.append('\n');
            }
            String escaped = Entities.escape(paragraph);
            builder.append("<p>")
                    .append(escaped.replace("\n", "<br />"))
                    .append("</p>");
        }
        if (builder.length() == 0) {
            builder.append("<p></p>");
        }
        return builder.toString();
    }
}
