import { marked } from "marked";
import { UpyunAccess } from "~/utils/upyun";

marked.setOptions({ breaks: true, gfm: true });

/** 历史失败上传留在正文里的占位，避免继续污染渲染 */
export function stripBrokenCompressMarkdown(md: string): string {
  return md
    .replace(/!\[[^\]]*\]\(\s*failed to open file[^)]*\)/g, "")
    .replace(/\n{3,}/g, "\n\n");
}

/**
 * 窄屏编辑器可能把 `![](url)` 折成两行，GFM 无法识别，合并为单行。
 */
function normalizeMarkdownImageLineBreaks(md: string): string {
  return md.replace(/!\[([^\]]*)\]\s*\r?\n\s*\(/g, "![$1](");
}

/** 预览 / 首页：img 又拍直链需带 _upt */
export async function signUpyunImagesInMarkedHtml(html: string): Promise<string> {
  if (typeof document === "undefined" || !html.includes("<img")) {
    return html;
  }
  const wrap = document.createElement("div");
  wrap.innerHTML = html;
  const imgs = wrap.querySelectorAll("img[src]");
  await Promise.all(
    Array.from(imgs).map(async (el) => {
      const src = el.getAttribute("src");
      if (!src?.includes("upyun")) return;
      const signed = await UpyunAccess.getSign(src);
      if (signed) el.setAttribute("src", signed);
    }),
  );
  return wrap.innerHTML;
}

/** 机构首页 Markdown → 可展示的 HTML（含又拍图签名） */
export async function renderOrgHomepageMarkdown(markdown: string): Promise<string> {
  let cleaned = stripBrokenCompressMarkdown(markdown || "");
  cleaned = normalizeMarkdownImageLineBreaks(cleaned).trim();
  if (!cleaned) return "";
  const html = marked.parse(cleaned) as string;
  return signUpyunImagesInMarkedHtml(html);
}
