export function safeHttpUrl(input: string) {
  try {
    const url = new URL(input);
    if (!["http:", "https:"].includes(url.protocol)) return null;
    return url;
  } catch {
    return null;
  }
}

export function extractXhsPublishUrl(input: string) {
  const candidates =
    input.match(/https?:\/\/[^\s<>"'，。！？；：、【】（）]+/gi) ?? [];
  for (const candidate of candidates) {
    const cleaned = candidate.replace(/[.,!?;:~)\]}]+$/g, "");
    const url = safeHttpUrl(cleaned);
    if (!url) continue;
    const hostname = url.hostname.toLowerCase();
    const isXhs =
      hostname === "xiaohongshu.com" ||
      hostname.endsWith(".xiaohongshu.com") ||
      hostname === "xhslink.cn" ||
      hostname.endsWith(".xhslink.cn");
    if (isXhs) return url.toString();
  }
  return "";
}
