import map from "./legacy-image-map.json";

const LEGACY_MAP = map as Record<string, string>;

const LEGACY_HOSTS = [
  "https://www.broadcastbeat.com",
  "https://broadcastbeat.com",
  "http://www.broadcastbeat.com",
  "http://broadcastbeat.com",
];

export function rewriteLegacyImageUrl(url: string | null | undefined): string {
  if (!url) return "";
  // Direct map hit (canonical https://www.broadcastbeat.com/...)
  const direct = LEGACY_MAP[url];
  if (direct) return direct;
  // Try alternate-host normalization
  for (const host of LEGACY_HOSTS) {
    if (url.startsWith(host)) {
      const path = url.slice(host.length);
      const canonical = `https://www.broadcastbeat.com${path}`;
      const hit = LEGACY_MAP[canonical];
      if (hit) return hit;
    }
  }
  return url;
}

export function rewriteLegacyImageUrlsInHtml(html: string): string {
  return html.replace(
    /(https?:\/\/(?:www\.)?broadcastbeat\.com\/wp-content\/uploads\/[^"'\s)]+)/g,
    (m) => rewriteLegacyImageUrl(m),
  );
}
